[Python-checkins] r88635 - in python/branches/pep-3151: .gitignore .hgeol .hgignore Demo Doc/ACKS.txt Doc/Makefile Doc/README.txt Doc/c-api/arg.rst Doc/c-api/buffer.rst Doc/c-api/code.rst Doc/c-api/codec.rst Doc/c-api/exceptions.rst Doc/c-api/import.rst Doc/c-api/init.rst Doc/c-api/intro.rst Doc/c-api/list.rst Doc/c-api/module.rst Doc/c-api/object.rst Doc/c-api/slice.rst Doc/c-api/type.rst Doc/c-api/typeobj.rst Doc/c-api/unicode.rst Doc/c-api/utilities.rst Doc/c-api/veryhigh.rst Doc/conf.py Doc/copyright.rst Doc/distutils/apiref.rst Doc/distutils/uploading.rst Doc/documenting/markup.rst Doc/documenting/style.rst Doc/extending/embedding.rst Doc/extending/extending.rst Doc/extending/windows.rst Doc/faq/design.rst Doc/faq/extending.rst Doc/faq/gui.rst Doc/faq/installed.rst Doc/faq/library.rst Doc/faq/programming.rst Doc/glossary.rst Doc/howto/index.rst Doc/howto/logging-cookbook.rst Doc/howto/logging.rst Doc/howto/pyporting.rst Doc/howto/regex.rst Doc/howto/sorting.rst Doc/howto/unicode.rst Doc/howto/webservers.rst Doc/includes/email-mime.py Doc/includes/mp_newtype.py Doc/includes/sqlite3/adapter_point_1.py Doc/includes/sqlite3/adapter_point_2.py Doc/includes/sqlite3/converter_point.py Doc/includes/tzinfo-examples.py Doc/install/index.rst Doc/library/2to3.rst Doc/library/__future__.rst Doc/library/_dummy_thread.rst Doc/library/_thread.rst Doc/library/abc.rst Doc/library/aifc.rst Doc/library/allos.rst Doc/library/argparse.rst Doc/library/array.rst Doc/library/ast.rst Doc/library/asynchat.rst Doc/library/asyncore.rst Doc/library/atexit.rst Doc/library/base64.rst Doc/library/bdb.rst Doc/library/bisect.rst Doc/library/builtins.rst Doc/library/calendar.rst Doc/library/cgi.rst Doc/library/cmd.rst Doc/library/codecs.rst Doc/library/collections.abc.rst Doc/library/collections.rst Doc/library/colorsys.rst Doc/library/compileall.rst Doc/library/concurrent.futures.rst Doc/library/configparser.rst Doc/library/contextlib.rst Doc/library/crypt.rst Doc/library/csv.rst Doc/library/ctypes.rst Doc/library/curses.rst Doc/library/datatypes.rst Doc/library/datetime.rst Doc/library/dbm.rst Doc/library/decimal.rst Doc/library/difflib.rst Doc/library/dis.rst Doc/library/doctest.rst Doc/library/dummy_threading.rst Doc/library/email.charset.rst Doc/library/email.generator.rst Doc/library/email.header.rst Doc/library/email.message.rst Doc/library/email.util.rst Doc/library/exceptions.rst Doc/library/filecmp.rst Doc/library/fileformats.rst Doc/library/fileinput.rst Doc/library/fnmatch.rst Doc/library/fractions.rst Doc/library/ftplib.rst Doc/library/functional.rst Doc/library/functions.rst Doc/library/functools.rst Doc/library/getopt.rst Doc/library/gettext.rst Doc/library/glob.rst Doc/library/grp.rst Doc/library/gzip.rst Doc/library/hashlib.rst Doc/library/heapq.rst Doc/library/hmac.rst Doc/library/html.entities.rst Doc/library/html.parser.rst Doc/library/html.rst Doc/library/http.client.rst Doc/library/http.cookiejar.rst Doc/library/http.cookies.rst Doc/library/http.server.rst Doc/library/idle.rst Doc/library/imaplib.rst Doc/library/imghdr.rst Doc/library/imp.rst Doc/library/importlib.rst Doc/library/index.rst Doc/library/inspect.rst Doc/library/io.rst Doc/library/itertools.rst Doc/library/json.rst Doc/library/keyword.rst Doc/library/linecache.rst Doc/library/logging.config.rst Doc/library/logging.handlers.rst Doc/library/logging.rst Doc/library/mailbox.rst Doc/library/mailcap.rst Doc/library/mimetypes.rst Doc/library/modulefinder.rst Doc/library/msilib.rst Doc/library/multiprocessing.rst Doc/library/netrc.rst Doc/library/nntplib.rst Doc/library/numeric.rst Doc/library/operator.rst Doc/library/optparse.rst Doc/library/os.path.rst Doc/library/os.rst Doc/library/parser.rst Doc/library/pdb.rst Doc/library/pickle.rst Doc/library/pickletools.rst Doc/library/pipes.rst Doc/library/pkgutil.rst Doc/library/platform.rst Doc/library/plistlib.rst Doc/library/poplib.rst Doc/library/pprint.rst Doc/library/profile.rst Doc/library/pty.rst Doc/library/py_compile.rst Doc/library/pyclbr.rst Doc/library/pydoc.rst Doc/library/pyexpat.rst Doc/library/queue.rst Doc/library/quopri.rst Doc/library/random.rst Doc/library/re.rst Doc/library/reprlib.rst Doc/library/resource.rst Doc/library/rlcompleter.rst Doc/library/runpy.rst Doc/library/sched.rst Doc/library/select.rst Doc/library/shelve.rst Doc/library/shlex.rst Doc/library/shutil.rst Doc/library/site.rst Doc/library/smtpd.rst Doc/library/smtplib.rst Doc/library/sndhdr.rst Doc/library/socket.rst Doc/library/socketserver.rst Doc/library/someos.rst Doc/library/sqlite3.rst Doc/library/ssl.rst Doc/library/stat.rst Doc/library/stdtypes.rst Doc/library/string.rst Doc/library/struct.rst Doc/library/subprocess.rst Doc/library/sunau.rst Doc/library/symbol.rst Doc/library/sys.rst Doc/library/sysconfig.rst Doc/library/tabnanny.rst Doc/library/tarfile.rst Doc/library/telnetlib.rst Doc/library/tempfile.rst Doc/library/test.rst Doc/library/textwrap.rst Doc/library/threading.rst Doc/library/time.rst Doc/library/timeit.rst Doc/library/tkinter.rst Doc/library/tkinter.tix.rst Doc/library/token.rst Doc/library/tokenize.rst Doc/library/trace.rst Doc/library/turtle.rst Doc/library/types.rst Doc/library/unicodedata.rst Doc/library/unittest.rst Doc/library/urllib.parse.rst Doc/library/urllib.request.rst Doc/library/uu.rst Doc/library/warnings.rst Doc/library/wave.rst Doc/library/weakref.rst Doc/library/webbrowser.rst Doc/library/xdrlib.rst Doc/library/xml.dom.minidom.rst Doc/library/xml.dom.pulldom.rst Doc/library/xml.etree.elementtree.rst Doc/library/xmlrpc.client.rst Doc/library/xmlrpc.server.rst Doc/library/zipfile.rst Doc/library/zlib.rst Doc/license.rst Doc/make.bat Doc/reference/compound_stmts.rst Doc/reference/datamodel.rst Doc/reference/executionmodel.rst Doc/reference/expressions.rst Doc/reference/lexical_analysis.rst Doc/reference/simple_stmts.rst Doc/tools/sphinxext/download.html Doc/tools/sphinxext/indexcontent.html Doc/tools/sphinxext/indexsidebar.html Doc/tools/sphinxext/pyspecific.py Doc/tools/sphinxext/static/basic.css Doc/tools/sphinxext/susp-ignored.csv Doc/tutorial/inputoutput.rst Doc/tutorial/interpreter.rst Doc/tutorial/introduction.rst Doc/tutorial/stdlib.rst Doc/tutorial/stdlib2.rst Doc/using/cmdline.rst Doc/whatsnew/2.0.rst Doc/whatsnew/2.1.rst Doc/whatsnew/2.2.rst Doc/whatsnew/2.4.rst Doc/whatsnew/2.7.rst Doc/whatsnew/3.0.rst Doc/whatsnew/3.2.rst Doc/whatsnew/3.3.rst Doc/whatsnew/index.rst Include/Python.h Include/abstract.h Include/ast.h Include/bytearrayobject.h Include/bytes_methods.h Include/bytesobject.h Include/cellobject.h Include/ceval.h Include/classobject.h Include/code.h Include/codecs.h Include/compile.h Include/complexobject.h Include/datetime.h Include/descrobject.h Include/dictobject.h Include/dtoa.h Include/eval.h Include/fileobject.h Include/floatobject.h Include/frameobject.h Include/funcobject.h Include/genobject.h Include/import.h Include/listobject.h Include/longintrepr.h Include/longobject.h Include/marshal.h Include/memoryobject.h Include/methodobject.h Include/modsupport.h Include/moduleobject.h Include/object.h Include/objimpl.h Include/parsetok.h Include/patchlevel.h Include/pyarena.h Include/pyatomic.h Include/pycapsule.h Include/pyctype.h Include/pydebug.h Include/pyerrors.h Include/pygetopt.h Include/pymath.h Include/pyport.h Include/pystate.h Include/pystrtod.h Include/pythonrun.h Include/pythread.h Include/pytime.h Include/setobject.h Include/sliceobject.h Include/structseq.h Include/symtable.h Include/sysmodule.h Include/timefuncs.h Include/token.h Include/traceback.h Include/tupleobject.h Include/typeslots.h Include/ucnhash.h Include/unicodeobject.h Include/warnings.h Include/weakrefobject.h LICENSE Lib/_abcoll.py Lib/_pyio.py Lib/_weakrefset.py Lib/abc.py Lib/argparse.py Lib/ast.py Lib/asynchat.py Lib/asyncore.py Lib/base64.py Lib/bdb.py Lib/cgi.py Lib/codecs.py Lib/collections Lib/collections.py Lib/compileall.py Lib/concurrent/futures/_base.py Lib/concurrent/futures/process.py Lib/configparser.py Lib/contextlib.py Lib/crypt.py Lib/ctypes/test/test_callbacks.py Lib/ctypes/test/test_keeprefs.py Lib/ctypes/test/test_memfunctions.py Lib/ctypes/test/test_python_api.py Lib/ctypes/test/test_refcounts.py Lib/ctypes/test/test_stringptr.py Lib/datetime.py Lib/dbm/dumb.py Lib/decimal.py Lib/difflib.py Lib/distutils/__init__.py Lib/distutils/archive_util.py Lib/distutils/command/bdist_wininst.py Lib/distutils/command/build_ext.py Lib/distutils/command/install.py Lib/distutils/dir_util.py Lib/distutils/msvc9compiler.py Lib/distutils/sysconfig.py Lib/distutils/tests/test_archive_util.py Lib/distutils/tests/test_bdist.py Lib/distutils/tests/test_bdist_dumb.py Lib/distutils/tests/test_build.py Lib/distutils/tests/test_build_clib.py Lib/distutils/tests/test_build_ext.py Lib/distutils/tests/test_check.py Lib/distutils/tests/test_cmd.py Lib/distutils/tests/test_config.py Lib/distutils/tests/test_config_cmd.py Lib/distutils/tests/test_core.py Lib/distutils/tests/test_cygwinccompiler.py Lib/distutils/tests/test_dep_util.py Lib/distutils/tests/test_dir_util.py Lib/distutils/tests/test_dist.py Lib/distutils/tests/test_extension.py Lib/distutils/tests/test_file_util.py Lib/distutils/tests/test_filelist.py Lib/distutils/tests/test_install.py Lib/distutils/tests/test_install_data.py Lib/distutils/tests/test_install_headers.py Lib/distutils/tests/test_install_lib.py Lib/distutils/tests/test_log.py Lib/distutils/tests/test_msvc9compiler.py Lib/distutils/tests/test_register.py Lib/distutils/tests/test_sdist.py Lib/distutils/tests/test_spawn.py Lib/distutils/tests/test_sysconfig.py Lib/distutils/tests/test_text_file.py Lib/distutils/tests/test_upload.py Lib/distutils/tests/test_util.py Lib/distutils/tests/test_version.py Lib/doctest.py Lib/email/__init__.py Lib/email/_parseaddr.py Lib/email/charset.py Lib/email/generator.py Lib/email/header.py Lib/email/message.py Lib/email/test/test_email.py Lib/email/utils.py Lib/encodings/base64_codec.py Lib/encodings/bz2_codec.py Lib/encodings/hex_codec.py Lib/encodings/quopri_codec.py Lib/encodings/rot_13.py Lib/encodings/uu_codec.py Lib/encodings/zlib_codec.py Lib/fractions.py Lib/ftplib.py Lib/functools.py Lib/getpass.py Lib/gettext.py Lib/gzip.py Lib/hashlib.py Lib/html/parser.py Lib/http/client.py Lib/http/cookies.py Lib/http/server.py Lib/idlelib/Bindings.py Lib/idlelib/EditorWindow.py Lib/idlelib/FileList.py Lib/idlelib/IOBinding.py Lib/idlelib/PyShell.py Lib/idlelib/RemoteObjectBrowser.py Lib/idlelib/ScriptBinding.py Lib/idlelib/config-keys.def Lib/idlelib/idle.bat Lib/idlelib/idlever.py Lib/idlelib/macosxSupport.py Lib/imaplib.py Lib/importlib/_bootstrap.py Lib/importlib/abc.py Lib/importlib/test/import_/test___package__.py Lib/importlib/test/import_/test_caching.py Lib/importlib/test/import_/test_fromlist.py Lib/importlib/test/import_/test_meta_path.py Lib/inspect.py Lib/json/__init__.py Lib/json/tests Lib/lib2to3 Lib/lib2to3/__main__.py Lib/lib2to3/fixes/fix_urllib.py Lib/lib2to3/main.py Lib/lib2to3/refactor.py Lib/lib2to3/tests/test_refactor.py Lib/lib2to3/tests/test_util.py Lib/logging/__init__.py Lib/logging/handlers.py Lib/mailbox.py Lib/mimetypes.py Lib/multiprocessing/__init__.py Lib/multiprocessing/connection.py Lib/multiprocessing/dummy/__init__.py Lib/multiprocessing/dummy/connection.py Lib/multiprocessing/forking.py Lib/multiprocessing/heap.py Lib/multiprocessing/managers.py Lib/multiprocessing/pool.py Lib/multiprocessing/process.py Lib/multiprocessing/queues.py Lib/multiprocessing/reduction.py Lib/multiprocessing/sharedctypes.py Lib/multiprocessing/synchronize.py Lib/multiprocessing/util.py Lib/netrc.py Lib/numbers.py Lib/os.py Lib/pdb.py Lib/poplib.py Lib/pstats.py Lib/py_compile.py Lib/pyclbr.py Lib/pydoc.py Lib/pydoc_data/_pydoc.css Lib/pydoc_data/topics.py Lib/random.py Lib/reprlib.py Lib/shelve.py Lib/shutil.py Lib/site.py Lib/smtpd.py Lib/smtplib.py Lib/socket.py Lib/sqlite3/test/dbapi.py Lib/sqlite3/test/types.py Lib/sre_parse.py Lib/string.py Lib/struct.py Lib/subprocess.py Lib/sysconfig.py Lib/tabnanny.py Lib/tarfile.py Lib/telnetlib.py Lib/tempfile.py Lib/test/__main__.py Lib/test/buffer_tests.py Lib/test/cmath_testcases.txt Lib/test/crashers/README Lib/test/crashers/underlying_dict.py Lib/test/datetimetester.py Lib/test/decimaltestdata/abs.decTest Lib/test/decimaltestdata/add.decTest Lib/test/decimaltestdata/base.decTest Lib/test/decimaltestdata/clamp.decTest Lib/test/decimaltestdata/compare.decTest Lib/test/decimaltestdata/decDouble.decTest Lib/test/decimaltestdata/decQuad.decTest Lib/test/decimaltestdata/decSingle.decTest Lib/test/decimaltestdata/divide.decTest Lib/test/decimaltestdata/divideint.decTest Lib/test/decimaltestdata/inexact.decTest Lib/test/decimaltestdata/max.decTest Lib/test/decimaltestdata/min.decTest Lib/test/decimaltestdata/minus.decTest Lib/test/decimaltestdata/multiply.decTest Lib/test/decimaltestdata/plus.decTest Lib/test/decimaltestdata/power.decTest Lib/test/decimaltestdata/quantize.decTest Lib/test/decimaltestdata/randomBound32.decTest Lib/test/decimaltestdata/randoms.decTest Lib/test/decimaltestdata/reduce.decTest Lib/test/decimaltestdata/remainder.decTest Lib/test/decimaltestdata/remainderNear.decTest Lib/test/decimaltestdata/rescale.decTest Lib/test/decimaltestdata/rounding.decTest Lib/test/decimaltestdata/samequantum.decTest Lib/test/decimaltestdata/squareroot.decTest Lib/test/decimaltestdata/subtract.decTest Lib/test/decimaltestdata/testall.decTest Lib/test/decimaltestdata/tointegral.decTest Lib/test/fork_wait.py Lib/test/json_tests Lib/test/list_tests.py Lib/test/lock_tests.py Lib/test/outstanding_bugs.py Lib/test/pickletester.py Lib/test/pydoc_mod.py Lib/test/pystone.py Lib/test/regrtest.py Lib/test/script_helper.py Lib/test/seq_tests.py Lib/test/sha256.pem Lib/test/string_tests.py Lib/test/subprocessdata Lib/test/support.py Lib/test/symlink_support.py Lib/test/test__locale.py Lib/test/test_abc.py Lib/test/test_argparse.py Lib/test/test_array.py Lib/test/test_ast.py Lib/test/test_asyncore.py Lib/test/test_atexit.py Lib/test/test_augassign.py Lib/test/test_base64.py Lib/test/test_bigaddrspace.py Lib/test/test_bigmem.py Lib/test/test_bool.py Lib/test/test_builtin.py Lib/test/test_bytes.py Lib/test/test_bz2.py Lib/test/test_calendar.py Lib/test/test_capi.py Lib/test/test_cfgparser.py Lib/test/test_cgi.py Lib/test/test_charmapcodec.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_codecs.py Lib/test/test_codeop.py Lib/test/test_collections.py Lib/test/test_compileall.py Lib/test/test_complex.py Lib/test/test_concurrent_futures.py Lib/test/test_configparser.py Lib/test/test_contextlib.py Lib/test/test_copyreg.py Lib/test/test_crypt.py Lib/test/test_csv.py Lib/test/test_dbm.py Lib/test/test_dbm_gnu.py Lib/test/test_decimal.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_epoll.py Lib/test/test_exceptions.py Lib/test/test_file.py Lib/test/test_fileio.py Lib/test/test_float.py Lib/test/test_fork1.py Lib/test/test_fractions.py Lib/test/test_frozen.py Lib/test/test_functools.py Lib/test/test_gc.py Lib/test/test_gdb.py Lib/test/test_genexps.py Lib/test/test_getargs2.py Lib/test/test_getopt.py Lib/test/test_glob.py Lib/test/test_grp.py Lib/test/test_gzip.py Lib/test/test_hashlib.py Lib/test/test_htmlparser.py Lib/test/test_http_cookiejar.py Lib/test/test_http_cookies.py Lib/test/test_httplib.py Lib/test/test_httpservers.py Lib/test/test_imaplib.py Lib/test/test_imp.py Lib/test/test_import.py Lib/test/test_inspect.py Lib/test/test_int.py Lib/test/test_io.py Lib/test/test_ioctl.py Lib/test/test_isinstance.py Lib/test/test_itertools.py Lib/test/test_json.py Lib/test/test_keywordonlyarg.py Lib/test/test_kqueue.py Lib/test/test_linecache.py Lib/test/test_listcomps.py Lib/test/test_logging.py Lib/test/test_long.py Lib/test/test_mailbox.py Lib/test/test_marshal.py Lib/test/test_math.py Lib/test/test_memoryio.py Lib/test/test_memoryview.py Lib/test/test_metaclass.py Lib/test/test_minidom.py Lib/test/test_mmap.py Lib/test/test_multiprocessing.py Lib/test/test_netrc.py Lib/test/test_nntplib.py Lib/test/test_normalization.py Lib/test/test_ntpath.py Lib/test/test_opcodes.py Lib/test/test_operator.py Lib/test/test_optparse.py Lib/test/test_os.py Lib/test/test_parser.py Lib/test/test_pdb.py Lib/test/test_pep247.py Lib/test/test_pep263.py Lib/test/test_pep3120.py Lib/test/test_pep3131.py Lib/test/test_pickle.py Lib/test/test_pickletools.py Lib/test/test_platform.py Lib/test/test_poplib.py Lib/test/test_posix.py Lib/test/test_posixpath.py Lib/test/test_pow.py Lib/test/test_pty.py Lib/test/test_pyclbr.py Lib/test/test_pydoc.py Lib/test/test_pyexpat.py Lib/test/test_queue.py Lib/test/test_random.py Lib/test/test_range.py Lib/test/test_reprlib.py Lib/test/test_resource.py Lib/test/test_richcmp.py Lib/test/test_runpy.py Lib/test/test_sax.py Lib/test/test_scope.py Lib/test/test_shelve.py Lib/test/test_shutil.py Lib/test/test_signal.py Lib/test/test_site.py Lib/test/test_slice.py Lib/test/test_smtpd.py Lib/test/test_smtplib.py Lib/test/test_socket.py Lib/test/test_socketserver.py Lib/test/test_ssl.py Lib/test/test_strlit.py Lib/test/test_struct.py Lib/test/test_structmembers.py Lib/test/test_subprocess.py Lib/test/test_sys.py Lib/test/test_sys_settrace.py Lib/test/test_sysconfig.py Lib/test/test_syslog.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_threadsignals.py Lib/test/test_time.py Lib/test/test_timeout.py Lib/test/test_tokenize.py Lib/test/test_trace.py Lib/test/test_traceback.py Lib/test/test_ttk_guionly.py Lib/test/test_tuple.py Lib/test/test_types.py Lib/test/test_ucn.py Lib/test/test_unicode.py Lib/test/test_unicodedata.py Lib/test/test_unittest.py Lib/test/test_urllib.py Lib/test/test_urllib2.py Lib/test/test_urllibnet.py Lib/test/test_urlparse.py Lib/test/test_uuid.py Lib/test/test_warnings.py Lib/test/test_weakset.py Lib/test/test_winreg.py Lib/test/test_winsound.py Lib/test/test_with.py Lib/test/test_wsgiref.py Lib/test/test_xml_etree.py Lib/test/test_xml_etree_c.py Lib/test/test_xmlrpc.py Lib/test/test_xmlrpc_net.py Lib/test/test_zipfile.py Lib/test/test_zipimport.py Lib/test/test_zipimport_support.py Lib/test/test_zlib.py Lib/test/win_console_handler.py Lib/test/zip_cp437_header.zip Lib/threading.py Lib/tkinter/__init__.py Lib/tkinter/scrolledtext.py Lib/tkinter/test/test_tkinter/test_loadtk.py Lib/tkinter/test/test_ttk/test_widgets.py Lib/tkinter/tix.py Lib/token.py Lib/tokenize.py Lib/trace.py Lib/turtle.py Lib/turtledemo/__main__.py Lib/turtledemo/about_turtledemo.txt Lib/turtledemo/demohelp.txt Lib/unittest/case.py Lib/unittest/loader.py Lib/unittest/main.py Lib/unittest/runner.py Lib/unittest/suite.py Lib/unittest/test/_test_warnings.py Lib/unittest/test/test_assertions.py Lib/unittest/test/test_break.py Lib/unittest/test/test_case.py Lib/unittest/test/test_discovery.py Lib/unittest/test/test_functiontestcase.py Lib/unittest/test/test_loader.py Lib/unittest/test/test_program.py Lib/unittest/test/test_runner.py Lib/unittest/test/test_setups.py Lib/unittest/test/test_suite.py Lib/unittest/util.py Lib/urllib/parse.py Lib/urllib/request.py Lib/wave.py Lib/weakref.py Lib/webbrowser.py Lib/wsgiref/handlers.py Lib/wsgiref/util.py Lib/xml/etree/ElementTree.py Lib/xmlrpc/client.py Lib/zipfile.py Mac/BuildScript/README.txt Mac/BuildScript/build-installer.py Mac/BuildScript/resources/ReadMe.txt Mac/BuildScript/resources/Welcome.rtf Mac/BuildScript/scripts/postflight.documentation Mac/Extras.ReadMe.txt Mac/IDLE/IDLE.app/Contents/Info.plist Mac/IDLE/idlemain.py Mac/Makefile.in Mac/PythonLauncher/Info.plist.in Mac/README Mac/Resources/app/Info.plist.in Mac/Resources/framework/Info.plist.in Makefile.pre.in Misc/ACKS Misc/AIX-NOTES Misc/NEWS Misc/PURIFY.README Misc/README Misc/README.AIX Misc/README.Emacs Misc/README.OpenBSD Misc/README.klocwork Misc/RFD Misc/RPM/python-3.2.spec Misc/RPM/python-3.3.spec Misc/SpecialBuilds.txt Misc/cheatsheet Misc/developers.txt Misc/indent.pro Misc/maintainers.rst Misc/pymemcompat.h Misc/python-wing4.wpr Misc/python.man Misc/python.pc.in Misc/setuid-prog.c Modules/Setup.dist Modules/_collectionsmodule.c Modules/_cryptmodule.c Modules/_ctypes/_ctypes.c Modules/_ctypes/_ctypes_test.c Modules/_ctypes/cfield.c Modules/_ctypes/libffi_msvc/ffi.c Modules/_datetimemodule.c Modules/_elementtree.c Modules/_functoolsmodule.c Modules/_gdbmmodule.c Modules/_io/bufferedio.c Modules/_io/bytesio.c Modules/_io/fileio.c Modules/_io/textio.c Modules/_json.c Modules/_lsprof.c Modules/_multiprocessing/multiprocessing.h Modules/_pickle.c Modules/_posixsubprocess.c Modules/_sqlite/connection.c Modules/_sqlite/cursor.c Modules/_sqlite/module.c Modules/_sqlite/statement.c Modules/_ssl.c Modules/_struct.c Modules/_testcapimodule.c Modules/_threadmodule.c Modules/_tkinter.c Modules/arraymodule.c Modules/atexitmodule.c Modules/audioop.c Modules/cjkcodecs/_codecs_iso2022.c Modules/cjkcodecs/multibytecodec.c Modules/cryptmodule.c Modules/gcmodule.c Modules/getpath.c Modules/grpmodule.c Modules/itertoolsmodule.c Modules/ld_so_aix.in Modules/main.c Modules/md5module.c Modules/mmapmodule.c Modules/parsermodule.c Modules/posixmodule.c Modules/pwdmodule.c Modules/pyexpat.c Modules/readline.c Modules/resource.c Modules/selectmodule.c Modules/sha1module.c Modules/sha256module.c Modules/sha512module.c Modules/signalmodule.c Modules/socketmodule.c Modules/socketmodule.h Modules/spwdmodule.c Modules/symtablemodule.c Modules/syslogmodule.c Modules/termios.c Modules/timemodule.c Modules/unicodedata.c Modules/xxlimited.c Modules/zipimport.c Modules/zlibmodule.c Objects/abstract.c Objects/bytearrayobject.c Objects/bytesobject.c Objects/codeobject.c Objects/complexobject.c Objects/descrobject.c Objects/dictobject.c Objects/fileobject.c Objects/floatobject.c Objects/funcobject.c Objects/genobject.c Objects/listobject.c Objects/longobject.c Objects/memoryobject.c Objects/moduleobject.c Objects/object.c Objects/obmalloc.c Objects/rangeobject.c Objects/setobject.c Objects/sliceobject.c Objects/stringlib/formatter.h Objects/stringlib/string_format.h Objects/structseq.c Objects/tupleobject.c Objects/typeobject.c Objects/typeslots.inc Objects/typeslots.py Objects/unicodectype.c Objects/unicodeobject.c Objects/weakrefobject.c PC PC/VC6/pythoncore.dsp PC/VC6/readme.txt PC/VS7.1/build_ssl.bat PC/VS7.1/pythoncore.vcproj PC/VS7.1/readme.txt PC/VS8.0/build.bat PC/VS8.0/build_env.bat PC/VS8.0/build_pgo.bat PC/VS8.0/build_ssl.bat PC/VS8.0/env.bat PC/VS8.0/idle.bat PC/VS8.0/kill_python.c PC/VS8.0/pyproject.vsprops PC/VS8.0/rt.bat PC/bdist_wininst/wininst.dsp PC/bdist_wininst/wininst.dsw PC/example_nt/example.vcproj PC/getpathp.c PC/import_nt.c PC/os2emx/Makefile PC/os2emx/README.os2emx PC/os2emx/python27.def PC/os2emx/python33.def PC/pyconfig.h PC/python3.def PC/python3.mak PC/python33gen.py PC/python33stub.def PC/python3dll.c PC/python_nt.rc PCbuild/build_ssl.bat PCbuild/build_tkinter.py PCbuild/kill_python.c PCbuild/make_buildinfo.c PCbuild/pcbuild.sln PCbuild/pyproject.vsprops PCbuild/python3dll.vcproj PCbuild/pythoncore.vcproj PCbuild/readme.txt PCbuild/xxlimited.vcproj Parser/asdl_c.py Parser/parsetok.c Parser/pgenmain.c Parser/printgrammar.c Parser/tokenizer.c Python/Python-ast.c Python/_warnings.c Python/ast.c Python/bltinmodule.c Python/ceval.c Python/ceval_gil.h Python/compile.c Python/dtoa.c Python/dynload_aix.c Python/dynload_dl.c Python/dynload_hpux.c Python/dynload_next.c Python/dynload_os2.c Python/dynload_shlib.c Python/dynload_win.c Python/errors.c Python/future.c Python/getargs.c Python/getcopyright.c Python/import.c Python/importdl.c Python/peephole.c Python/pyarena.c Python/pystrtod.c Python/pythonrun.c Python/sysmodule.c Python/thread_nt.h Python/thread_pthread.h Python/traceback.c README Tools/README Tools/buildbot/build-amd64.bat Tools/buildbot/build.bat Tools/buildbot/buildmsi.bat Tools/buildbot/clean-amd64.bat Tools/buildbot/clean.bat Tools/buildbot/external-amd64.bat Tools/buildbot/external-common.bat Tools/buildbot/external.bat Tools/buildbot/test-amd64.bat Tools/buildbot/test.bat Tools/ccbench/ccbench.py Tools/demo Tools/framer Tools/msi/msi.py Tools/msi/uuids.py Tools/parser Tools/scripts/README Tools/scripts/abitype.py Tools/scripts/find-uname.py Tools/scripts/find_recursionlimit.py Tools/scripts/get-remote-certificate.py Tools/scripts/patchcheck.py Tools/scripts/redemo.py Tools/scripts/untabify.py Tools/ssl Tools/test2to3 Tools/unicode/gencodec.py Tools/unicode/genwincodecs.bat Tools/unicode/makeunicodedata.py Tools/unittestgui Tools/world configure configure.in pyconfig.h.in runtests.sh setup.py

antoine.pitrou python-checkins at python.org
Sat Feb 26 08:16:43 CET 2011


Author: antoine.pitrou
Date: Sat Feb 26 08:16:32 2011
New Revision: 88635

Log:
Merged revisions 86409-86410,86413-86414,86417,86419,86422,86424-86425,86427-86431,86435,86438,86441-86446,86448-86451,86463,86467,86478-86480,86484-86488,86491-86493,86498-86501,86504,86506-86511,86513-86514,86516-86517,86520-86521,86523,86525-86526,86528,86530,86533,86535,86537-86538,86540,86542,86544-86545,86547-86553,86555,86561-86562,86564-86567,86570-86580,86583-86585,86587,86592-86596,86598,86601,86603,86605,86607-86608,86610-86611,86614,86617-86626,86630-86636,86638-86642,86645-86651,86654-86655,86660-86662,86665,86668-86671,86676,86679,86681,86684,86689-86690,86693-86694,86697,86699-86702,86705,86708,86713,86717,86720,86725,86727,86729-86734,86737,86743-86747,86750-86751,86758-86759,86791,86794-86795,86797-86801,86804,86808,86819,86823-86825,86828-86829,86837-86839,86842-86845,86854-86857,86861,86864,86867-86870,86874-86875,86878-86884,86887-86893,86895-86896,86901-86903,86905-86925,86928-86937,86940,86943-86971,86974-86977,86979-86981,86983-86986,86993,86996-87004,87007-87014,87017-87032,87036,87038-87045,87047-87048,87050-87052,87054,87056-87060,87062-87084,87086,87088,87093-87094,87101-87110,87112-87119,87124-87137,87140-87141,87145-87161,87171-87177,87179-87186,87188-87194,87197-87198,87201-87210,87212-87217,87221-87222,87225,87228-87230,87233,87236,87238,87241,87245-87248,87251,87256,87258,87260-87277,87280,87283-87284,87288-87289,87292-87304,87306,87312,87315-87317,87323-87324,87327-87329,87337-87341,87344-87346,87348,87350-87356,87359-87368,87371-87374,87377-87378,87381,87384,87389-87400,87402-87403,87408,87411,87415,87418,87421,87424-87427,87430,87433,87435-87443,87445-87448,87451,87454-87455,87458-87463,87466-87479,87482-87483,87485-87486,87489,87492-87493,87496-87498,87501,87504-87508,87512-87514,87516-87539,87542,87547-87550,87553,87556-87564,87567,87569,87571,87573,87575,87577,87579-87590,87593-87595,87598,87601,87603-87604,87606-87607,87610-87612,87615,87627-87628,87638-87639,87642,87646,87648,87651,87653-87657,87665-87667,87671-87673,87677-87689,87691,87695,87698,87703-87705,87710-87714,87716-87722,87728-87740,87744,87746-87750,87753-87762,87765-87769,87771-87784,87786-87792,87795-87797,87802,87805-87808,87810-87813,87820-87835,87838-87840,87843-87850,87853,87856,87858-87863,87865,87867-87871,87873,87876-87877,87890-87891,87895-87904,87906-87908,87910-87912,87914-87917,87919-87922,87924-87926,87938-87943,87946-87949,87952-87954,87957-87958,87960,87966,87968-87969,87971-87975,87978,87980-87984,87986,87988-87991,87993,87996-88001,88003-88009,88011-88018,88021-88022,88026,88028,88032-88033,88035-88036,88040-88044,88047-88058,88063,88066,88069,88072-88080,88083-88085,88092-88094,88097,88100-88109,88111,88114-88115,88117-88122,88125-88131,88134-88137,88139-88147,88149-88166,88170-88172,88174,88176,88178-88188,88191,88196-88201,88203-88204,88207,88209-88215,88220-88223,88226,88228,88230-88232,88234-88236,88239-88240,88244-88247,88251-88252,88256,88258-88259,88261,88263-88266,88271-88276,88280-88281,88284,88299,88301-88302,88322,88329-88334,88337,88340-88352,88355-88371,88374-88375,88377,88381-88389,88394-88396,88399-88403,88407,88411-88413,88420-88421,88423-88424,88426,88430-88432,88434-88435,88438-88445,88447-88449,88451,88456,88459-88460,88463-88467,88470,88474-88476,88478,88480-88481,88484,88486,88490-88494,88496,88498,88500-88501,88503,88505-88507,88511-88513,88515-88517,88519-88521,88523-88525,88527-88528,88530,88533-88534,88538-88541,88545-88546,88550,88552-88554,88558,88567,88574-88581,88584-88589,88602-88604,88607-88610,88613,88616,88618-88622,88624-88632 via svnmerge from 
svn+ssh://pythondev@svn.python.org/python/branches/py3k

................
  r86409 | georg.brandl | 2010-11-11 08:26:40 +0100 (jeu., 11 nov. 2010) | 1 line
  
  Review the new configparser docs.
................
  r86410 | alexander.belopolsky | 2010-11-11 15:07:41 +0100 (jeu., 11 nov. 2010) | 4 lines
  
  Issue #10386: Added __all__ to token module; this simplifies importing
  in tokenize module and prevents leaking of private names through
  import *.
................
  r86413 | lukasz.langa | 2010-11-11 20:53:23 +0100 (jeu., 11 nov. 2010) | 4 lines
  
  configparser.py: changed PendingDeprecationWarnings to DeprecationWarnings, via http://mail.python.org/pipermail/python-dev/2010-November/105391.html
  configparser:py: renamed _views to _proxies to be consistent with the SectionProxy name
................
  r86414 | r.david.murray | 2010-11-11 21:09:20 +0100 (jeu., 11 nov. 2010) | 8 lines
  
  #1466065: add validate option to base64.b64decode
  
  Patch by Neil Tallim.  This provides a mechanism for module
  users to achieve RFC 3548 compliance in the cases where ignoring
  non-base64-alphabet input characters is *not* mandated by the RFC that
  references RFC 3548.
................
  r86417 | alexander.belopolsky | 2010-11-11 23:43:45 +0100 (jeu., 11 nov. 2010) | 1 line
  
  Issue #10389: Documented rules for use of case in section titles.
................
  r86419 | r.david.murray | 2010-11-12 01:35:31 +0100 (ven., 12 nov. 2010) | 4 lines
  
  #7950: add warning about security implications of shell=True to subprocess docs
  
  Patch by Chris Rebert.
................
  r86422 | terry.reedy | 2010-11-12 05:22:22 +0100 (ven., 12 nov. 2010) | 1 line
................
  r86424 | georg.brandl | 2010-11-12 07:19:48 +0100 (ven., 12 nov. 2010) | 1 line
  
  Build a PDF of the FAQs too.
................
  r86425 | georg.brandl | 2010-11-12 07:20:12 +0100 (ven., 12 nov. 2010) | 1 line
  
  #10008: Fix duplicate index entry.
................
  r86427 | georg.brandl | 2010-11-12 09:09:11 +0100 (ven., 12 nov. 2010) | 1 line
  
  Switch to Sphinx 1.0.5.
................
  r86428 | georg.brandl | 2010-11-12 09:09:26 +0100 (ven., 12 nov. 2010) | 1 line
  
  Fix weird line block in table.
................
  r86429 | georg.brandl | 2010-11-12 09:57:12 +0100 (ven., 12 nov. 2010) | 1 line
  
  Add a deprecated-removed directive that allows to give the version of removal for deprecations.
................
  r86430 | martin.v.loewis | 2010-11-12 18:20:02 +0100 (ven., 12 nov. 2010) | 2 lines
  
  Add UUID for 3.2a4
................
  r86431 | antoine.pitrou | 2010-11-12 19:49:16 +0100 (ven., 12 nov. 2010) | 4 lines
  
  Issue #4471: Add the IMAP.starttls() method to enable encryption on
  standard IMAP4 connections.  Original patch by Lorenzo M. Catucci.
................
  r86435 | andrew.kuchling | 2010-11-12 21:54:47 +0100 (ven., 12 nov. 2010) | 1 line
  
  Remove myself as a maintainer for curses and mailbox modules.
................
  r86438 | eric.araujo | 2010-11-12 23:25:23 +0100 (ven., 12 nov. 2010) | 2 lines
  
  And now for something completely different: Finish fixing #10252 again.
................
  r86441 | antoine.pitrou | 2010-11-13 01:28:53 +0100 (sam., 13 nov. 2010) | 4 lines
  
  Switch from gmane to another provider for NNTP tests (as gmane isn't reliable
  enough).  Also, use setUpClass in order to connect only once per test run.
................
  r86442 | fred.drake | 2010-11-13 05:24:26 +0100 (sam., 13 nov. 2010) | 2 lines
  
  use appropriate markup
................
  r86443 | fred.drake | 2010-11-13 06:24:17 +0100 (sam., 13 nov. 2010) | 2 lines
  
  fix copy-editing level nits
................
  r86444 | georg.brandl | 2010-11-13 07:36:58 +0100 (sam., 13 nov. 2010) | 1 line
  
  Update pydoc topics.
................
  r86445 | georg.brandl | 2010-11-13 07:38:37 +0100 (sam., 13 nov. 2010) | 1 line
  
  Ignore suspicious-ignore file.
................
  r86446 | georg.brandl | 2010-11-13 07:39:58 +0100 (sam., 13 nov. 2010) | 1 line
  
  Bump to 3.2a4.
................
  r86448 | mark.dickinson | 2010-11-13 11:27:38 +0100 (sam., 13 nov. 2010) | 1 line
  
  Make Fraction(-1).__hash__() return -2 rather than -1 (see issue 10356).
................
  r86449 | mark.dickinson | 2010-11-13 11:43:40 +0100 (sam., 13 nov. 2010) | 1 line
  
  Streamline a cmath test (and fix some overlong lines into the bargain).
................
  r86450 | senthil.kumaran | 2010-11-13 13:27:49 +0100 (sam., 13 nov. 2010) | 3 lines
  
  Fix Issue5111 -  Wrap the Ipv6 host with [] in the Host header
................
  r86451 | georg.brandl | 2010-11-13 14:25:40 +0100 (sam., 13 nov. 2010) | 1 line
  
  Minor edits.
................
  r86463 | raymond.hettinger | 2010-11-14 06:27:15 +0100 (dim., 14 nov. 2010) | 1 line
  
  Issue 10410:  An iterable is not necessarily a container.
................
  r86467 | vinay.sajip | 2010-11-14 22:33:04 +0100 (dim., 14 nov. 2010) | 1 line
  
  Logging: added stack_info argument.
................
  r86478 | alexander.belopolsky | 2010-11-16 15:29:01 +0100 (mar., 16 nov. 2010) | 1 line
  
  Issue #10413: Updated comments to reflect code changes
................
  r86479 | georg.brandl | 2010-11-16 16:15:29 +0100 (mar., 16 nov. 2010) | 1 line
  
  Add stub for PEP 3148.
................
  r86480 | georg.brandl | 2010-11-16 16:15:56 +0100 (mar., 16 nov. 2010) | 1 line
  
  Post-release bumps.
................
  r86484 | antoine.pitrou | 2010-11-16 18:49:46 +0100 (mar., 16 nov. 2010) | 3 lines
  
  Avoid some BytesWarnings when running test_imaplib in verbose mode
................
  r86485 | antoine.pitrou | 2010-11-16 18:55:26 +0100 (mar., 16 nov. 2010) | 4 lines
  
  Issue #10429: IMAP.starttls() stored the capabilities as bytes objects,
  rather than strings.
................
  r86486 | eric.araujo | 2010-11-16 20:13:50 +0100 (mar., 16 nov. 2010) | 4 lines
  
  Provide links to Python source where the code is short, readable and
  informative adjunct to the docs.  Forward-port of Raymond's r86225 and
  r86245 using the new source reST role added in #10334.
................
  r86487 | matthias.klose | 2010-11-16 21:07:51 +0100 (mar., 16 nov. 2010) | 2 lines
  
  Modules/_io/bufferedio.c (buffered_dealloc_warn): Make it static.
................
  r86488 | ezio.melotti | 2010-11-16 21:57:59 +0100 (mar., 16 nov. 2010) | 1 line
  
  Fix typo
................
  r86491 | brian.quinlan | 2010-11-17 12:06:29 +0100 (mer., 17 nov. 2010) | 1 line
  
  Removes an inefficient spin loop in as_completed
................
  r86492 | stefan.krah | 2010-11-17 12:16:34 +0100 (mer., 17 nov. 2010) | 3 lines
  
  Issue #10356: Decimal(-1).__hash__() should equal hash(Decimal(-1)).
................
  r86493 | antoine.pitrou | 2010-11-17 17:19:35 +0100 (mer., 17 nov. 2010) | 4 lines
  
  Issue #10440: Support RUSAGE_THREAD as a constant in the resource module.
  Patch by Robert Collins.
................
  r86498 | antoine.pitrou | 2010-11-17 21:29:42 +0100 (mer., 17 nov. 2010) | 3 lines
  
  Issue #10443: Add the SSLContext.set_default_verify_paths() method.
................
  r86499 | david.malcolm | 2010-11-17 22:20:18 +0100 (mer., 17 nov. 2010) | 6 lines
  
  Issue #9518: Extend the PyModuleDef_HEAD_INIT macro to explicitly
  zero-initialize all fields, fixing compiler warnings seen when building
  extension modules with gcc with "-Wmissing-field-initializers" (implied
  by "-W")
................
  r86500 | antoine.pitrou | 2010-11-17 22:55:41 +0100 (mer., 17 nov. 2010) | 3 lines
  
  Use laxer timeouts in barrier tests
................
  r86501 | benjamin.peterson | 2010-11-17 23:33:12 +0100 (mer., 17 nov. 2010) | 1 line
  
  handle dict subclasses gracefully in PyArg_ValidateKeywordArguments
................
  r86504 | alexander.belopolsky | 2010-11-18 02:52:54 +0100 (jeu., 18 nov. 2010) | 15 lines
  
  Issue #10446: Several changes to module documentation generated by pydoc:
  
  1. Online reference manual link is now version-specific and the
     'MODULE DOCS' section renamed to 'MODULE REFERENCE'.
  
  2. 'FILE' section is moved to the end of the file.
  
  3. Special names processed by pydoc such as __version__ or __credits__
     are now excluded from the DATA section.
  
  4. Defined __all__ to prevent pydoc from exposing undocumented details
     about itself.
  
  5. Removed Python 2.3 compatibility code.
................
  r86506 | brian.curtin | 2010-11-18 03:15:28 +0100 (jeu., 18 nov. 2010) | 2 lines
  
  Fix #8886. Use context managers throughout the test.
................
  r86507 | brett.cannon | 2010-11-18 04:03:04 +0100 (jeu., 18 nov. 2010) | 5 lines
  
  Fix a minor inconsistency in capitalization for the 'No module named' exception
  message in importlib.
  
  Thanks to Éric Araujo for spotting the inconsistency.
................
  r86508 | alexander.belopolsky | 2010-11-18 04:50:18 +0100 (jeu., 18 nov. 2010) | 1 line
  
  Issue #10446 NEWS entry
................
  r86509 | michael.foord | 2010-11-18 12:02:50 +0100 (jeu., 18 nov. 2010) | 1 line
  
  Remove duplicate period from reference doc
................
  r86510 | kristjan.jonsson | 2010-11-18 13:46:39 +0100 (jeu., 18 nov. 2010) | 2 lines
  
  Issue 10260
  Adding the wait_for() method to threading.Condition
................
  r86511 | benjamin.peterson | 2010-11-18 15:14:43 +0100 (jeu., 18 nov. 2010) | 1 line
  
  reduce try block compass
................
  r86513 | eric.araujo | 2010-11-18 15:22:08 +0100 (jeu., 18 nov. 2010) | 2 lines
  
  Remove spurious space that was breaking Vim’s reST highlighting.
................
  r86514 | senthil.kumaran | 2010-11-18 16:00:53 +0100 (jeu., 18 nov. 2010) | 3 lines
  
  Fix Issue 9991: xmlrpc client ssl check faulty
................
  r86516 | antoine.pitrou | 2010-11-18 16:11:43 +0100 (jeu., 18 nov. 2010) | 3 lines
  
  Make test_nntplib more robust when the "last" article in a group can't be retrieved
................
  r86517 | stefan.krah | 2010-11-18 16:20:34 +0100 (jeu., 18 nov. 2010) | 3 lines
  
  Issue #10356: hash(Decimal("sNaN")) now raises ValueError instead of TypeError.
................
  r86520 | senthil.kumaran | 2010-11-18 16:36:41 +0100 (jeu., 18 nov. 2010) | 3 lines
  
  Fix Issue2244 - urllib unquotes user and password info multiple times - Patch by Theodore Turocy
................
  r86521 | eric.araujo | 2010-11-18 17:38:46 +0100 (jeu., 18 nov. 2010) | 17 lines
  
  Fix usage of :option: in the docs (#9312).
  
  :option: is used to create a link to an option of python, not to mark
  up any instance of any arbitrary command-line option.  These were
  changed to ````.
  
  For modules which do have a command-line interface, lists of options
  have been properly marked up with the program/cmdoption directives
  combo.  Options defined in such blocks can be linked to with :option:
  later in the same file, they won’t link to an option of python.
  
  Finally, the markup of command-line fragments in optparse.rst has
  been cleaned to use ``x`` instead of ``"x"``, keeping that latter
  form for actual Python strings.
  
  Patch by Eli Bendersky and Éric Araujo.
................
  r86523 | senthil.kumaran | 2010-11-18 18:08:48 +0100 (jeu., 18 nov. 2010) | 3 lines
  
  Code Changes as per review comments by Antoine Pitrou.
................
  r86525 | antoine.pitrou | 2010-11-18 18:29:23 +0100 (jeu., 18 nov. 2010) | 5 lines
  
  Wrap all test_nntplib methods accessing a remote server in a transient_internet()
  exception catcher.  Wrapping the initial connection routine is not sufficient
  as network timeouts can then occur as part of NNTP commands.
................
  r86526 | alexander.belopolsky | 2010-11-18 19:50:13 +0100 (jeu., 18 nov. 2010) | 1 line
  
  Issue 7828: Fixed chr() and ord() documentation for wide characters
................
  r86528 | ezio.melotti | 2010-11-18 20:48:27 +0100 (jeu., 18 nov. 2010) | 1 line
  
  #10455: fix typo
................
  r86530 | alexander.belopolsky | 2010-11-19 17:09:58 +0100 (ven., 19 nov. 2010) | 1 line
  
  Issue #4153: Updated Unicode HOWTO.
................
  r86533 | antoine.pitrou | 2010-11-19 21:07:52 +0100 (ven., 19 nov. 2010) | 3 lines
  
  Fix test_ssl_presence when ssl is not present
................
  r86535 | fred.drake | 2010-11-19 22:24:25 +0100 (ven., 19 nov. 2010) | 2 lines
  
  remove documentation for something that's gone
................
  r86537 | georg.brandl | 2010-11-19 23:09:04 +0100 (ven., 19 nov. 2010) | 1 line
  
  Do not put a raw REPLACEMENT CHARACTER in the document.
................
  r86538 | benjamin.peterson | 2010-11-20 02:38:49 +0100 (sam., 20 nov. 2010) | 1 line
  
  use %R format code; fixes invalid dereferencing #10391
................
  r86540 | benjamin.peterson | 2010-11-20 03:01:45 +0100 (sam., 20 nov. 2010) | 1 line
  
  c89 declarations
................
  r86542 | r.david.murray | 2010-11-20 04:48:58 +0100 (sam., 20 nov. 2010) | 2 lines
  
  Make test class name unique so that both test classes run.
................
  r86544 | brian.quinlan | 2010-11-20 05:09:35 +0100 (sam., 20 nov. 2010) | 1 line
  
  Fixes a timing-related failure on Windows (issue 10183)
................
  r86545 | benjamin.peterson | 2010-11-20 05:31:07 +0100 (sam., 20 nov. 2010) | 1 line
  
  new plan: functions that want 'tmp' can declare it
................
  r86547 | ezio.melotti | 2010-11-20 10:57:27 +0100 (sam., 20 nov. 2010) | 1 line
  
  Add a few labels and links to unittest doc
................
  r86548 | mark.dickinson | 2010-11-20 11:09:56 +0100 (sam., 20 nov. 2010) | 1 line
  
  Add configure-time test for log1p disrespecting zero sign.
................
  r86549 | ezio.melotti | 2010-11-20 11:13:45 +0100 (sam., 20 nov. 2010) | 1 line
  
  Use correct markup for True/False/None
................
  r86550 | georg.brandl | 2010-11-20 11:24:34 +0100 (sam., 20 nov. 2010) | 1 line
  
  Fix rst markup errors.
................
  r86551 | mark.dickinson | 2010-11-20 11:29:12 +0100 (sam., 20 nov. 2010) | 1 line
  
  Regenerated configure and pyconfig.h.in.
................
  r86552 | mark.dickinson | 2010-11-20 11:43:10 +0100 (sam., 20 nov. 2010) | 3 lines
  
  Issue #10325: Fix two issues in the fallback definitions of PY_LLONG_MAX and
  PY_ULLONG_MAX in pyport.h.  Thanks Hallvard B Furuseth for the patch.
................
  r86553 | mark.dickinson | 2010-11-20 12:08:27 +0100 (sam., 20 nov. 2010) | 4 lines
  
  Issue #9920: Skip tests for cmath.atan and cmath.atanh applied to
  complex zeros on systems where the log1p function fails to respect
  the sign of zero.  This fixes a test failure on AIX.
................
  r86555 | georg.brandl | 2010-11-20 12:25:01 +0100 (sam., 20 nov. 2010) | 1 line
  
  #10465: fix broken delegation in __getattr__ of _PaddedFile.
................
  r86561 | georg.brandl | 2010-11-20 12:47:10 +0100 (sam., 20 nov. 2010) | 1 line
  
  #10460: Update indent.pro to match PEP 7 better.
................
  r86562 | georg.brandl | 2010-11-20 14:44:41 +0100 (sam., 20 nov. 2010) | 1 line
  
  #10439: document PyCodec C APIs.
................
  r86564 | georg.brandl | 2010-11-20 15:08:53 +0100 (sam., 20 nov. 2010) | 1 line
  
  #10460: an even better indent.pro.
................
  r86565 | georg.brandl | 2010-11-20 15:16:17 +0100 (sam., 20 nov. 2010) | 1 line
  
  socket.gethostbyname(socket.gethostname()) can fail when host name resolution is not set up correctly; do not fail test_socket if this is the case.
................
  r86566 | michael.foord | 2010-11-20 16:07:30 +0100 (sam., 20 nov. 2010) | 1 line
  
  Issue 9732: addition of getattr_static to the inspect module
................
  r86567 | r.david.murray | 2010-11-20 16:10:13 +0100 (sam., 20 nov. 2010) | 5 lines
  
  Improve TestBytesGeneratorIdempotent using by using linesep.
  
  Also corrects a typo from a previous commit.  Unfortunately
  this does *not* fix issue #10134.
................
  r86570 | michael.foord | 2010-11-20 16:34:26 +0100 (sam., 20 nov. 2010) | 1 line
  
  Issue 10326: TestCase instances can now be pickled (they store names of instance methods instead of references to the instance methods themselves).
................
  r86571 | michael.foord | 2010-11-20 16:43:02 +0100 (sam., 20 nov. 2010) | 1 line
  
  Issue 10326: extend test for pickling of TestCase instances to ensure they can be unpickled too
................
  r86572 | michael.foord | 2010-11-20 16:47:56 +0100 (sam., 20 nov. 2010) | 1 line
  
  Issue 10326: further extend test for unpickling to ensure type lookup mechanism works after unpickling
................
  r86573 | lukasz.langa | 2010-11-20 17:15:37 +0100 (sam., 20 nov. 2010) | 3 lines
  
  configparser: the name of the DEFAULT section is now customizable
................
  r86574 | lukasz.langa | 2010-11-20 17:16:24 +0100 (sam., 20 nov. 2010) | 3 lines
  
  acknowledge configparser evolution
................
  r86575 | michael.foord | 2010-11-20 17:20:16 +0100 (sam., 20 nov. 2010) | 1 line
  
  Issue 9732: remove use of __class__ in inspect.getattr_static and note the mro exception to code execution
................
  r86576 | lukasz.langa | 2010-11-20 17:24:30 +0100 (sam., 20 nov. 2010) | 3 lines
  
  removed a NEWS entry that cloned itself in mysterious circumstances
................
  r86577 | r.david.murray | 2010-11-20 17:33:30 +0100 (sam., 20 nov. 2010) | 4 lines
  
  #1574217: only swallow AttributeErrors in isinstance, not everything.
  
  Patch and tests by Brian Harring, with improvements by Ralf Schmitt.
................
  r86578 | michael.foord | 2010-11-20 17:40:44 +0100 (sam., 20 nov. 2010) | 1 line
  
  Issue 9732: fetch the method resolution order from the type metaclass directly in getattr_static
................
  r86579 | michael.foord | 2010-11-20 17:58:30 +0100 (sam., 20 nov. 2010) | 1 line
  
  Issue 9732: __class__ no longer checked on objects by getattr_static
................
  r86580 | senthil.kumaran | 2010-11-20 18:02:50 +0100 (sam., 20 nov. 2010) | 3 lines
  
  Fix issue10377 - Output from pstats - it is just secs (i.e, wallclock time) and not CPU time.
................
  r86583 | benjamin.peterson | 2010-11-20 18:21:08 +0100 (sam., 20 nov. 2010) | 1 line
  
  code style
................
  r86584 | benjamin.peterson | 2010-11-20 18:22:13 +0100 (sam., 20 nov. 2010) | 1 line
  
  add space
................
  r86585 | michael.foord | 2010-11-20 18:22:21 +0100 (sam., 20 nov. 2010) | 1 line
  
  Improve unittest.TestLoader.discover docstring
................
  r86587 | benjamin.peterson | 2010-11-20 18:24:04 +0100 (sam., 20 nov. 2010) | 1 line
  
  correct logic when pos is after the string #10467
................
  r86592 | michael.foord | 2010-11-20 18:50:34 +0100 (sam., 20 nov. 2010) | 1 line
  
  Addition of issue 9926 to NEWS
................
  r86593 | benjamin.peterson | 2010-11-20 19:07:52 +0100 (sam., 20 nov. 2010) | 1 line
  
  add filename to ENOENT message #4925
................
  r86594 | alexander.belopolsky | 2010-11-20 19:21:07 +0100 (sam., 20 nov. 2010) | 1 line
  
  Issue #10371: Deprecated undocumented functions in the trace module.
................
  r86595 | benjamin.peterson | 2010-11-20 19:24:54 +0100 (sam., 20 nov. 2010) | 1 line
  
  don't shadow globals
................
  r86596 | ezio.melotti | 2010-11-20 20:04:17 +0100 (sam., 20 nov. 2010) | 1 line
  
  #9424: Replace deprecated assert* methods in the Python test suite.
................
  r86598 | benjamin.peterson | 2010-11-20 20:09:08 +0100 (sam., 20 nov. 2010) | 1 line
  
  revert changes in inappropiate branch
................
  r86601 | eric.araujo | 2010-11-20 20:35:27 +0100 (sam., 20 nov. 2010) | 2 lines
  
  Fix two NameErrors in distutils (#10407)
................
  r86603 | antoine.pitrou | 2010-11-20 20:36:05 +0100 (sam., 20 nov. 2010) | 3 lines
  
  In 3.x, bytearray is akin to bytes, not str.
................
  r86605 | eric.araujo | 2010-11-20 20:37:28 +0100 (sam., 20 nov. 2010) | 2 lines
  
  Add entry for r86601
................
  r86607 | antoine.pitrou | 2010-11-20 20:50:57 +0100 (sam., 20 nov. 2010) | 4 lines
  
  Issue #10255: Fix reference leak in Py_InitializeEx().  Patch by Neil
  Schemenauer.
................
  r86608 | georg.brandl | 2010-11-20 20:54:36 +0100 (sam., 20 nov. 2010) | 1 line
  
  #9724: add nonlocal to pydoc topics.
................
  r86610 | antoine.pitrou | 2010-11-20 21:03:08 +0100 (sam., 20 nov. 2010) | 4 lines
  
  Issue #8078: Add constants for higher baud rates in the termios module.
  Patch by Rodolpho Eckhardt.
................
  r86611 | r.david.murray | 2010-11-20 22:18:51 +0100 (sam., 20 nov. 2010) | 4 lines
  
  #10453: compileall now uses argparse instead of getopt, so -h works.
  
  Patch by Michele Orrù.
................
  r86614 | r.david.murray | 2010-11-20 22:28:24 +0100 (sam., 20 nov. 2010) | 2 lines
  
  Fix email doc update I overlooked (thanks, Éric)
................
  r86617 | eric.araujo | 2010-11-20 22:53:02 +0100 (sam., 20 nov. 2010) | 2 lines
  
  Fix typos and style in compileall.
................
  r86618 | benjamin.peterson | 2010-11-20 23:35:41 +0100 (sam., 20 nov. 2010) | 1 line
  
  count() should return integers #10474
................
  r86619 | georg.brandl | 2010-11-20 23:40:10 +0100 (sam., 20 nov. 2010) | 1 line
  
  Add error handling in range_count.
................
  r86620 | benjamin.peterson | 2010-11-20 23:44:32 +0100 (sam., 20 nov. 2010) | 1 line
  
  code style and simplification
................
  r86621 | benjamin.peterson | 2010-11-20 23:50:04 +0100 (sam., 20 nov. 2010) | 1 line
  
  enable test that was commented out for whatever reason
................
  r86622 | benjamin.peterson | 2010-11-21 00:01:55 +0100 (dim., 21 nov. 2010) | 1 line
  
  merge all range tests into test_range
................
  r86623 | benjamin.peterson | 2010-11-21 00:03:34 +0100 (dim., 21 nov. 2010) | 1 line
  
  fix two broken tests
................
  r86624 | benjamin.peterson | 2010-11-21 00:05:39 +0100 (dim., 21 nov. 2010) | 1 line
  
  pep 7 actually wants the brace on a new line
................
  r86625 | eric.araujo | 2010-11-21 00:56:22 +0100 (dim., 21 nov. 2010) | 2 lines
  
  Document index and count as part of the Sequence ABC (#9746)
................
  r86626 | raymond.hettinger | 2010-11-21 01:07:55 +0100 (dim., 21 nov. 2010) | 1 line
  
  Clean-up the description of the range object.
................
  r86630 | eric.araujo | 2010-11-21 03:19:09 +0100 (dim., 21 nov. 2010) | 2 lines
  
  Try to get more useful output from failing buildbot
................
  r86631 | raymond.hettinger | 2010-11-21 03:47:22 +0100 (dim., 21 nov. 2010) | 1 line
  
  Issue #7770: Note the useful range of sin/cos in the decimal module examples.
................
  r86632 | eric.araujo | 2010-11-21 04:09:17 +0100 (dim., 21 nov. 2010) | 2 lines
  
  Style edits in followup to r86521 (#9312)
................
  r86633 | nick.coghlan | 2010-11-21 04:44:04 +0100 (dim., 21 nov. 2010) | 1 line
  
  Issue #10220: Add inspect.getgeneratorstate(). Initial patch by Rodolpho Eckhardt
................
  r86634 | nick.coghlan | 2010-11-21 04:55:53 +0100 (dim., 21 nov. 2010) | 1 line
  
  Add a couple of missing versionadded tags in the inspect module docs
................
  r86635 | raymond.hettinger | 2010-11-21 05:08:28 +0100 (dim., 21 nov. 2010) | 1 line
  
  Revert  r86517
................
  r86636 | mark.dickinson | 2010-11-21 08:37:49 +0100 (dim., 21 nov. 2010) | 1 line
  
  Fix capitalization.
................
  r86638 | lukasz.langa | 2010-11-21 14:41:35 +0100 (dim., 21 nov. 2010) | 3 lines
  
  Issue #10489: removed broken `__name__` support from configparser
................
  r86639 | lukasz.langa | 2010-11-21 14:56:42 +0100 (dim., 21 nov. 2010) | 3 lines
  
  configparser: read-only attributes to get the section name and parser from a SectionProxy instance
................
  r86640 | senthil.kumaran | 2010-11-21 15:36:14 +0100 (dim., 21 nov. 2010) | 3 lines
  
  Fix issue3709 - BaseHTTPRequestHandler will buffer the headers and write only on end_headers call.
................
  r86641 | benjamin.peterson | 2010-11-21 16:12:34 +0100 (dim., 21 nov. 2010) | 1 line
  
  fix refleak
................
  r86642 | r.david.murray | 2010-11-21 17:53:48 +0100 (dim., 21 nov. 2010) | 10 lines
  
  Fix TestBytesGeneratorIdempotent tests and a couple bugs they revealed.
  
  The tests that were failing on (some) windows machines, where the
  msg_XX.txt files used native \r\n lineseps are now also run on machines
  that use \n natively, and conversely the \n tests are run on Windows.
  The failing tests revealed one place where linesep needed to be added
  to a flatten call in generator.  There was also another that the tests
  didn't catch, so I added a test for that case as well.
................
  r86645 | antoine.pitrou | 2010-11-21 18:14:19 +0100 (dim., 21 nov. 2010) | 3 lines
  
  Make test_nntplib more robust
................
  r86646 | brett.cannon | 2010-11-21 20:58:24 +0100 (dim., 21 nov. 2010) | 1 line
  
  Add sets to the precedence table.
................
  r86647 | ezio.melotti | 2010-11-21 21:27:39 +0100 (dim., 21 nov. 2010) | 1 line
  
  Add CSS rule for the deprecated-removed directive
................
  r86648 | mark.dickinson | 2010-11-21 22:09:58 +0100 (dim., 21 nov. 2010) | 2 lines
  
  Issue #10488: Bring documentation for 'float' builtin up to date.
................
  r86649 | michael.foord | 2010-11-21 22:28:01 +0100 (dim., 21 nov. 2010) | 1 line
  
  Issue 10470:  'python -m unittest' launches test discovery by default.(If you need to pass options to test discovery the discover subcommand must still be specified explicitly.)
................
  r86650 | raymond.hettinger | 2010-11-22 00:23:29 +0100 (lun., 22 nov. 2010) | 1 line
  
  Issue 6722: Improve the namedtuple examples.
................
  r86651 | brian.curtin | 2010-11-22 00:45:10 +0100 (lun., 22 nov. 2010) | 5 lines
  
  Fix #6378. Start IDLE using the proper version of Python based on the directory
  tree that idle.bat resides in.
  
  Works with any/all versions of Python installed concurrently.
................
  r86654 | raymond.hettinger | 2010-11-22 00:51:45 +0100 (lun., 22 nov. 2010) | 1 line
  
  Issue 3292: Fixup to the Sequence docs.
................
  r86655 | brian.curtin | 2010-11-22 01:01:01 +0100 (lun., 22 nov. 2010) | 2 lines
  
  Quote the paths in the event that they contain spaces.
................
  r86660 | raymond.hettinger | 2010-11-22 02:08:14 +0100 (lun., 22 nov. 2010) | 1 line
  
  Update maintainers
................
  r86661 | eric.araujo | 2010-11-22 02:11:49 +0100 (lun., 22 nov. 2010) | 2 lines
  
  Fix typo
................
  r86662 | eric.araujo | 2010-11-22 02:19:20 +0100 (lun., 22 nov. 2010) | 2 lines
  
  r84925 followup: add docstring for get_makefile_filename (+PEP 257 fixes)
................
  r86665 | ezio.melotti | 2010-11-22 02:22:43 +0100 (lun., 22 nov. 2010) | 1 line
  
  Add myself for unittest and fix Alexander username
................
  r86668 | eric.araujo | 2010-11-22 03:42:43 +0100 (lun., 22 nov. 2010) | 2 lines
  
  Fix one compileall test (#10453).  Patch by Michele Orrù.
................
  r86669 | alexander.belopolsky | 2010-11-22 04:06:56 +0100 (lun., 22 nov. 2010) | 1 line
  
  Issue #10138: Removed 'indefinitely' from the proleptic calendar description.
................
  r86670 | eric.araujo | 2010-11-22 04:09:19 +0100 (lun., 22 nov. 2010) | 4 lines
  
  Remove unnecessary `object` base class in docs (#10366).
  
  Also add a note about inheritance from `object` being default.
................
  r86671 | eric.araujo | 2010-11-22 04:13:47 +0100 (lun., 22 nov. 2010) | 2 lines
  
  Fix resource warning from patchcheck.py
................
  r86676 | senthil.kumaran | 2010-11-22 05:48:26 +0100 (lun., 22 nov. 2010) | 4 lines
  
  Fix Issue4493 - urllib2 adds '/' to the path component of url, when it does not
  starts with one. This behavior is exhibited by browser and other clients.
................
  r86679 | senthil.kumaran | 2010-11-22 06:08:13 +0100 (lun., 22 nov. 2010) | 3 lines
  
  Fix - s/urllib2/urllib.request/
................
  r86681 | martin.v.loewis | 2010-11-22 10:00:02 +0100 (lun., 22 nov. 2010) | 2 lines
  
  Issue #10459: Update CJK character names to Unicode 6.0.
................
  r86684 | michael.foord | 2010-11-22 11:41:27 +0100 (lun., 22 nov. 2010) | 1 line
  
  Improve test for 'python -m unittest' launching test discovery
................
  r86689 | kristjan.jonsson | 2010-11-22 12:37:06 +0100 (lun., 22 nov. 2010) | 3 lines
  
  issue 10501
  make_buildinfo regression with unquoted path
  Make_buildinfo.exe should be called with a quoted path, and should quote the full paths to its temp files, to support spaces in filenames.
................
  r86690 | ezio.melotti | 2010-11-22 13:56:58 +0100 (lun., 22 nov. 2010) | 1 line
  
  #9424: add a DeprecationWarning for assertEquals, assertNotEquals, assertAlmostEquals, assertNotAlmostEquals, and assert_
................
  r86693 | antoine.pitrou | 2010-11-22 17:19:04 +0100 (lun., 22 nov. 2010) | 3 lines
  
  Fix tests when ctypes isn't available
................
  r86694 | antoine.pitrou | 2010-11-22 17:26:21 +0100 (lun., 22 nov. 2010) | 3 lines
  
  Fix test_multiprocessing when ctypes isn't available
................
  r86697 | alexander.belopolsky | 2010-11-22 20:40:51 +0100 (lun., 22 nov. 2010) | 1 line
  
  Issue #6878: Fixed return type of tkinter methods documented to return lists.
................
  r86699 | lukasz.langa | 2010-11-23 00:31:26 +0100 (mar., 23 nov. 2010) | 3 lines
  
  Issue #9846: ZipExtFile provides no mechanism for closing the underlying file object
................
  r86700 | lukasz.langa | 2010-11-23 01:15:02 +0100 (mar., 23 nov. 2010) | 3 lines
  
  zipfile: remove remaining ResourceWarnings
................
  r86701 | lukasz.langa | 2010-11-23 01:19:53 +0100 (mar., 23 nov. 2010) | 3 lines
  
  information on Issue #9846
................
  r86702 | terry.reedy | 2010-11-23 07:01:31 +0100 (mar., 23 nov. 2010) | 2 lines
  
  Issue 9222 Fix filetypes for open dialog
................
  r86705 | georg.brandl | 2010-11-23 08:54:19 +0100 (mar., 23 nov. 2010) | 1 line
  
  #10468: document Unicode exception creation and access functions.
................
  r86708 | georg.brandl | 2010-11-23 09:37:54 +0100 (mar., 23 nov. 2010) | 2 lines
  
  #10511: clarification of what heaps are; suggested by Johannes Hoff.
................
  r86713 | georg.brandl | 2010-11-23 19:14:57 +0100 (mar., 23 nov. 2010) | 1 line
  
  assert.h is also included. Thanks to Savio Sena.
................
  r86717 | terry.reedy | 2010-11-23 21:17:24 +0100 (mar., 23 nov. 2010) | 2 lines
  
  Issue 1859: Doc that textwrap does not break on \n (pending possible behavior patch). Patch by Jeremy Thurgood.
................
  r86720 | terry.reedy | 2010-11-23 21:32:47 +0100 (mar., 23 nov. 2010) | 2 lines
  
  IssIssue 1859: Add Jeremy Thurgood to Misc/ACKS
................
  r86725 | georg.brandl | 2010-11-24 10:09:29 +0100 (mer., 24 nov. 2010) | 1 line
  
  Remove UTF-8 BOM.
................
  r86727 | brian.curtin | 2010-11-24 14:14:05 +0100 (mer., 24 nov. 2010) | 7 lines
  
  Fix #10027. st_nlink not set on Windows calls to os.stat/lstat.
  
  Note: This patch has no tests because as of now there is no way to create
  links. #8879 adds that and the tests will go in there. I've manually observed
  that existing links on my system function properly with this.
................
  r86729 | brian.curtin | 2010-11-24 14:23:18 +0100 (mer., 24 nov. 2010) | 2 lines
  
  ifdef a Windows specific section.
................
  r86730 | barry.warsaw | 2010-11-24 19:18:21 +0100 (mer., 24 nov. 2010) | 2 lines
  
  Remove unnecessary import.
................
  r86731 | barry.warsaw | 2010-11-24 20:43:47 +0100 (mer., 24 nov. 2010) | 2 lines
  
  Final patch for issue 9807.
................
  r86732 | ezio.melotti | 2010-11-24 21:18:02 +0100 (mer., 24 nov. 2010) | 1 line
  
  #10299: Add a table that lists all the built-in functions in functions.rst
................
  r86733 | brian.curtin | 2010-11-24 21:24:31 +0100 (mer., 24 nov. 2010) | 8 lines
  
  Fix #8879. Add os.link support to Windows.
  
  Additionally, the st_ino attribute of stat structures was not being filled
  in. This was left out of the fix to #10027 and was noticed due to
  test_tarfile failing when applying the patch for this issue. An earlier
  version of the fix to #10027 included st_ino, but that attribute got lost
  in the shuffle of a few review/fix cycles. All tests pass.
................
  r86734 | barry.warsaw | 2010-11-24 21:30:00 +0100 (mer., 24 nov. 2010) | 5 lines
  
  Put /usr/local paths after the relative paths in library_dirs and
  include_dirs, so installed non-matching shared libraries don't break extension
  module linking.  Fixes issue 10520.
................
  r86737 | ezio.melotti | 2010-11-24 23:02:18 +0100 (mer., 24 nov. 2010) | 1 line
  
  Add NEWS entry for r86732 and fix double function in the table.
................
  r86743 | barry.warsaw | 2010-11-25 02:34:47 +0100 (jeu., 25 nov. 2010) | 2 lines
  
  sys.abiflags may not be defined on all platforms.
................
  r86744 | barry.warsaw | 2010-11-25 04:46:44 +0100 (jeu., 25 nov. 2010) | 2 lines
  
  sys.abiflags is not defined on all platforms.
................
  r86745 | terry.reedy | 2010-11-25 07:12:34 +0100 (jeu., 25 nov. 2010) | 2 lines
  
  Issue 2986: Add autojunk paramater to SequenceMatcher to turn off heuristic. Patch by Terry Reedy, Eli Bendersky, and Simon Cross
................
  r86746 | raymond.hettinger | 2010-11-25 09:11:57 +0100 (jeu., 25 nov. 2010) | 1 line
  
  Clean-up docstring, comments, and whitespace.
................
  r86747 | amaury.forgeotdarc | 2010-11-25 09:13:35 +0100 (jeu., 25 nov. 2010) | 3 lines
  
  Fix compilation warnings seen on Windows.
  'typecode' is always an ascii letter, there was no data lost.
................
  r86750 | senthil.kumaran | 2010-11-25 15:56:44 +0100 (jeu., 25 nov. 2010) | 3 lines
  
  Mouse support and colour to Demo/curses/life.py by Dafydd Crosby
................
  r86751 | eric.smith | 2010-11-25 17:08:06 +0100 (jeu., 25 nov. 2010) | 1 line
  
  Issue #7094: Add alternate ('#') flag to __format__ methods for float, complex and Decimal. Allows greater control over when decimal points appear. Added to make transitioning from %-formatting easier. '#g' still has a problem with Decimal which I'll fix soon.
................
  r86758 | eric.araujo | 2010-11-26 01:39:59 +0100 (ven., 26 nov. 2010) | 2 lines
  
  #10453 follow-up: Fix test_quiet on Windows, thanks to Stephan Krah.
................
  r86759 | senthil.kumaran | 2010-11-26 03:20:04 +0100 (ven., 26 nov. 2010) | 3 lines
  
   s/colour/color/g 
................
  r86791 | stefan.krah | 2010-11-26 11:54:09 +0100 (ven., 26 nov. 2010) | 1 line
  
  Indentation cleanup.
................
  r86794 | georg.brandl | 2010-11-26 12:50:13 +0100 (ven., 26 nov. 2010) | 1 line
  
  #10526: fix typo.
................
  r86795 | georg.brandl | 2010-11-26 12:55:48 +0100 (ven., 26 nov. 2010) | 1 line
  
  Use PyLong_FromLong where appropriate.
................
  r86797 | georg.brandl | 2010-11-26 13:05:27 +0100 (ven., 26 nov. 2010) | 1 line
  
  Modernize code in effective().
................
  r86798 | georg.brandl | 2010-11-26 13:05:48 +0100 (ven., 26 nov. 2010) | 1 line
  
  #10420: fix docs of bdb.effective().
................
  r86799 | georg.brandl | 2010-11-26 13:08:19 +0100 (ven., 26 nov. 2010) | 1 line
  
  Remove parenthetical remark that is confusing now that the module is not named "__builtin__" anymore.
................
  r86800 | georg.brandl | 2010-11-26 13:10:06 +0100 (ven., 26 nov. 2010) | 1 line
  
  Typo fix.
................
  r86801 | georg.brandl | 2010-11-26 13:12:14 +0100 (ven., 26 nov. 2010) | 1 line
  
  Better example for os.system(): do not change the system time.
................
  r86804 | stefan.krah | 2010-11-26 13:58:05 +0100 (ven., 26 nov. 2010) | 1 line
  
  Issue #10383: Fix two leaks.
................
  r86808 | stefan.krah | 2010-11-26 17:16:47 +0100 (ven., 26 nov. 2010) | 1 line
  
  Further indentation cleanup.
................
  r86819 | alexander.belopolsky | 2010-11-26 19:51:39 +0100 (ven., 26 nov. 2010) | 1 line
  
  Fixed deprecation warnings.
................
  r86823 | eric.araujo | 2010-11-27 00:31:07 +0100 (sam., 27 nov. 2010) | 2 lines
  
  Use link-generating markup (see #9312)
................
  r86824 | eric.araujo | 2010-11-27 00:46:18 +0100 (sam., 27 nov. 2010) | 2 lines
  
  Rewrap long lines + minor edits
................
  r86825 | raymond.hettinger | 2010-11-27 09:09:40 +0100 (sam., 27 nov. 2010) | 1 line
  
  Replace _nbits() with int.bit_length().
................
  r86828 | raymond.hettinger | 2010-11-27 10:31:37 +0100 (sam., 27 nov. 2010) | 1 line
  
  Issue 10242: unittest.assertItemsEqual makes too many assumptions.
................
  r86829 | stefan.krah | 2010-11-27 12:44:18 +0100 (sam., 27 nov. 2010) | 1 line
  
  Fix additional leaks.
................
  r86837 | barry.warsaw | 2010-11-27 21:03:03 +0100 (sam., 27 nov. 2010) | 2 lines
  
  Roumen Petrov's fix for when all paths are absolute.  (Issue 10520)
................
  r86838 | antoine.pitrou | 2010-11-27 21:40:43 +0100 (sam., 27 nov. 2010) | 3 lines
  
  Make doc for PyErr_Format() up to date.
................
  r86839 | terry.reedy | 2010-11-27 21:52:14 +0100 (sam., 27 nov. 2010) | 2 lines
  
  Add version-added note twice for new difflib SequenceMatcher autojunk parameter.
................
  r86842 | antoine.pitrou | 2010-11-27 23:00:11 +0100 (sam., 27 nov. 2010) | 4 lines
  
  Issue #10518: Bring back the callable() builtin.
  Approved by Guido (BDFL) and Georg (RM).
................
  r86843 | stefan.krah | 2010-11-27 23:06:49 +0100 (sam., 27 nov. 2010) | 1 line
  
  Windows: fix leak in posix_listdir.
................
  r86844 | benjamin.peterson | 2010-11-28 03:51:28 +0100 (dim., 28 nov. 2010) | 1 line
  
  there's now a setup.py switch for this
................
  r86845 | ezio.melotti | 2010-11-28 05:18:54 +0100 (dim., 28 nov. 2010) | 1 line
  
  Add callable() to the built-in functions table.
................
  r86854 | brian.curtin | 2010-11-29 00:59:46 +0100 (lun., 29 nov. 2010) | 6 lines
  
  Fix for #8879.
  Amaury noticed that this was originally written in a way that would fail on
  names that can't be encoded with the mbcs codec. Restructured the function
  to work with wide names first then narrow names second, to fall in line
  with the way other functions are written in posixmodule.c.
................
  r86855 | raymond.hettinger | 2010-11-29 02:38:25 +0100 (lun., 29 nov. 2010) | 1 line
  
  Do not add an obsolete unittest name to Py3.2.
................
  r86856 | ezio.melotti | 2010-11-29 03:02:10 +0100 (lun., 29 nov. 2010) | 1 line
  
  Use assertCountEqual instead of assertItemsEqual
................
  r86857 | raymond.hettinger | 2010-11-29 04:56:12 +0100 (lun., 29 nov. 2010) | 1 line
  
  Issue #10565:  Iterator ABC should require both __next__ and __iter__.
................
  r86861 | senthil.kumaran | 2010-11-29 12:54:17 +0100 (lun., 29 nov. 2010) | 5 lines
  
  Fix #10561 - Fix pdb behavior. Delete the breakpoints by breakpoint number.
  Handle multiple breakpoints at same line. Update docs/test. 
  Patch by Xavier de Gaye.
................
  r86864 | senthil.kumaran | 2010-11-29 13:42:29 +0100 (lun., 29 nov. 2010) | 3 lines
  
  Remove the comment used while testing.
................
  r86867 | georg.brandl | 2010-11-29 15:50:54 +0100 (lun., 29 nov. 2010) | 1 line
  
  Fix indentation bug.
................
  r86868 | georg.brandl | 2010-11-29 15:53:15 +0100 (lun., 29 nov. 2010) | 1 line
  
  Fix heading style inconsistencies.
................
  r86869 | georg.brandl | 2010-11-29 21:12:24 +0100 (lun., 29 nov. 2010) | 1 line
  
  Code style cleanup in bdb.
................
  r86870 | georg.brandl | 2010-11-29 21:19:15 +0100 (lun., 29 nov. 2010) | 1 line
  
  Use booleans where applicable.
................
  r86874 | raymond.hettinger | 2010-11-30 03:49:29 +0100 (mar., 30 nov. 2010) | 1 line
  
  Issue #10323: Predictable final state for slice().
................
  r86875 | alexander.belopolsky | 2010-11-30 04:03:30 +0100 (mar., 30 nov. 2010) | 3 lines
  
  Issue #10572: Moved json tests to Lib/test/json_tests.
  Approved by Raymond Hettinger.
................
  r86878 | nick.coghlan | 2010-11-30 07:19:46 +0100 (mar., 30 nov. 2010) | 1 line
  
  Issue 10586: change the new functools.lru_cache implementation to expose the maximum and current cache sizes through the public statistics API. This API is now a single function that returns a named tuple.
................
  r86879 | nick.coghlan | 2010-11-30 07:36:04 +0100 (mar., 30 nov. 2010) | 1 line
  
  Issue 10220: switch to using string constants rather than integers for inspect.getgeneratorstate() return values and make debugging friendly str() and repr() for generator states a requirement in the test suite
................
  r86880 | raymond.hettinger | 2010-11-30 08:13:04 +0100 (mar., 30 nov. 2010) | 1 line
  
  Neaten-up a bit.
................
  r86881 | georg.brandl | 2010-11-30 08:43:28 +0100 (mar., 30 nov. 2010) | 1 line
  
  #10584: fix bad links.
................
  r86882 | georg.brandl | 2010-11-30 09:20:16 +0100 (mar., 30 nov. 2010) | 1 line
  
  Fix input type for zlib.
................
  r86883 | georg.brandl | 2010-11-30 10:30:54 +0100 (mar., 30 nov. 2010) | 1 line
  
  Include structseq.h in Python.h, and remove now-redundant includes in individual sources.
................
  r86884 | georg.brandl | 2010-11-30 10:41:01 +0100 (mar., 30 nov. 2010) | 1 line
  
  Remove redundant includes of headers that are already included by Python.h.
................
  r86887 | georg.brandl | 2010-11-30 15:57:54 +0100 (mar., 30 nov. 2010) | 1 line
  
  Fix typo.
................
  r86888 | brian.curtin | 2010-11-30 16:40:04 +0100 (mar., 30 nov. 2010) | 3 lines
  
  Try to fix failures on platforms that can't encode the test characters.
  Skip the test if encoding fails.
................
  r86889 | nick.coghlan | 2010-11-30 16:48:08 +0100 (mar., 30 nov. 2010) | 1 line
  
  Issue 9873: the URL parsing functions now accept ASCII encoded byte sequences in addition to character strings
................
  r86890 | brian.curtin | 2010-11-30 16:54:04 +0100 (mar., 30 nov. 2010) | 2 lines
  
  Actually fix what I attempted to fix in r86888...
................
  r86891 | alexander.belopolsky | 2010-11-30 17:56:15 +0100 (mar., 30 nov. 2010) | 1 line
  
  Issue #10552: Partially fixed a sort error in Tools/unicode/gencodec.py
................
  r86892 | eric.araujo | 2010-11-30 18:20:31 +0100 (mar., 30 nov. 2010) | 2 lines
  
  Let’s keep “throw” for the generator method and use “raise” elsewhere.
................
  r86893 | alexander.belopolsky | 2010-11-30 18:30:43 +0100 (mar., 30 nov. 2010) | 1 line
  
  Issue #9598: untabify.py will now respect encoding cookie in the files it processes
................
  r86895 | raymond.hettinger | 2010-11-30 18:45:41 +0100 (mar., 30 nov. 2010) | 1 line
  
  Add some internal links.
................
  r86896 | daniel.stutzbach | 2010-11-30 18:49:53 +0100 (mar., 30 nov. 2010) | 1 line
  
  Fix typo: "ofbytes" should be "of bytes"
................
  r86901 | raymond.hettinger | 2010-11-30 20:15:45 +0100 (mar., 30 nov. 2010) | 1 line
  
  Add example, tighten text, and minor clean-ups.
................
  r86902 | raymond.hettinger | 2010-11-30 21:02:57 +0100 (mar., 30 nov. 2010) | 1 line
  
  Documentation nits.
................
  r86903 | raymond.hettinger | 2010-11-30 21:32:59 +0100 (mar., 30 nov. 2010) | 1 line
  
  Add link to specification.
................
  r86905 | antoine.pitrou | 2010-11-30 23:23:20 +0100 (mar., 30 nov. 2010) | 4 lines
  
  Issue #8685: Speed up set difference `a - b` when source set `a` is
  much larger than operand `b`.  Patch by Andrew Bennetts.
................
  r86906 | brian.curtin | 2010-12-01 00:46:54 +0100 (mer., 01 déc. 2010) | 3 lines
  
  Fix #10591. Fix test_os for refleak runs.
  Split a common setUp/tearDown into the appropriate parts.
................
  r86907 | raymond.hettinger | 2010-12-01 01:47:56 +0100 (mer., 01 déc. 2010) | 1 line
  
  Doc and docstring nits.
................
  r86908 | ezio.melotti | 2010-12-01 01:56:10 +0100 (mer., 01 déc. 2010) | 1 line
  
  #10535: Enable silenced warnings in unittest by default
................
  r86909 | ezio.melotti | 2010-12-01 02:45:53 +0100 (mer., 01 déc. 2010) | 1 line
  
  Fix test failure in debug builds and add NEWS entry for r86908
................
  r86910 | ezio.melotti | 2010-12-01 03:32:32 +0100 (mer., 01 déc. 2010) | 1 line
  
  #10273: Rename assertRegexpMatches and assertRaisesRegexp to assertRegex and assertRaisesRegex.
................
  r86911 | raymond.hettinger | 2010-12-01 04:45:41 +0100 (mer., 01 déc. 2010) | 1 line
  
  Issue 10593:  Adopt Nick's suggestion for an lru_cache with maxsize=None.
................
  r86912 | raymond.hettinger | 2010-12-01 11:49:19 +0100 (mer., 01 déc. 2010) | 1 line
  
  Add recipe to itertools doc.
................
  r86913 | georg.brandl | 2010-12-01 16:32:43 +0100 (mer., 01 déc. 2010) | 1 line
  
  Add missing word, and add a better reference to the actual function.
................
  r86914 | georg.brandl | 2010-12-01 16:36:33 +0100 (mer., 01 déc. 2010) | 1 line
  
  #10594: fix parameter names in PyList API docs.
................
  r86915 | georg.brandl | 2010-12-01 16:44:25 +0100 (mer., 01 déc. 2010) | 1 line
  
  Fix some markup and style in the unittest docs.
................
  r86916 | alexander.belopolsky | 2010-12-01 21:05:49 +0100 (mer., 01 déc. 2010) | 1 line
  
  Issue #4113: Added custom __repr__ method to functools.partial.
................
  r86917 | alexander.belopolsky | 2010-12-01 22:55:40 +0100 (mer., 01 déc. 2010) | 1 line
  
  Reverted unintended change from r86916
................
  r86918 | raymond.hettinger | 2010-12-01 23:48:00 +0100 (mer., 01 déc. 2010) | 1 line
  
  Add itertools.accumulate().
................
  r86919 | raymond.hettinger | 2010-12-01 23:50:36 +0100 (mer., 01 déc. 2010) | 1 line
  
  Add itertools.accumulate().
................
  r86920 | raymond.hettinger | 2010-12-02 00:45:20 +0100 (jeu., 02 déc. 2010) | 1 line
  
  Clean-up last update (missing comma, unnecessary spacing change, spurious backtick).
................
  r86921 | alexander.belopolsky | 2010-12-02 01:05:57 +0100 (jeu., 02 déc. 2010) | 1 line
  
  With Raymond's approval added a paragraph describing Unicode 6.0.0 changes.  Not reST formatted.
................
  r86922 | alexander.belopolsky | 2010-12-02 01:10:11 +0100 (jeu., 02 déc. 2010) | 1 line
  
  Issue4335: Added a test for inspect.getsourcelines with a module without EOL at EOF.
................
  r86923 | raymond.hettinger | 2010-12-02 02:38:25 +0100 (jeu., 02 déc. 2010) | 1 line
  
  Fix markup
................
  r86924 | raymond.hettinger | 2010-12-02 03:41:33 +0100 (jeu., 02 déc. 2010) | 1 line
  
  Add an example to the random docs.
................
  r86925 | r.david.murray | 2010-12-02 03:58:07 +0100 (jeu., 02 déc. 2010) | 4 lines
  
  #10464: fix netrc handling of lines with embedded '#" characters.
  
  Patch by Xuanji Li.
................
  r86928 | nick.coghlan | 2010-12-02 05:11:46 +0100 (jeu., 02 déc. 2010) | 1 line
  
  Issue #9573: os.fork now works when triggered as a side effect of import (the wisdom of actually relying on this remains questionable!)
................
  r86929 | raymond.hettinger | 2010-12-02 06:35:35 +0100 (jeu., 02 déc. 2010) | 1 line
  
  Neaten-up random module docs.
................
  r86930 | terry.reedy | 2010-12-02 08:05:56 +0100 (jeu., 02 déc. 2010) | 2 lines
  
  Issue 9299 Add exist_ok parameter to os.makedirs to suppress 'File exists' exception. Patch by Ray Allen.
................
  r86931 | georg.brandl | 2010-12-02 10:06:12 +0100 (jeu., 02 déc. 2010) | 1 line
  
  Fix-up documentation of makedirs().
................
  r86932 | david.malcolm | 2010-12-02 17:41:00 +0100 (jeu., 02 déc. 2010) | 2 lines
  
  Fix spelling of Jamie Zawinski's surname in urllib.parse docstring (issue 10606)
................
  r86933 | georg.brandl | 2010-12-02 19:02:01 +0100 (jeu., 02 déc. 2010) | 1 line
  
  #10597: fix Py_SetPythonHome docs by pointing to where the meaning of PYTHONHOME is already documented.
................
  r86934 | georg.brandl | 2010-12-02 19:06:51 +0100 (jeu., 02 déc. 2010) | 1 line
  
  #7475: add (un)transform method to bytes/bytearray and str, add back codecs that can be used with them from Python 2.
................
  r86935 | brian.curtin | 2010-12-02 19:29:18 +0100 (jeu., 02 déc. 2010) | 17 lines
  
  Fix #9333. Expose os.symlink on Windows only when usable.
  
  In order to create symlinks on Windows, SeCreateSymbolicLinkPrivilege 
  is an account privilege that is required to be held by the user. Not only
  must the privilege be enabled for the account, the activated privileges for
  the currently running application must be adjusted to enable the requested
  privilege.
  
  Rather than exposing an additional function to be called prior to the user's
  first os.symlink call, we handle the AdjustTokenPrivileges Windows API call
  internally and only expose os.symlink when the privilege escalation was
  successful.
  
  Due to the change of only exposing os.symlink when it's available, we can
  go back to the original test skipping methods of checking via `hasattr`.
................
  r86936 | r.david.murray | 2010-12-02 22:47:19 +0100 (jeu., 02 déc. 2010) | 4 lines
  
  #8989: add 'domain' keyword to make_msgid.
  
  Patch by Adrian von Bidder.
................
  r86937 | daniel.stutzbach | 2010-12-02 22:55:33 +0100 (jeu., 02 déc. 2010) | 1 line
  
  Issue9915: speeding up sorting with a key
................
  r86940 | eric.araujo | 2010-12-02 23:16:19 +0100 (jeu., 02 déc. 2010) | 2 lines
  
  Fix wrong test code in test_csv (#10602)
................
  r86943 | georg.brandl | 2010-12-02 23:35:25 +0100 (jeu., 02 déc. 2010) | 1 line
  
  Re-add accidentally removed line.
................
  r86944 | michael.foord | 2010-12-03 01:53:09 +0100 (ven., 03 déc. 2010) | 1 line
  
  Issue 7911: unittest.TestCase.longMessage defaults to True for improved failure messages by default
................
  r86945 | michael.foord | 2010-12-03 02:34:01 +0100 (ven., 03 déc. 2010) | 1 line
  
  Initial implementation of Lib/test/__main__.py so we can run tests with 'python -m test'
................
  r86946 | benjamin.peterson | 2010-12-03 02:44:10 +0100 (ven., 03 déc. 2010) | 1 line
  
  code style
................
  r86947 | michael.foord | 2010-12-03 03:03:30 +0100 (ven., 03 déc. 2010) | 1 line
  
  Set test.regrtest.TEMPDIR correctly when run with 'python -m test'
................
  r86948 | raymond.hettinger | 2010-12-03 03:09:34 +0100 (ven., 03 déc. 2010) | 1 line
  
  Simplify the signature for itertools.accumulate() to match numpy.  Handle one item iterable the same way as min()/max().
................
  r86949 | michael.foord | 2010-12-03 03:27:44 +0100 (ven., 03 déc. 2010) | 1 line
  
  Remove test/__main__.py until runpy tests can be fixed
................
  r86950 | raymond.hettinger | 2010-12-03 03:33:53 +0100 (ven., 03 déc. 2010) | 1 line
  
  Update the itertools.accumulate() docs.
................
  r86951 | brian.curtin | 2010-12-03 03:46:02 +0100 (ven., 03 déc. 2010) | 6 lines
  
  Fix #10554. Added context manager support to Popen objects.
  
  Added a few common Popen uses to the tests like we've done for a few other
  instances of adding context managers. Eventually the entire test suite
  could be converted to use the context manager format.
................
  r86952 | r.david.murray | 2010-12-03 05:06:39 +0100 (ven., 03 déc. 2010) | 12 lines
  
  #1486713: Add a tolerant mode to HTMLParser.
  
  The motivation for adding this option is that the the functionality it
  provides used to be provided by sgmllib in Python2, and was used by,
  for example, BeautifulSoup.  Without this option, the Python3 version
  of BeautifulSoup and the many programs that use it are crippled.
  
  The original patch was by 'kxroberto'.  I modified it heavily but kept his
  heuristics and test.  I also added additional heuristics to fix #975556,
  #1046092, and part of #6191.  This patch should be completely backward
  compatible:  the behavior with the default strict=True is unchanged.
................
  r86953 | r.david.murray | 2010-12-03 05:26:18 +0100 (ven., 03 déc. 2010) | 2 lines
  
  Add missing versionchanged, correct 'throw' wording to 'raise'.
................
  r86954 | georg.brandl | 2010-12-03 08:37:16 +0100 (ven., 03 déc. 2010) | 1 line
  
  Move entries from "core" section to where they belong.
................
  r86955 | georg.brandl | 2010-12-03 08:38:22 +0100 (ven., 03 déc. 2010) | 1 line
  
  #1745035: add limits for command and data size to smtpd; patch by Savio Sena.
................
  r86956 | nick.coghlan | 2010-12-03 08:44:33 +0100 (ven., 03 déc. 2010) | 1 line
  
  Partially revert r78719 - it removed a check that is still needed in some cases (i.e. this will allow Michael to add the test.__main__ support that broke the buildbots previously)
................
  r86957 | georg.brandl | 2010-12-03 08:47:22 +0100 (ven., 03 déc. 2010) | 1 line
  
  #940286: pydoc.Helper.help() ignores input/output init parameters.
................
  r86958 | georg.brandl | 2010-12-03 08:49:09 +0100 (ven., 03 déc. 2010) | 1 line
  
  Use booleans.
................
  r86959 | georg.brandl | 2010-12-03 08:54:09 +0100 (ven., 03 déc. 2010) | 1 line
  
  Remove redundant check for PyBytes in unicode_encode.
................
  r86960 | georg.brandl | 2010-12-03 08:55:44 +0100 (ven., 03 déc. 2010) | 1 line
  
  #10360: catch TypeError in WeakSet.__contains__, just like WeakKeyDictionary does.
................
  r86961 | georg.brandl | 2010-12-03 10:18:37 +0100 (ven., 03 déc. 2010) | 1 line
  
  Rewrap NEWS (Builbot test commit.)
................
  r86962 | nick.coghlan | 2010-12-03 10:29:11 +0100 (ven., 03 déc. 2010) | 14 lines
  
  Improve Pydoc interactive browsing (#2001).  Patch by Ron Adam.
  
  * A -b option to start an enhanced browsing session.
  * Allow -b and -p options to be used together.
  * Specifying port 0 will pick an arbitrary unused socket port.
  * A new browse() function to start the new server and browser.
  * Show Python version information in the header.
  * A *Get* field which takes the same input as the help() function.
  * A *Search* field which replaces the Tkinter search box.
  * Links to *Module Index*, *Topics*, and *Keywords*.
  * Improved source file viewing.
  * An HTMLDoc.filelink() method.
  * The -g option and the gui() and serve() functions are deprecated.
................
  r86963 | georg.brandl | 2010-12-03 10:45:33 +0100 (ven., 03 déc. 2010) | 1 line
  
  Add a line with the actual changes.
................
  r86964 | georg.brandl | 2010-12-03 10:58:38 +0100 (ven., 03 déc. 2010) | 1 line
  
  #10549: fix interface of docclass() for text documenter.
................
  r86965 | michael.foord | 2010-12-03 11:42:03 +0100 (ven., 03 déc. 2010) | 1 line
  
  Adding lib/test/__main__.py for running tests with 'python -m test'
................
  r86966 | michael.foord | 2010-12-03 11:59:15 +0100 (ven., 03 déc. 2010) | 1 line
  
  Fix lib/test/__main__.py to work even outside a Python build.
................
  r86967 | vinay.sajip | 2010-12-03 12:50:38 +0100 (ven., 03 déc. 2010) | 1 line
  
  logging: Added getLogRecordFactory/setLogRecordFactory with docs and tests.
................
  r86968 | michael.foord | 2010-12-03 13:27:40 +0100 (ven., 03 déc. 2010) | 1 line
  
  Factor out common code from lib/test/__main__.py and lib/test/regrtest.py into a function.
................
  r86969 | vinay.sajip | 2010-12-03 14:01:11 +0100 (ven., 03 déc. 2010) | 1 line
  
  logging: tidied up some docstrings.
................
  r86970 | nick.coghlan | 2010-12-03 15:26:13 +0100 (ven., 03 déc. 2010) | 3 lines
  
  Issue 2690: Add support for slicing and negative indices to range objects (includes precalculation and storage of the range length).
  
  Refer to the tracker issue for the language moratorium implications of this change
................
  r86971 | nick.coghlan | 2010-12-03 15:30:41 +0100 (ven., 03 déc. 2010) | 1 line
  
  Add missing CSS file from r86962
................
  r86974 | georg.brandl | 2010-12-03 16:30:09 +0100 (ven., 03 déc. 2010) | 1 line
  
  Markup consistency fixes.
................
  r86975 | nick.coghlan | 2010-12-03 17:08:46 +0100 (ven., 03 déc. 2010) | 1 line
  
  Handle Windows paths and don't double up on HTML header sections in new pydoc URL handler
................
  r86976 | lukasz.langa | 2010-12-03 17:28:00 +0100 (ven., 03 déc. 2010) | 2 lines
  
  Issue 10499: Modular interpolation in configparser
................
  r86977 | victor.stinner | 2010-12-03 17:51:33 +0100 (ven., 03 déc. 2010) | 1 line
  
  #6780: fix complex() constructor TypeError message
................
  r86979 | victor.stinner | 2010-12-03 18:06:43 +0100 (ven., 03 déc. 2010) | 4 lines
  
  import: use PyUnicode_FSConverter to support bytes path and PEP 383
  
  (instead of PyArg_Parse*() with "es" format and Py_FileSystemDefaultEncoding)
................
  r86980 | georg.brandl | 2010-12-03 18:19:27 +0100 (ven., 03 déc. 2010) | 1 line
  
  Fix punctuation.
................
  r86981 | antoine.pitrou | 2010-12-03 19:41:39 +0100 (ven., 03 déc. 2010) | 5 lines
  
  Issue #10478: Reentrant calls inside buffered IO objects (for example by
  way of a signal handler) now raise a RuntimeError instead of freezing the
  current process.
................
  r86983 | terry.reedy | 2010-12-03 19:57:42 +0100 (ven., 03 déc. 2010) | 1 line
................
  r86984 | antoine.pitrou | 2010-12-03 20:14:17 +0100 (ven., 03 déc. 2010) | 3 lines
  
  Add an "advanced topics" section to the io doc.
................
  r86985 | eric.araujo | 2010-12-03 20:19:17 +0100 (ven., 03 déc. 2010) | 5 lines
  
  Fix incorrect use of gettext in argparse (#10497).
  
  Steven, the maintainer of argparse, agreed to have this committed
  without tests for now, since the fix is obvious.  See the bug log.
................
  r86986 | michael.foord | 2010-12-03 20:20:44 +0100 (ven., 03 déc. 2010) | 1 line
  
  Fix so that test.test_unittest can be executed by unittest and not just regrtest
................
  r86993 | eric.araujo | 2010-12-03 20:41:00 +0100 (ven., 03 déc. 2010) | 7 lines
  
  Allow translators to reorder placeholders in localizable messages from
  argparse (#10528).
  
  There is no unit test; I checked with xgettext that no more warnings
  were emitted.  Steven approved the change.
................
  r86996 | georg.brandl | 2010-12-03 20:56:42 +0100 (ven., 03 déc. 2010) | 1 line
  
  Fix indentation.
................
  r86997 | antoine.pitrou | 2010-12-03 20:59:41 +0100 (ven., 03 déc. 2010) | 4 lines
  
  Issue #10272: The ssl module now raises socket.timeout instead of a generic
  SSLError on socket timeouts.
................
  r86998 | martin.v.loewis | 2010-12-03 21:14:31 +0100 (ven., 03 déc. 2010) | 2 lines
  
  Merge branches/pep-0384.
................
  r86999 | lukasz.langa | 2010-12-03 23:15:19 +0100 (ven., 03 déc. 2010) | 3 lines
  
  %s -> %r correction after review by Éric Araujo
................
  r87000 | terry.reedy | 2010-12-03 23:29:40 +0100 (ven., 03 déc. 2010) | 3 lines
  
  Issue 10534 deprecate isbjunk and isbpopular methods.
  Will add gone in 3.3 test later.
................
  r87001 | terry.reedy | 2010-12-03 23:50:06 +0100 (ven., 03 déc. 2010) | 2 lines
  
  Issue #10534: add NEWS entry for r86983 and  r87000.
................
  r87002 | martin.v.loewis | 2010-12-04 00:11:07 +0100 (sam., 04 déc. 2010) | 21 lines
  
  Merged revisions 85551,86156-86157,86464 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
  
  ........
    r85551 | benjamin.peterson | 2010-10-15 23:57:29 +0200 (Fr, 15 Okt 2010) | 1 line
    
    escape() is now in the html module
  ........
    r86156 | georg.brandl | 2010-11-04 09:34:57 +0100 (Do, 04 Nov 2010) | 1 line
    
    Consistency fixes in option parser help texts.
  ........
    r86157 | georg.brandl | 2010-11-04 09:35:30 +0100 (Do, 04 Nov 2010) | 1 line
    
    #10286: fix urllib class names.
  ........
    r86464 | benjamin.peterson | 2010-11-14 16:28:52 +0100 (So, 14 Nov 2010) | 1 line
    
    match only .py files #10416
  ........
................
  r87003 | michael.foord | 2010-12-04 02:11:21 +0100 (sam., 04 déc. 2010) | 1 line
  
  Issue 10620: Specifying test modules by path instead of module name to 'python -m unittest'
................
  r87004 | michael.foord | 2010-12-04 02:43:59 +0100 (sam., 04 déc. 2010) | 1 line
  
  Correct comment in unittest test
................
  r87007 | alexander.belopolsky | 2010-12-04 04:38:46 +0100 (sam., 04 déc. 2010) | 5 lines
  
  Issue #10557: Fixed error messages from float() and other numeric
  types.  Added a new API function, PyUnicode_TransformDecimalToASCII(),
  which transforms non-ASCII decimal digits in a Unicode string to their
  ASCII equivalents.
................
  r87008 | georg.brandl | 2010-12-04 10:04:04 +0100 (sam., 04 déc. 2010) | 1 line
  
  Fix typo.
................
  r87009 | martin.v.loewis | 2010-12-04 10:08:10 +0100 (sam., 04 déc. 2010) | 2 lines
  
  Make script 2-vs-3-agnostic.
................
  r87010 | gregory.p.smith | 2010-12-04 10:10:44 +0100 (sam., 04 déc. 2010) | 11 lines
  
  issue7213 + issue2320: Cause a DeprecationWarning if the close_fds argument is
  not passed to subprocess.Popen as the default value will be changing in a
  future Python to the safer and more often desired value of True.
  
  DeprecationWarnings that show up in a lot of existing code are controversial
  and have caused pain in the past.  I'd like to leave this on for 3.2 beta1 and
  see how things go.  We can remove the warning if it is deemed too noisy during
  any betas.  (case study: the md5 and sha module DeprecationWarnings are loathed
  around the world as those modules were never going to be removed in 2.x and
  2to3 has a fixer for code that uses them)
................
  r87011 | martin.v.loewis | 2010-12-04 10:11:41 +0100 (sam., 04 déc. 2010) | 2 lines
  
  Add Revision keyword.
................
  r87012 | martin.v.loewis | 2010-12-04 10:12:14 +0100 (sam., 04 déc. 2010) | 2 lines
  
  Regenerate.
................
  r87013 | georg.brandl | 2010-12-04 10:14:36 +0100 (sam., 04 déc. 2010) | 1 line
  
  #6045: provide at least get() and setdefault() for all dbm modules.
................
  r87014 | senthil.kumaran | 2010-12-04 10:44:30 +0100 (sam., 04 déc. 2010) | 3 lines
  
  Add the NEWS entry for issue7904
................
  r87017 | gregory.p.smith | 2010-12-04 10:59:52 +0100 (sam., 04 déc. 2010) | 2 lines
  
  refactor the warning test.
................
  r87018 | hirokazu.yamamoto | 2010-12-04 11:16:05 +0100 (sam., 04 déc. 2010) | 6 lines
  
  Fixed several corner case issues on os.stat/os.lstat related to reparse
  points. (Windows)
  
  - Set S_IEXEC via final path name not link name.
  - Set S_IFLNK also via FindFirstFile (when CreateFile fails)
................
  r87019 | georg.brandl | 2010-12-04 11:26:46 +0100 (sam., 04 déc. 2010) | 1 line
  
  Add an "optimize" parameter to compile() to control the optimization level, and provide an interface to it in py_compile, compileall and PyZipFile.
................
  r87020 | georg.brandl | 2010-12-04 11:39:14 +0100 (sam., 04 déc. 2010) | 1 line
  
  #1513299: cleanup some map() uses where a comprehension works better.
................
  r87021 | georg.brandl | 2010-12-04 11:47:18 +0100 (sam., 04 déc. 2010) | 1 line
  
  #1772833: add -q command line option.
................
  r87022 | georg.brandl | 2010-12-04 12:02:04 +0100 (sam., 04 déc. 2010) | 1 line
  
  #1569291: speed up array.repeat() by making only O(log n) memcpy() calls; the code follows unicode_repeat.
................
  r87023 | mark.dickinson | 2010-12-04 12:06:25 +0100 (sam., 04 déc. 2010) | 1 line
  
  Fix indentation in Objects/longobject.c
................
  r87024 | georg.brandl | 2010-12-04 12:12:43 +0100 (sam., 04 déc. 2010) | 1 line
  
  #7905: Actually respect the keyencoding parameter to shelve.Shelf.
................
  r87025 | georg.brandl | 2010-12-04 12:20:26 +0100 (sam., 04 déc. 2010) | 1 line
  
  Add the "interact" pdb command from pdb++.
................
  r87026 | gregory.p.smith | 2010-12-04 12:22:11 +0100 (sam., 04 déc. 2010) | 3 lines
  
  issue6559: Adds a pass_fds parameter to subprocess.Popen that allows the caller
  to list exactly which file descriptors should be kept open.
................
  r87027 | gregory.p.smith | 2010-12-04 12:36:58 +0100 (sam., 04 déc. 2010) | 3 lines
  
  issue10622: fix superflous scrollbar on the right side of <pre> boxes in the
  generated html docs.  visible in chrome, possibly other webkit browsers.
................
  r87028 | lukasz.langa | 2010-12-04 12:48:11 +0100 (sam., 04 déc. 2010) | 3 lines
  
  configparser: minute refactoring of RawConfigParser.items()
................
  r87029 | mark.dickinson | 2010-12-04 12:52:58 +0100 (sam., 04 déc. 2010) | 1 line
  
  Remove some unecessary '#ifdef Py_NAN's from floatobject.c
................
  r87030 | martin.v.loewis | 2010-12-04 13:00:49 +0100 (sam., 04 déc. 2010) | 3 lines
  
  Expose CompileString, not CompileStringFlags under the
  limited API.
................
  r87031 | hirokazu.yamamoto | 2010-12-04 13:20:57 +0100 (sam., 04 déc. 2010) | 2 lines
  
  I hope this will fix Win2008(x64) buildbot error.
................
  r87032 | mark.dickinson | 2010-12-04 13:25:30 +0100 (sam., 04 déc. 2010) | 3 lines
  
  Issue #10596: Fix float.__mod__ to have the same behaviour as
  float.__divmod__ with respect to signed zeros.
................
  r87036 | lukasz.langa | 2010-12-04 13:46:01 +0100 (sam., 04 déc. 2010) | 5 lines
  
  configparser: fixed inconsistency where in SafeConfigParser option values
   were ensured to be strings but section names and option keys were not.
   Behaviour unchanged for RawConfigParser and ConfigParser.
................
  r87038 | mark.dickinson | 2010-12-04 14:14:29 +0100 (sam., 04 déc. 2010) | 1 line
  
  Use copysign to produce appropriately signed zeros instead of trying to worm around possible compiler optimizations.
................
  r87039 | eric.smith | 2010-12-04 14:27:34 +0100 (sam., 04 déc. 2010) | 1 line
  
  Removed static function complex_format, moved it into complex_repr. Modified tests to check both str and repr, which are the same for complex.
................
  r87040 | eric.smith | 2010-12-04 14:32:18 +0100 (sam., 04 déc. 2010) | 1 line
  
  Issue #10624: Move requires_IEEE_754 into test.support. I'll fix up other uses of it shortly.
................
  r87041 | lukasz.langa | 2010-12-04 14:48:13 +0100 (sam., 04 déc. 2010) | 4 lines
  
  support for checking test coverage added.
  70% coverage at the moment (not tragic but needs work).
................
  r87042 | martin.v.loewis | 2010-12-04 14:49:32 +0100 (sam., 04 déc. 2010) | 2 lines
  
  Fix PEP number.
................
  r87043 | eric.smith | 2010-12-04 16:17:38 +0100 (sam., 04 déc. 2010) | 1 line
  
  Issue #10624: Use support.requires_IEEE_754 in all appropriate tests.
................
  r87044 | eric.smith | 2010-12-04 16:26:13 +0100 (sam., 04 déc. 2010) | 1 line
  
  Issue 10625: Add tests for negative zeros in complex str and repr.
................
  r87045 | georg.brandl | 2010-12-04 17:00:47 +0100 (sam., 04 déc. 2010) | 1 line
  
  #7245: Add a SIGINT handler on continue in pdb that allows to break a program again by pressing Ctrl-C.
................
  r87047 | georg.brandl | 2010-12-04 17:21:42 +0100 (sam., 04 déc. 2010) | 1 line
  
  Add display/undisplay pdb commands.
................
  r87048 | georg.brandl | 2010-12-04 17:22:44 +0100 (sam., 04 déc. 2010) | 1 line
  
  Fix accidental checkin.
................
  r87050 | georg.brandl | 2010-12-04 18:09:30 +0100 (sam., 04 déc. 2010) | 1 line
  
  Fix typo.
................
  r87051 | georg.brandl | 2010-12-04 18:11:36 +0100 (sam., 04 déc. 2010) | 1 line
  
  Fix test suite to not activate new sigint behavior in pdb.
................
  r87052 | eric.smith | 2010-12-04 18:12:41 +0100 (sam., 04 déc. 2010) | 1 line
  
  More issue #10624: Add requires_IEEE_754 to __all__.
................
  r87054 | victor.stinner | 2010-12-04 18:24:33 +0100 (sam., 04 déc. 2010) | 3 lines
  
  Issue #10601: sys.displayhook uses 'backslashreplace' error handler on
  UnicodeEncodeError.
................
  r87056 | eric.araujo | 2010-12-04 18:31:49 +0100 (sam., 04 déc. 2010) | 2 lines
  
  Use proper plural forms in argparse (#4391)
................
  r87057 | lukasz.langa | 2010-12-04 18:48:18 +0100 (sam., 04 déc. 2010) | 2 lines
  
  configparser: mapping protocol access get() handles configparser-specific arguments as well
................
  r87058 | gregory.p.smith | 2010-12-04 19:11:44 +0100 (sam., 04 déc. 2010) | 2 lines
  
  clarify the docs and new warning message.
................
  r87059 | antoine.pitrou | 2010-12-04 19:36:03 +0100 (sam., 04 déc. 2010) | 3 lines
  
  Silence compile error
................
  r87060 | georg.brandl | 2010-12-04 20:01:29 +0100 (sam., 04 déc. 2010) | 1 line
  
  Update pydoc topics.
................
  r87062 | georg.brandl | 2010-12-04 20:06:14 +0100 (sam., 04 déc. 2010) | 1 line
  
  Update suspicious exceptions.
................
  r87063 | georg.brandl | 2010-12-04 20:06:18 +0100 (sam., 04 déc. 2010) | 1 line
  
  Fix markup errors.
................
  r87064 | georg.brandl | 2010-12-04 20:09:24 +0100 (sam., 04 déc. 2010) | 1 line
  
  Bump to 3.2b1.
................
  r87065 | raymond.hettinger | 2010-12-04 21:51:36 +0100 (sam., 04 déc. 2010) | 1 line
  
  Doc nit.
................
  r87066 | raymond.hettinger | 2010-12-04 23:56:25 +0100 (sam., 04 déc. 2010) | 1 line
  
  Fill-in stub for concurrent.futures
................
  r87067 | raymond.hettinger | 2010-12-05 00:42:12 +0100 (dim., 05 déc. 2010) | 1 line
  
  Mention itertools.accumulate().
................
  r87068 | raymond.hettinger | 2010-12-05 01:39:18 +0100 (dim., 05 déc. 2010) | 1 line
  
  Start the argparse entry.
................
  r87069 | raymond.hettinger | 2010-12-05 02:01:52 +0100 (dim., 05 déc. 2010) | 1 line
  
  Optimization of Timsort.
................
  r87070 | hirokazu.yamamoto | 2010-12-05 03:04:16 +0100 (dim., 05 déc. 2010) | 3 lines
  
  Now can reproduce the error on AMD64 Windows Server 2008
  even where os.symlink is not supported.
................
  r87071 | hirokazu.yamamoto | 2010-12-05 03:41:46 +0100 (dim., 05 déc. 2010) | 2 lines
  
  Avoid possible zombi process.
................
  r87072 | hirokazu.yamamoto | 2010-12-05 03:48:08 +0100 (dim., 05 déc. 2010) | 1 line
  
  Sorry, I had introduced tab in source code.
................
  r87073 | raymond.hettinger | 2010-12-05 03:56:21 +0100 (dim., 05 déc. 2010) | 1 line
  
  Note the updates to range objects.
................
  r87074 | raymond.hettinger | 2010-12-05 05:04:21 +0100 (dim., 05 déc. 2010) | 1 line
  
  Describe the transform/untranform methods
................
  r87075 | hirokazu.yamamoto | 2010-12-05 05:16:47 +0100 (dim., 05 déc. 2010) | 1 line
  
  Should use posix_error here.
................
  r87076 | raymond.hettinger | 2010-12-05 06:39:54 +0100 (dim., 05 déc. 2010) | 1 line
  
  Optimization notes.
................
  r87077 | raymond.hettinger | 2010-12-05 07:35:16 +0100 (dim., 05 déc. 2010) | 1 line
  
  New string format character.
................
  r87078 | nick.coghlan | 2010-12-05 07:45:03 +0100 (dim., 05 déc. 2010) | 2 lines
  
  Issue 10626 investigation: regrtest now checks for alterations to the logging state in the current process (and yes, test_pydoc alters it)
................
  r87079 | raymond.hettinger | 2010-12-05 08:02:45 +0100 (dim., 05 déc. 2010) | 1 line
  
  Update the unittest section.
................
  r87080 | raymond.hettinger | 2010-12-05 08:06:47 +0100 (dim., 05 déc. 2010) | 1 line
  
  Spelling
................
  r87081 | nick.coghlan | 2010-12-05 08:17:25 +0100 (dim., 05 déc. 2010) | 1 line
  
  More fine-grained monitoring of alterations to logging state
................
  r87082 | georg.brandl | 2010-12-05 08:51:39 +0100 (dim., 05 déc. 2010) | 1 line
  
  Temporarily disable newly failing test for the release.
................
  r87083 | georg.brandl | 2010-12-05 08:59:29 +0100 (dim., 05 déc. 2010) | 1 line
  
  Apply rest of #10628, and add a few todo comments.
................
  r87084 | raymond.hettinger | 2010-12-05 09:35:21 +0100 (dim., 05 déc. 2010) | 1 line
  
  Nits and todos
................
  r87086 | georg.brandl | 2010-12-05 12:40:48 +0100 (dim., 05 déc. 2010) | 1 line
  
  Take PyUnicode_TransformDecimalToASCII out of the limited API.
................
  r87088 | georg.brandl | 2010-12-05 12:42:38 +0100 (dim., 05 déc. 2010) | 1 line
  
  Fix title.
................
  r87093 | martin.v.loewis | 2010-12-06 00:07:58 +0100 (lun., 06 déc. 2010) | 2 lines
  
  Automate build for python3.dll.
  Package missing files.
................
  r87094 | raymond.hettinger | 2010-12-06 05:31:40 +0100 (lun., 06 déc. 2010) | 2 lines
  
  Typo fixups.
................
  r87101 | georg.brandl | 2010-12-06 23:02:48 +0100 (lun., 06 déc. 2010) | 1 line
  
  Remove visible XXX comments.
................
  r87102 | georg.brandl | 2010-12-06 23:25:25 +0100 (lun., 06 déc. 2010) | 1 line
  
  Don't use deprecated aliases.
................
  r87103 | raymond.hettinger | 2010-12-07 00:31:36 +0100 (mar., 07 déc. 2010) | 1 line
  
  Note improvements to the docs.
................
  r87104 | david.malcolm | 2010-12-07 01:32:04 +0100 (mar., 07 déc. 2010) | 2 lines
  
  Fix typo
................
  r87105 | raymond.hettinger | 2010-12-07 02:47:52 +0100 (mar., 07 déc. 2010) | 1 line
  
  Add entry for the new sysconfig module.
................
  r87106 | raymond.hettinger | 2010-12-07 03:04:56 +0100 (mar., 07 déc. 2010) | 1 line
  
  Add entry for new pdb features
................
  r87107 | benjamin.peterson | 2010-12-07 04:46:27 +0100 (mar., 07 déc. 2010) | 1 line
  
  return views from dict proxy items/values/keys #10630
................
  r87108 | benjamin.peterson | 2010-12-07 04:47:37 +0100 (mar., 07 déc. 2010) | 1 line
  
  add news note
................
  r87109 | benjamin.peterson | 2010-12-07 05:04:02 +0100 (mar., 07 déc. 2010) | 1 line
  
  use the more direct API
................
  r87110 | raymond.hettinger | 2010-12-07 07:45:30 +0100 (mar., 07 déc. 2010) | 1 line
  
  Add example for the entry for argparse
................
  r87112 | raymond.hettinger | 2010-12-07 09:52:41 +0100 (mar., 07 déc. 2010) | 1 line
  
  More cleanups and examples.
................
  r87113 | raymond.hettinger | 2010-12-07 10:24:30 +0100 (mar., 07 déc. 2010) | 2 lines
  
  Spelling.
................
  r87114 | raymond.hettinger | 2010-12-07 10:37:11 +0100 (mar., 07 déc. 2010) | 1 line
  
  Clean-ups and examples.
................
  r87115 | raymond.hettinger | 2010-12-07 10:44:21 +0100 (mar., 07 déc. 2010) | 1 line
  
  Make the example a little more interesting and useful.
................
  r87116 | raymond.hettinger | 2010-12-07 10:55:02 +0100 (mar., 07 déc. 2010) | 2 lines
  
  Martin's name with Unicode.
................
  r87117 | hirokazu.yamamoto | 2010-12-07 11:24:37 +0100 (mar., 07 déc. 2010) | 2 lines
  
  Issue #10637: Called CloseHandle twice in os.stat/os.lstat (Windows)
................
  r87118 | ronald.oussoren | 2010-12-07 15:41:05 +0100 (mar., 07 déc. 2010) | 14 lines
  
  Two small changes to adjust framework builds to the new stable ABI
  
  Both the Makefile and the script that is used on OSX to create the binary
  installer refer to the directory containing the Makefile using the name
  'config'. This name was changed with the new ABI (with default build flags
  it is now named config-3.2m).  This patch ensures that both files use the
  correct name.
  
  The build-installer.py script contains one other change: it now tests for the
  Tcl/Tk framework version by looking at the 'Current' symlink in the framework
  instead of runnning a script. This makes it possible to verify the version
  that is in the SDK that's used during the build instead of the version that
  is installed on the system.
................
  r87119 | ronald.oussoren | 2010-12-07 16:28:10 +0100 (mar., 07 déc. 2010) | 2 lines
  
  Fix for issue #10107: Without this patch IDLE on OSX doesn't warn about unsaved files when quitting.
................
  r87124 | raymond.hettinger | 2010-12-08 02:13:53 +0100 (mer., 08 déc. 2010) | 1 line
  
  Update whatsnew.  Salt the random number seed.
................
  r87125 | raymond.hettinger | 2010-12-08 07:42:41 +0100 (mer., 08 déc. 2010) | 2 lines
  
  Add example for concurrent.futures.
................
  r87126 | raymond.hettinger | 2010-12-08 07:48:33 +0100 (mer., 08 déc. 2010) | 1 line
  
  Clean-ups.
................
  r87127 | raymond.hettinger | 2010-12-08 07:50:02 +0100 (mer., 08 déc. 2010) | 1 line
  
  Nits.
................
  r87128 | senthil.kumaran | 2010-12-08 09:04:49 +0100 (mer., 08 déc. 2010) | 3 lines
  
  Fix Issue8194  - Fix incompatible API change in the parse_respones for xmlrpclib.
................
  r87129 | raymond.hettinger | 2010-12-08 11:18:21 +0100 (mer., 08 déc. 2010) | 1 line
  
  range() example
................
  r87130 | raymond.hettinger | 2010-12-08 12:19:45 +0100 (mer., 08 déc. 2010) | 1 line
  
  Example of argparge with subparsers.
................
  r87131 | raymond.hettinger | 2010-12-08 12:33:19 +0100 (mer., 08 déc. 2010) | 2 lines
  
  Entry for inspect.getattr_static().
................
  r87132 | hirokazu.yamamoto | 2010-12-08 15:47:07 +0100 (mer., 08 déc. 2010) | 3 lines
  
  Mention NASM which is needed to build openssl-1.0.0a original source.
  (PC/VC6/readme.txt)
................
  r87133 | alexander.belopolsky | 2010-12-08 22:21:56 +0100 (mer., 08 déc. 2010) | 1 line
  
  Added a datetime new features entry
................
  r87134 | alexander.belopolsky | 2010-12-08 22:38:46 +0100 (mer., 08 déc. 2010) | 1 line
  
  Edited the Unicode 6.0.0 entry to add unicode.org links and trim the summary.
................
  r87135 | victor.stinner | 2010-12-08 23:25:45 +0100 (mer., 08 déc. 2010) | 4 lines
  
  Issue #10546: UTF-16-LE and UTF-16-BE *do* support non-BMP characters
  
  Fix the doc and add tests.
................
  r87136 | r.david.murray | 2010-12-08 23:53:00 +0100 (mer., 08 déc. 2010) | 6 lines
  
  Have script_helper._assert_python strip refcount strings from stderr.
  
  This makes the output of the function and those that depend on it
  independent of whether or not they are being run under a debug
  build.
................
  r87137 | alexander.belopolsky | 2010-12-09 00:31:48 +0100 (jeu., 09 déc. 2010) | 1 line
  
  Issue #6697: Fixed instances of _PyUnicode_AsString() result not checked for NULL
................
  r87140 | hirokazu.yamamoto | 2010-12-09 11:49:00 +0100 (jeu., 09 déc. 2010) | 2 lines
  
  Should call Py_INCREF for Py_None (Modules/_ssl.c: PySSL_cipher)
................
  r87141 | hirokazu.yamamoto | 2010-12-09 12:13:30 +0100 (jeu., 09 déc. 2010) | 2 lines
  
  Fixed typo in comment.
................
  r87145 | raymond.hettinger | 2010-12-09 17:41:54 +0100 (jeu., 09 déc. 2010) | 2 lines
  
  Entries for datetime, callable, and collections.Counter.
................
  r87146 | georg.brandl | 2010-12-09 19:08:43 +0100 (jeu., 09 déc. 2010) | 1 line
  
  Fix "seperate".
................
  r87147 | georg.brandl | 2010-12-09 19:10:27 +0100 (jeu., 09 déc. 2010) | 1 line
  
  #10661: give QName a nicer repr.
................
  r87148 | georg.brandl | 2010-12-09 19:26:02 +0100 (jeu., 09 déc. 2010) | 1 line
  
  Guard against rogue tuples.
................
  r87149 | raymond.hettinger | 2010-12-10 00:43:34 +0100 (ven., 10 déc. 2010) | 1 line
  
  Doh! Example pasted twice, but only once in the right place.
................
  r87150 | raymond.hettinger | 2010-12-10 02:09:01 +0100 (ven., 10 déc. 2010) | 1 line
  
  Overview of email module and recategorize various entries.
................
  r87151 | raymond.hettinger | 2010-12-10 02:19:15 +0100 (ven., 10 déc. 2010) | 1 line
  
  Reclassify some entries and remove a couple of minor ones.
................
  r87152 | ezio.melotti | 2010-12-10 03:32:05 +0100 (ven., 10 déc. 2010) | 1 line
  
  #10273: Remove a "Matches" that I missed in r86910. Thanks to RDM for noticing it.
................
  r87153 | vinay.sajip | 2010-12-10 09:17:05 +0100 (ven., 10 déc. 2010) | 1 line
  
  Minor documentation tweak.
................
  r87154 | vinay.sajip | 2010-12-10 09:19:38 +0100 (ven., 10 déc. 2010) | 1 line
  
  test.support: Added TestHandler and Matcher classes for better support of assertions about logging.
................
  r87155 | vinay.sajip | 2010-12-10 10:11:23 +0100 (ven., 10 déc. 2010) | 1 line
  
  Fied typo
................
  r87156 | georg.brandl | 2010-12-10 11:01:44 +0100 (ven., 10 déc. 2010) | 1 line
  
  #10668: fix wrong call of __init__.
................
  r87157 | vinay.sajip | 2010-12-10 12:42:57 +0100 (ven., 10 déc. 2010) | 1 line
  
  logging: added handler of last resort.
................
  r87158 | raymond.hettinger | 2010-12-10 18:45:13 +0100 (ven., 10 déc. 2010) | 1 line
  
  Move nntp entry back to changed modules section and add entry for non-ascii import directories.
................
  r87159 | alexander.belopolsky | 2010-12-10 19:11:24 +0100 (ven., 10 déc. 2010) | 1 line
  
  Updated UCD version and unicode.org links to Unicode 6.0.0
................
  r87160 | alexander.belopolsky | 2010-12-10 19:14:16 +0100 (ven., 10 déc. 2010) | 1 line
  
  Reverted accidental commit (from r87159)
................
  r87161 | georg.brandl | 2010-12-10 20:22:11 +0100 (ven., 10 déc. 2010) | 1 line
  
  Fix typo.
................
  r87171 | martin.v.loewis | 2010-12-11 19:17:22 +0100 (sam., 11 déc. 2010) | 2 lines
  
  Adjust PySlice_GetIndices documentation to signature change.
................
  r87172 | georg.brandl | 2010-12-11 20:10:30 +0100 (sam., 11 déc. 2010) | 1 line
  
  Avoid AttributeError(_closed) when a TemporaryDirectory is deallocated whose mkdtemp call failed.
................
  r87173 | martin.v.loewis | 2010-12-11 20:22:04 +0100 (sam., 11 déc. 2010) | 2 lines
  
  Add versionchanged for parameter type changes.
................
  r87174 | barry.warsaw | 2010-12-11 22:32:01 +0100 (sam., 11 déc. 2010) | 4 lines
  
  Create the hardlink between python-3.2m and python-3.2 in altbininstall target
  instead of bininstall target so it shows up when you do 'make altinstall'.
  Closes issue 10677.
................
  r87175 | georg.brandl | 2010-12-11 23:19:34 +0100 (sam., 11 déc. 2010) | 1 line
  
  Fix markup.
................
  r87176 | benjamin.peterson | 2010-12-12 02:33:04 +0100 (dim., 12 déc. 2010) | 1 line
  
  remove (un)transform methods
................
  r87177 | benjamin.peterson | 2010-12-12 02:46:43 +0100 (dim., 12 déc. 2010) | 1 line
  
  having three copies of the same test is surely a bit excessive
................
  r87179 | vinay.sajip | 2010-12-12 14:20:55 +0100 (dim., 12 déc. 2010) | 1 line
  
  Logging documentation update.
................
  r87180 | vinay.sajip | 2010-12-12 14:25:29 +0100 (dim., 12 déc. 2010) | 1 line
  
  Logging documentation - further update.
................
  r87181 | vinay.sajip | 2010-12-12 14:49:39 +0100 (dim., 12 déc. 2010) | 1 line
  
  Logging documentation - further update.
................
  r87182 | nick.coghlan | 2010-12-12 16:24:21 +0100 (dim., 12 déc. 2010) | 2 lines
  
  Issue #10188 (partial resolution): tidy up some behaviour in the new tempfile.TemporaryDirectory context manager
................
  r87183 | vinay.sajip | 2010-12-12 18:37:27 +0100 (dim., 12 déc. 2010) | 1 line
  
  Logging documentation - further update.
................
  r87184 | antoine.pitrou | 2010-12-12 19:09:53 +0100 (dim., 12 déc. 2010) | 3 lines
  
  SET_LINENO was removed in 2.3
................
  r87185 | antoine.pitrou | 2010-12-12 19:12:40 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Remove reference to stuff which is already obsolete in 2.x.
................
  r87186 | antoine.pitrou | 2010-12-12 19:14:34 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Obsolete aliases needn't be documented
................
  r87188 | antoine.pitrou | 2010-12-12 19:25:25 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Make this a warning and fix indentation
................
  r87189 | antoine.pitrou | 2010-12-12 20:59:47 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Better explain the buffer interface (hopefully)
................
  r87190 | antoine.pitrou | 2010-12-12 21:01:43 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Add link to the buffer protocol description from the memory description.
................
  r87191 | r.david.murray | 2010-12-12 21:06:19 +0100 (dim., 12 déc. 2010) | 6 lines
  
  #243654: only create a new MIME boundary if we don't already have one.
  
  The rearranged code should do exactly what the old code did, but
  the new code avoids a potentially costly re computation in the case
  where a boundary already exists.
................
  r87192 | antoine.pitrou | 2010-12-12 21:09:18 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Remove redundant sentence, and fix markup
................
  r87193 | antoine.pitrou | 2010-12-12 21:13:31 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Fix heading level
................
  r87194 | antoine.pitrou | 2010-12-12 21:17:29 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Consistent ordering of availability statements
................
  r87197 | antoine.pitrou | 2010-12-12 21:34:49 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Homogenize the "optional OS services" menu
................
  r87198 | antoine.pitrou | 2010-12-12 21:57:12 +0100 (dim., 12 déc. 2010) | 3 lines
  
  Improve readability of the socket docs
................
  r87201 | vinay.sajip | 2010-12-12 23:30:17 +0100 (dim., 12 déc. 2010) | 1 line
  
  Logging documentation - further update.
................
  r87202 | vinay.sajip | 2010-12-12 23:45:35 +0100 (dim., 12 déc. 2010) | 1 line
  
  Logging documentation - further update.
................
  r87203 | vinay.sajip | 2010-12-12 23:47:13 +0100 (dim., 12 déc. 2010) | 1 line
  
  Logging documentation - further update.
................
  r87204 | nick.coghlan | 2010-12-13 04:02:43 +0100 (lun., 13 déc. 2010) | 1 line
  
  Actually finish the tests for r87182
................
  r87205 | kristjan.jonsson | 2010-12-13 04:32:10 +0100 (lun., 13 déc. 2010) | 8 lines
  
  issue 10683
  When the solution is converted to Visual Studio 2010, the command line to invoke make_buildinfo changes from:
  $(SolutionDir)make_buildinfo.exe" Debug "$(IntDir)\"
  to
  $(SolutionDir)make_buildinfo.exe" Debug "$(IntDir)"
  If the final backslash is omitted, the backslash in IntDir will escape the quote, thus passing the quote in as part of the path name.
  
  This solution is a hack-fix to that problem by skipping any trailing quote from the path name.  It works as long as we don't need any additional arguments to make_buildinfo.exe.  This will help all those sould that are going to run this project through the visual studio autoconverter and get the same error.
................
  r87206 | gregory.p.smith | 2010-12-13 07:45:02 +0100 (lun., 13 déc. 2010) | 5 lines
  
  Get rid of the close_fds DeprecationWarning.  Changes the default on a per
  platform basis.  It remains False on Windows and changes to True on all
  other platforms (POSIX).  Based on python-dev discussion and
  http://bugs.python.org/issue7213.
................
  r87207 | gregory.p.smith | 2010-12-13 08:59:39 +0100 (lun., 13 déc. 2010) | 4 lines
  
  issue7213: Open the pipes used by subprocesses with the FD_CLOEXEC flag from
  the C code, using pipe2() when available.  Adds unittests for close_fds and
  cloexec behaviors.
................
  r87208 | gregory.p.smith | 2010-12-13 09:00:52 +0100 (lun., 13 déc. 2010) | 2 lines
  
  regenerate configure based on r87207.
................
  r87209 | gregory.p.smith | 2010-12-13 09:07:14 +0100 (lun., 13 déc. 2010) | 2 lines
  
  Mention the subprocess.Popen close_fds default change.  Fixup *s to -s.
................
  r87210 | vinay.sajip | 2010-12-13 09:54:02 +0100 (lun., 13 déc. 2010) | 1 line
  
  Logging documentatio update.
................
  r87212 | nick.coghlan | 2010-12-13 17:32:51 +0100 (lun., 13 déc. 2010) | 1 line
  
  Captured IO streams with embedded backslashes are always such a fun combination...
................
  r87213 | barry.warsaw | 2010-12-13 19:04:23 +0100 (lun., 13 déc. 2010) | 6 lines
  
  Issue 10687.  When --without-pymalloc is given, $VERSION is the same as
  $LDVERSION, which screws up the sym/hard-links.  This avoids those games when
  $VERSION == $LDVERSION.
  
  Also, include a drive-by fix for an obvious syntax error.
................
  r87214 | vinay.sajip | 2010-12-13 19:43:57 +0100 (lun., 13 déc. 2010) | 1 line
  
  Logging documentation update.
................
  r87215 | vinay.sajip | 2010-12-13 19:49:08 +0100 (lun., 13 déc. 2010) | 1 line
  
  Logging documentation update.
................
  r87216 | r.david.murray | 2010-12-13 23:50:30 +0100 (lun., 13 déc. 2010) | 2 lines
  
  #10698: fix typo in example.
................
  r87217 | r.david.murray | 2010-12-14 00:51:19 +0100 (mar., 14 déc. 2010) | 5 lines
  
  #1078919: make add_header automatically do RFC2231 encoding when needed.
  
  Also document the use of three-tuples if control of the charset
  and language is desired.
................
  r87221 | r.david.murray | 2010-12-14 01:55:46 +0100 (mar., 14 déc. 2010) | 4 lines
  
  #10699: fix docstring for tzset: it does not take a parameter
  
  Thanks to Garrett Cooper for the fix.
................
  r87222 | r.david.murray | 2010-12-14 02:22:50 +0100 (mar., 14 déc. 2010) | 2 lines
  
  Use skipIf instead of a return when attribute doesn't exist.
................
  r87225 | r.david.murray | 2010-12-14 02:38:16 +0100 (mar., 14 déc. 2010) | 2 lines
  
  9162: fix license in multiprocessing files
................
  r87228 | r.david.murray | 2010-12-14 03:25:43 +0100 (mar., 14 déc. 2010) | 2 lines
  
  Turn on regrtest -W (rerun immediately) option for Windows, too.
................
  r87229 | gregory.p.smith | 2010-12-14 14:43:30 +0100 (mar., 14 déc. 2010) | 7 lines
  
  Issue #6559: fix the subprocess.Popen pass_fds implementation. Add a unittest.
  Issue #7213: Change the close_fds default on Windows to better match the new
  default on POSIX.  True when possible (False if stdin/stdout/stderr are
  supplied).
  
  Update the documentation to reflect all of the above.
................
  r87230 | r.david.murray | 2010-12-14 15:16:20 +0100 (mar., 14 déc. 2010) | 7 lines
  
  #10695: use %s not %d so that a string 'port' does not cause a debug traceback
  
  Passing the port as a string value works fine in regular mode, but
  if you turned debug on it would throw an error trying to print the
  port number, which is surprising and confusing.
................
  r87233 | gregory.p.smith | 2010-12-14 15:38:00 +0100 (mar., 14 déc. 2010) | 4 lines
  
  Issue #1731717: Fixed the problem where subprocess.wait() could cause an
  OSError exception when The OS had been told to ignore SIGCLD in our process
  or otherwise not wait for exiting child processes.
................
  r87236 | gregory.p.smith | 2010-12-14 16:23:02 +0100 (mar., 14 déc. 2010) | 2 lines
  
  Fix "BytesWarning: str() on a bytes instance"
................
  r87238 | r.david.murray | 2010-12-14 17:20:53 +0100 (mar., 14 déc. 2010) | 7 lines
  
  #775964: skip YP/NIS entries instead of failing the test
  
  Also includes doc updates mentioning that these entries may not
  be retrievable via getgrnam and getgrgid.
  
  Patch by Bobby Impollonia.
................
  r87241 | gregory.p.smith | 2010-12-14 19:18:49 +0100 (mar., 14 déc. 2010) | 2 lines
  
  SIGCHLD is a more portable name than SIGCLD.  (OSX has no SIGCLD)
................
  r87245 | vinay.sajip | 2010-12-14 20:40:21 +0100 (mar., 14 déc. 2010) | 1 line
  
  Logging documentation update.
................
  r87246 | raymond.hettinger | 2010-12-14 22:12:03 +0100 (mar., 14 déc. 2010) | 1 line
  
  Nits
................
  r87247 | antoine.pitrou | 2010-12-14 23:06:10 +0100 (mar., 14 déc. 2010) | 3 lines
  
  Freshen README contents
................
  r87248 | r.david.murray | 2010-12-14 23:32:50 +0100 (mar., 14 déc. 2010) | 2 lines
  
  More comprehensive compileall cli tests, and fixes.
................
  r87251 | r.david.murray | 2010-12-15 00:06:25 +0100 (mer., 15 déc. 2010) | 4 lines
  
  #4236: avoid possible Fatal Error when import is called from __del__
  
  Patch by Simon Cross, crasher test code by Martin von Löwis.
................
  r87256 | r.david.murray | 2010-12-15 03:19:14 +0100 (mer., 15 déc. 2010) | 2 lines
  
  #10705: document what the values of debuglevel are and mean.
................
  r87258 | andrew.kuchling | 2010-12-15 03:37:01 +0100 (mer., 15 déc. 2010) | 1 line
  
  Typo fix
................
  r87260 | senthil.kumaran | 2010-12-15 05:02:45 +0100 (mer., 15 déc. 2010) | 6 lines
  
  TIMEOUT value change in URLTimeout Test. test.support.transient_internet has a
  socket timeout of 30 when it checks for resource.  Explicit overrding (like
  setting the 10) wont exhibit consistent behavior when tests are outside context
  manager. So, settting it 30.
................
  r87261 | antoine.pitrou | 2010-12-15 16:33:18 +0100 (mer., 15 déc. 2010) | 4 lines
  
  Issue #10706: Remove outdated script runtests.sh.  Either `make test`
  or `python -m test` should be used instead.
................
  r87262 | antoine.pitrou | 2010-12-15 16:42:59 +0100 (mer., 15 déc. 2010) | 3 lines
  
  Remove outdated compatibility file.
................
  r87263 | antoine.pitrou | 2010-12-15 16:47:34 +0100 (mer., 15 déc. 2010) | 3 lines
  
  Encourage --with-pydebug rather than individual setting of debug options.
................
  r87264 | antoine.pitrou | 2010-12-15 16:48:20 +0100 (mer., 15 déc. 2010) | 3 lines
  
  I don't think we need to ship the comp.lang.python RFD these days.
................
  r87265 | raymond.hettinger | 2010-12-15 17:30:37 +0100 (mer., 15 déc. 2010) | 1 line
  
  Issue 10667: Fast path for collections.Counter
................
  r87266 | raymond.hettinger | 2010-12-15 18:54:13 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Add entries for the random module and the collections module.
................
  r87267 | raymond.hettinger | 2010-12-15 19:20:19 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Adopt Antoine's suggestion to improve readability with module subsections.
................
  r87268 | raymond.hettinger | 2010-12-15 19:31:57 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Minor regroupings.
................
  r87269 | raymond.hettinger | 2010-12-15 20:00:38 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Move email section in with other modules.  Fix markup.
................
  r87270 | antoine.pitrou | 2010-12-15 20:07:26 +0100 (mer., 15 déc. 2010) | 3 lines
  
  Move the urllib-inherited API to a distinguished section
................
  r87271 | eric.araujo | 2010-12-15 20:09:58 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Improve trace documentation (#9264).  Patch by Eli Bendersky.
................
  r87272 | raymond.hettinger | 2010-12-15 20:20:01 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Add intro to the changed modules section.
................
  r87273 | eric.araujo | 2010-12-15 20:30:15 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Use nested method directives, rewrap long lines, fix whitespace.
................
  r87274 | raymond.hettinger | 2010-12-15 20:33:49 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Elaborate on the calculation used in the random module.
................
  r87275 | alexander.belopolsky | 2010-12-15 20:47:37 +0100 (mer., 15 déc. 2010) | 1 line
  
  Use sentence case in section titles consistently
................
  r87276 | terry.reedy | 2010-12-15 21:18:10 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Issue 10534, difflib: tweak doc; test new SequenceMatcher instance attributes; avoid unneeded lists of SM.b2j keys and items in .__chain_b. Do not backport.
................
  r87277 | eric.araujo | 2010-12-15 21:26:30 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Fix wrong name in docstring and doc (#10693).  Original patch by Eli Bendersky.
................
  r87280 | eric.araujo | 2010-12-15 22:07:22 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Fix build_ext with VS 8.0.  Patch by Hirokazu Yamamoto (#9558).
................
  r87283 | eric.araujo | 2010-12-15 23:06:35 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Add disclaimer about MinGW compat in distutils docs (#6007).  Patch by Chris Lambacher.
................
  r87284 | raymond.hettinger | 2010-12-15 23:07:15 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Add entries for structseq, ContextDecorator, and various C-API changes.
................
  r87288 | raymond.hettinger | 2010-12-15 23:35:03 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Entry for decimal and fractions.
................
  r87289 | eric.araujo | 2010-12-15 23:37:27 +0100 (mer., 15 déc. 2010) | 2 lines
  
  Mark up one missed None in pkgutil.rst (#8851)
................
  r87292 | antoine.pitrou | 2010-12-15 23:59:16 +0100 (mer., 15 déc. 2010) | 4 lines
  
  Issue #8844: Regular and recursive lock acquisitions can now be interrupted
  by signals on platforms using pthreads.  Patch by Reid Kleckner.
................
  r87293 | antoine.pitrou | 2010-12-16 00:38:50 +0100 (jeu., 16 déc. 2010) | 3 lines
  
  Make test_threadsignals more lax, and add notes
................
  r87294 | eric.araujo | 2010-12-16 01:07:01 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  No need to generate a link for something that’s just above.
................
  r87295 | raymond.hettinger | 2010-12-16 01:21:08 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  Entries for ElementTree, collectionsm, functools and ZipFile.
................
  r87296 | eric.araujo | 2010-12-16 01:23:30 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  Advertise “python -m” instead of direct filename.
................
  r87297 | raymond.hettinger | 2010-12-16 01:30:53 +0100 (jeu., 16 déc. 2010) | 1 line
  
  Nits
................
  r87298 | raymond.hettinger | 2010-12-16 01:53:05 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  Thank you ispell.
................
  r87299 | lukasz.langa | 2010-12-16 02:16:22 +0100 (jeu., 16 déc. 2010) | 4 lines
  
  Broken ConfigParser removed, SafeConfigParser renamed to ConfigParser.
  Life is beatiful once again.
................
  r87300 | eric.araujo | 2010-12-16 02:40:26 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  Advertise “python -m test” over test.regrtest (r87296 followup)
................
  r87301 | lukasz.langa | 2010-12-16 02:42:36 +0100 (jeu., 16 déc. 2010) | 3 lines
  
  Acknowledged renaming of SafeConfigParser to ConfigParser.
................
  r87302 | eric.araujo | 2010-12-16 03:10:11 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  Add versionadded directive missing from r78983.
................
  r87303 | raymond.hettinger | 2010-12-16 03:24:12 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  Improve the ContextDecorator example.
................
  r87304 | eric.araujo | 2010-12-16 04:13:05 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  Fix one versionchanged
................
  r87306 | brian.curtin | 2010-12-16 04:24:49 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  EasyDialogs was removed in 3.x. fallback_getpass will always be the answer here.
................
  r87312 | eric.araujo | 2010-12-16 07:28:48 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  Add missing docs and directives related to PEP 3147 and byte-compilation
................
  r87315 | raymond.hettinger | 2010-12-16 11:06:11 +0100 (jeu., 16 déc. 2010) | 1 line
  
  Add todo for WSGI
................
  r87316 | antoine.pitrou | 2010-12-16 14:33:56 +0100 (jeu., 16 déc. 2010) | 3 lines
  
  Credit Florent for porting
................
  r87317 | antoine.pitrou | 2010-12-16 17:48:36 +0100 (jeu., 16 déc. 2010) | 4 lines
  
  Issue #10714: Limit length of incoming request in http.server to 65536 bytes
  for security reasons.  Initial patch by Ross Lagerwall.
................
  r87323 | antoine.pitrou | 2010-12-16 19:25:24 +0100 (jeu., 16 déc. 2010) | 3 lines
  
  Issue #10710: `Misc/setuid-prog.c` is removed from the source tree.
................
  r87324 | r.david.murray | 2010-12-16 20:08:51 +0100 (jeu., 16 déc. 2010) | 9 lines
  
  #10719: restore messages generated on invalid compileall args
  
  Before the introduction of filename arguments to compileall it gave semi useful
  messages about not being able to 'list' names that weren't valid directories.
  This fix restores that behavior.  In addition to the test for this case, the
  patch also adds a test for the default behavior of compileall when no arguments
  are provided, and fixes a bug in one of the previously added tests.
................
  r87327 | gregory.p.smith | 2010-12-16 20:23:05 +0100 (jeu., 16 déc. 2010) | 2 lines
  
  assert that the regex given to assertRegex is non-empty.
................
  r87328 | lukasz.langa | 2010-12-17 02:32:29 +0100 (ven., 17 déc. 2010) | 5 lines
  
  configparser API cleanup: default values now sensible, slightly incompatible.
  Backwards compatible alternative values possible as documented.
  Done by Łukasz Langa, approved by Raymond and Fred.
................
  r87329 | senthil.kumaran | 2010-12-17 05:48:45 +0100 (ven., 17 déc. 2010) | 3 lines
  
  Fix Issue9721 - urljoin behavior when the relative url starts with ';'
................
  r87337 | r.david.murray | 2010-12-17 17:11:40 +0100 (ven., 17 déc. 2010) | 2 lines
  
  #10559: provide instructions for accessing sys.argv when first mentioned.
................
  r87338 | r.david.murray | 2010-12-17 17:29:07 +0100 (ven., 17 déc. 2010) | 2 lines
  
  #10454: clarify the compileall docs and help messages.
................
  r87339 | daniel.stutzbach | 2010-12-17 17:31:32 +0100 (ven., 17 déc. 2010) | 1 line
  
  Issue 8753: Added documentation for Py_ReprEntr and Py_ReprLeave.
................
  r87340 | antoine.pitrou | 2010-12-17 18:35:56 +0100 (ven., 17 déc. 2010) | 4 lines
  
  Issue #10711: Remove HTTP 0.9 support from http.client.  The `strict`
  parameter to HTTPConnection and friends is deprecated.
................
  r87341 | antoine.pitrou | 2010-12-17 18:42:16 +0100 (ven., 17 déc. 2010) | 4 lines
  
  Issue #4188: Avoid creating dummy thread objects when logging operations
  from the threading module (with the internal verbose flag activated).
................
  r87344 | raymond.hettinger | 2010-12-17 21:19:50 +0100 (ven., 17 déc. 2010) | 1 line
  
  Expand the LBYL glossary entry.
................
  r87345 | martin.v.loewis | 2010-12-17 21:43:27 +0100 (ven., 17 déc. 2010) | 1 line
  
  Upgrade Tcl/Tk to 8.5.9.
................
  r87346 | daniel.stutzbach | 2010-12-17 21:53:03 +0100 (ven., 17 déc. 2010) | 1 line
  
  Issue2690: Update docs to reflect the change made by issue2690.
................
  r87348 | martin.v.loewis | 2010-12-17 22:04:09 +0100 (ven., 17 déc. 2010) | 1 line
  
  Upgrade to sqlite3 3.7.4.
................
  r87350 | lukasz.langa | 2010-12-17 22:56:32 +0100 (ven., 17 déc. 2010) | 3 lines
  
  100% test coverage, better mapping protocol compatibility, some minor bugfixes
................
  r87351 | lukasz.langa | 2010-12-17 22:57:32 +0100 (ven., 17 déc. 2010) | 3 lines
  
  configparser hype coming up!
................
  r87352 | lukasz.langa | 2010-12-17 23:05:46 +0100 (ven., 17 déc. 2010) | 3 lines
  
  fix for an embarrassing autoformatting SNAFU. Thanks for your alertness, Antoine.
................
  r87353 | victor.stinner | 2010-12-17 23:24:30 +0100 (ven., 17 déc. 2010) | 1 line
  
  update .gitignore using .hgignore
................
  r87354 | daniel.stutzbach | 2010-12-17 23:28:07 +0100 (ven., 17 déc. 2010) | 1 line
  
  Fix typo
................
  r87355 | raymond.hettinger | 2010-12-18 00:31:30 +0100 (sam., 18 déc. 2010) | 1 line
  
  Add link to a sample solution to a common problem.
................
  r87356 | r.david.murray | 2010-12-18 04:48:32 +0100 (sam., 18 déc. 2010) | 11 lines
  
  #9907: call rl_initialize early when using editline on OSX
  
  editline rl_initialize apparently discards any mappings done before it
  is called, which makes tab revert to file completion instead of inserting
  a tab.  So now on OSX we call rl_initialize first if we are using
  readline, and then re-read the users .editrc (if any) afterward so they
  can still override our defaults.
  
  Patch by Ned Deily, modified by Ronald Oussoren.
................
  r87359 | raymond.hettinger | 2010-12-18 10:41:32 +0100 (sam., 18 déc. 2010) | 1 line
  
  Enhance argparse example to show aliases.
................
  r87360 | raymond.hettinger | 2010-12-18 11:48:26 +0100 (sam., 18 déc. 2010) | 2 lines
  
  Minor wordsmithing and markup fix-ups.
................
  r87361 | raymond.hettinger | 2010-12-18 11:57:50 +0100 (sam., 18 déc. 2010) | 2 lines
  
  Minor markup and wording fixups.
................
  r87362 | steven.bethard | 2010-12-18 12:19:23 +0100 (sam., 18 déc. 2010) | 1 line
  
  Add subparser aliases for argparse. Resolves issue 9324. Approved by Georg for beta2 on the tracker.
................
  r87363 | raymond.hettinger | 2010-12-18 12:20:52 +0100 (sam., 18 déc. 2010) | 2 lines
  
  Nits.
................
  r87364 | georg.brandl | 2010-12-18 12:53:25 +0100 (sam., 18 déc. 2010) | 1 line
  
  Add attribution.
................
  r87365 | georg.brandl | 2010-12-18 12:58:12 +0100 (sam., 18 déc. 2010) | 1 line
  
  Typo fix.
................
  r87366 | georg.brandl | 2010-12-18 13:01:15 +0100 (sam., 18 déc. 2010) | 1 line
  
  Use kbd role.
................
  r87367 | antoine.pitrou | 2010-12-18 13:33:06 +0100 (sam., 18 déc. 2010) | 3 lines
  
  Make this a note again.
................
  r87368 | ezio.melotti | 2010-12-18 15:59:43 +0100 (sam., 18 déc. 2010) | 1 line
  
  #5587: add a repr to dict_proxy objects.  Patch by David Stanek and Daniel Urban.
................
  r87371 | georg.brandl | 2010-12-18 17:21:58 +0100 (sam., 18 déc. 2010) | 1 line
  
  Fix typo.
................
  r87372 | r.david.murray | 2010-12-18 17:39:06 +0100 (sam., 18 déc. 2010) | 2 lines
  
  #10728: the default for printing help is sys.stdout, not stderr.
................
  r87373 | senthil.kumaran | 2010-12-18 17:55:23 +0100 (sam., 18 déc. 2010) | 3 lines
  
  Fix Issue6791 - Limit the HTTP header readline with _MAXLENGTH. Patch by Antoine Pitrou
................
  r87374 | r.david.murray | 2010-12-18 18:19:10 +0100 (sam., 18 déc. 2010) | 8 lines
  
  #10404: Use ctl-button-1 for context menus on OSX Idle.
  
  This provides access to the context menus where they previously could
  not be accessed due to the way OSX Tk binds buttons.  It also
  improves platform consistency.
  
  Patch by Ned Deily.
................
  r87377 | ezio.melotti | 2010-12-18 18:31:58 +0100 (sam., 18 déc. 2010) | 1 line
  
  Use lowercase true/false in assertTrue/assertFalse messages.
................
  r87378 | georg.brandl | 2010-12-18 18:51:28 +0100 (sam., 18 déc. 2010) | 1 line
  
  #10723: add missing builtin exceptions.
................
  r87381 | antoine.pitrou | 2010-12-18 18:59:18 +0100 (sam., 18 déc. 2010) | 3 lines
  
  NEWS entry for r87373	
................
  r87384 | r.david.murray | 2010-12-18 19:25:38 +0100 (sam., 18 déc. 2010) | 12 lines
  
  #9286: Fix the rfc822 parser to preserve whitespace in address local part.
  
  Such addresses are not RFC compliant except under the 'obsolete syntax'
  rules, but before this fix the whitespace was dropped from the input,
  concatenating the pieces.  That breaks one of the principles of the
  email package, that of preserving the input as much as possible.
  It also denies the application program the opportunity to apply its
  own heuristics to interpretation of such non-compliant addresses.
  
  It is possible users of the email package were depending on the local
  part always being a single token, so this fix will not be backported.
................
  r87389 | ezio.melotti | 2010-12-18 21:00:04 +0100 (sam., 18 déc. 2010) | 1 line
  
  #10573: use actual/expected consistently in unittest methods. The order of the args of assertCountEqual is also changed.
................
  r87390 | michael.foord | 2010-12-19 04:19:47 +0100 (dim., 19 déc. 2010) | 1 line
  
  Issue 10611. Issue 9857. Improve the way exception handling, including test skipping, is done inside TestCase.run
................
  r87391 | michael.foord | 2010-12-19 04:59:10 +0100 (dim., 19 déc. 2010) | 1 line
  
  Fix minor issue in implementation of issue 10470.
................
  r87392 | michael.foord | 2010-12-19 05:07:28 +0100 (dim., 19 déc. 2010) | 1 line
  
  Improvement to fix for issue 9926 to allow TestResult to be reused.
................
  r87393 | vinay.sajip | 2010-12-19 07:02:31 +0100 (dim., 19 déc. 2010) | 1 line
  
  Logging documentation update.
................
  r87394 | georg.brandl | 2010-12-19 11:10:32 +0100 (dim., 19 déc. 2010) | 1 line
  
  #6075: make idle work with both Carbon AquaTk and Cocoa AquaTk. Patch by Kevin Walzer and Ned Deily.
................
  r87395 | georg.brandl | 2010-12-19 11:17:46 +0100 (dim., 19 déc. 2010) | 1 line
  
  Temporarily skip test failing with newer ttk.
................
  r87396 | georg.brandl | 2010-12-19 11:25:28 +0100 (dim., 19 déc. 2010) | 1 line
  
  Update pydoc topics.
................
  r87397 | georg.brandl | 2010-12-19 11:28:46 +0100 (dim., 19 déc. 2010) | 1 line
  
  Fix markup error and update suspicious file.
................
  r87398 | georg.brandl | 2010-12-19 11:30:28 +0100 (dim., 19 déc. 2010) | 1 line
  
  Bump to 3.2b2.
................
  r87399 | senthil.kumaran | 2010-12-19 11:49:52 +0100 (dim., 19 déc. 2010) | 3 lines
  
  Issue3243 - Support iterable bodies in httplib. Patch contributions by Xuanji Li and Chris AtLee.
................
  r87400 | georg.brandl | 2010-12-19 13:33:52 +0100 (dim., 19 déc. 2010) | 1 line
  
  #3243 follow-up: remove debugging print and fix docs; data is a bytes object.
................
  r87402 | vinay.sajip | 2010-12-19 13:56:57 +0100 (dim., 19 déc. 2010) | 1 line
  
  Logging documentation reorganised.
................
  r87403 | vinay.sajip | 2010-12-19 14:41:26 +0100 (dim., 19 déc. 2010) | 1 line
  
  Logging documentation updates.
................
  r87408 | r.david.murray | 2010-12-20 19:08:59 +0100 (lun., 20 déc. 2010) | 8 lines
  
  Make test_compileall more robust by using -S to keep sys.path minimized.
  
  Arfrever Taifersar Arahesis reported that test_compileall failed during Gentoo
  install because it was tyring to write .pyc files to a read-only system
  directory during test_no_args_compiles_path.  Having subprocess call python
  with -S should eliminate the system directories from the path.
................
  r87411 | r.david.murray | 2010-12-20 20:04:51 +0100 (lun., 20 déc. 2010) | 2 lines
  
  Revert incorrect patch made at the wrong time.
................
  r87415 | r.david.murray | 2010-12-21 19:07:59 +0100 (mar., 21 déc. 2010) | 4 lines
  
  Fix the change made for issue 1243654.
  
  Surprisingly, it turns out there was no test that exercised this code path.
................
  r87418 | r.david.murray | 2010-12-21 19:24:33 +0100 (mar., 21 déc. 2010) | 10 lines
  
  Make test_compileall more robust by using -S to keep sys.path minimized.
  
  Try this again, hopefully the right way this time.
  
  Arfrever Taifersar Arahesis reported that test_compileall failed during Gentoo
  install because it was tyring to write .pyc files to a read-only system
  directory during test_no_args_compiles_path.  Having the tests call python
  with -S should eliminate the system directories from the path.
................
  r87421 | antoine.pitrou | 2010-12-21 19:49:01 +0100 (mar., 21 déc. 2010) | 4 lines
  
  Suggest sys.maxsize as a reliable way to know whether the interpreter is 64-bit.
  (part of #10735)
................
  r87424 | raymond.hettinger | 2010-12-21 20:24:26 +0100 (mar., 21 déc. 2010) | 1 line
  
  Deprecate assertDictContainsSubset()
................
  r87425 | raymond.hettinger | 2010-12-21 21:09:55 +0100 (mar., 21 déc. 2010) | 2 lines
  
  Reference the release schedule
................
  r87426 | raymond.hettinger | 2010-12-21 21:52:12 +0100 (mar., 21 déc. 2010) | 2 lines
  
  Document the alternate format for :ref:.
................
  r87427 | antoine.pitrou | 2010-12-21 22:20:59 +0100 (mar., 21 déc. 2010) | 3 lines
  
  Issue #10750: The `raw` attribute of buffered IO objects is now read-only.
................
  r87430 | r.david.murray | 2010-12-21 22:53:37 +0100 (mar., 21 déc. 2010) | 9 lines
  
  #4871: check that zipfile password is bytes, and give useful error message.
  
  Previously passing a string in as the password would fail either with
  an assertion error or a TypeError with a confusing error message.
  Note that a string can't be accepted since zipfile has no way to
  guess what encoding should be used to turn it into bytes.
  
  Patch by Victor Stinner.
................
  r87433 | alexander.belopolsky | 2010-12-22 02:37:36 +0100 (mer., 22 déc. 2010) | 3 lines
  
  Both PEP 3131 and the current implementation use NFKC normalization
  for identifiers.  Fixed the documentation to agree.
................
  r87435 | alexander.belopolsky | 2010-12-22 03:35:20 +0100 (mer., 22 déc. 2010) | 1 line
  
  Removed unneeded #include
................
  r87436 | gregory.p.smith | 2010-12-22 06:22:17 +0100 (mer., 22 déc. 2010) | 2 lines
  
  fix a compiler warning about err_msg potentially being used uninitialized.
................
  r87437 | raymond.hettinger | 2010-12-22 10:11:54 +0100 (mer., 22 déc. 2010) | 2 lines
  
  Add todo
................
  r87438 | michael.foord | 2010-12-22 11:39:04 +0100 (mer., 22 déc. 2010) | 1 line
  
  Minor typo corrections in whatsnew
................
  r87439 | vinay.sajip | 2010-12-22 16:04:15 +0100 (mer., 22 déc. 2010) | 1 line
  
  Logging documentation updates.
................
  r87440 | michael.foord | 2010-12-22 19:28:51 +0100 (mer., 22 déc. 2010) | 1 line
  
  Another trivial typo correction in whatsnew
................
  r87441 | antoine.pitrou | 2010-12-22 23:19:15 +0100 (mer., 22 déc. 2010) | 3 lines
  
  Fix ResourceWarning in test_normalization
................
  r87442 | alexander.belopolsky | 2010-12-23 03:27:37 +0100 (jeu., 23 déc. 2010) | 1 line
  
  Issue #10254: Fixed a crash and a regression introduced by the implementation of PRI 29.
................
  r87443 | alexander.belopolsky | 2010-12-23 03:58:25 +0100 (jeu., 23 déc. 2010) | 1 line
  
  Issue #10587: Document the meaning of str methods.
................
  r87445 | eric.araujo | 2010-12-23 19:41:33 +0100 (jeu., 23 déc. 2010) | 2 lines
  
  Fix small inaccuracy: there is no index function
................
  r87446 | eric.araujo | 2010-12-23 19:44:31 +0100 (jeu., 23 déc. 2010) | 2 lines
  
  Nits: use a real boolean, make one docstring more similar to the other ones
................
  r87447 | eric.araujo | 2010-12-23 20:13:05 +0100 (jeu., 23 déc. 2010) | 2 lines
  
  Fix typo in superclass method name
................
  r87448 | r.david.murray | 2010-12-23 20:44:49 +0100 (jeu., 23 déc. 2010) | 4 lines
  
  #4496: remove misleading comment and note that self.handlers is obsolete.
  
  self.handlers is still used in one urllib2 test, but not by the code iteslf.
................
  r87451 | r.david.murray | 2010-12-23 21:35:46 +0100 (jeu., 23 déc. 2010) | 4 lines
  
  #1155362: allow hh:mm:ss-uuuu like we allow hh:mm:ss+uuuu in parsedate_tz
  
  Original patch by Thomas Herve.
................
  r87454 | raymond.hettinger | 2010-12-23 22:54:02 +0100 (jeu., 23 déc. 2010) | 4 lines
  
  Fix buglet.  If the input was an iterator, the fallback would occur after
  part of the iterator had been consumed.   Also, fix argument names which
  did not match the docs and were a bit misleading.
................
  r87455 | benjamin.peterson | 2010-12-23 23:17:42 +0100 (jeu., 23 déc. 2010) | 1 line
  
  fix docstring
................
  r87458 | benjamin.peterson | 2010-12-23 23:49:38 +0100 (jeu., 23 déc. 2010) | 1 line
  
  use native tenary condition
................
  r87459 | benjamin.peterson | 2010-12-23 23:53:42 +0100 (jeu., 23 déc. 2010) | 1 line
  
  kill some function imports
................
  r87460 | terry.reedy | 2010-12-24 00:10:28 +0100 (ven., 24 déc. 2010) | 3 lines
  
  Issue 10730: mimetypes module - add .svgz to mimetypes.suffix_map and .svg to types_map.
  Addition OKed by GB on IRC (R. David Murray). No backport.
................
  r87461 | eric.araujo | 2010-12-24 00:18:41 +0100 (ven., 24 déc. 2010) | 2 lines
  
  Fix syntax typo
................
  r87462 | benjamin.peterson | 2010-12-24 00:45:39 +0100 (ven., 24 déc. 2010) | 1 line
  
  update comment
................
  r87463 | alexander.belopolsky | 2010-12-24 01:24:11 +0100 (ven., 24 déc. 2010) | 1 line
  
  Issue #9063: Corrected the tzinfo example.
................
  r87466 | raymond.hettinger | 2010-12-24 01:48:47 +0100 (ven., 24 déc. 2010) | 1 line
  
  Add test for r87454.
................
  r87467 | raymond.hettinger | 2010-12-24 01:52:54 +0100 (ven., 24 déc. 2010) | 1 line
  
  Fix docs and comment for r87454.
................
  r87468 | raymond.hettinger | 2010-12-24 01:58:34 +0100 (ven., 24 déc. 2010) | 2 lines
  
  Fix docstring.
................
  r87469 | senthil.kumaran | 2010-12-24 05:03:59 +0100 (ven., 24 déc. 2010) | 4 lines
  
  Fix some mistakes- Issue3243 (r87399)  Correcting the operator precendence
  problem with Content-Length header and uncommenting the test.
................
  r87470 | alexander.belopolsky | 2010-12-24 05:22:40 +0100 (ven., 24 déc. 2010) | 1 line
  
  Added an XXX note to describe timedelta/timedelta feature.
................
  r87471 | raymond.hettinger | 2010-12-24 11:02:22 +0100 (ven., 24 déc. 2010) | 20 lines
  
  Improve diff for assertCountEqual() to actually show the differing counts.
  
  New output looks like this: 
  
  Traceback (most recent call last):
    File "test.py", line 5, in test_ce
      self.assertCountEqual('abracadabra xx', 'simsalabim xx')
  AssertionError: Element counts were not equal:
  Expected 5, got 2:  'a'
  Expected 2, got 1:  'b'
  Expected 0, got 2:  'i'
  Expected 0, got 2:  'm'
  Expected 0, got 1:  'l'
  Expected 0, got 2:  's'
  Expected 1, got 0:  'c'
  Expected 1, got 0:  'd'
  Expected 2, got 0:  'r'
................
  r87472 | raymond.hettinger | 2010-12-24 11:04:00 +0100 (ven., 24 déc. 2010) | 1 line
  
  Add news entry for 87471.
................
  r87473 | raymond.hettinger | 2010-12-24 11:30:06 +0100 (ven., 24 déc. 2010) | 1 line
  
  Add direct tests for the util functions.
................
  r87474 | raymond.hettinger | 2010-12-24 12:20:30 +0100 (ven., 24 déc. 2010) | 1 line
  
  Put diff output in useful order (when the elements were first seen).
................
  r87475 | raymond.hettinger | 2010-12-24 12:24:00 +0100 (ven., 24 déc. 2010) | 1 line
  
  Keep helper functions private.
................
  r87476 | vinay.sajip | 2010-12-24 13:03:48 +0100 (ven., 24 déc. 2010) | 1 line
  
  Logging documentation updates.
................
  r87477 | raymond.hettinger | 2010-12-24 22:51:48 +0100 (ven., 24 déc. 2010) | 1 line
  
  Adopt symmetric names for arguments (actual/expected --> first/second).
................
  r87478 | terry.reedy | 2010-12-24 22:59:03 +0100 (ven., 24 déc. 2010) | 2 lines
  
  Match current tracker name, though I do not know if still active.
................
  r87479 | r.david.murray | 2010-12-24 23:36:49 +0100 (ven., 24 déc. 2010) | 8 lines
  
  #1693546: don't add quotes around RFC 2231 encoded values.
  
  The RFC is bit hard to understand on this point, but the examples
  clearly show that parameter values that are encoded according
  to its charset/language rules don't have surrounding quotes, and
  the ABNF does not allow for quotes.  So when we produce such
  encoded values, we no longer add quotes.
................
  r87482 | brian.quinlan | 2010-12-25 00:10:41 +0100 (sam., 25 déc. 2010) | 1 line
  
  Better reporting of test failures on Windows.
................
  r87483 | brian.quinlan | 2010-12-25 01:18:27 +0100 (sam., 25 déc. 2010) | 1 line
  
  Assign closed handles to None to make errors more obvious if they are used.
................
  r87485 | victor.stinner | 2010-12-25 23:40:32 +0100 (sam., 25 déc. 2010) | 5 lines
  
  Issue #10763: subprocess.communicate() closes stdout and stderr if both are
  pipes (bug specific to Windows).
  
  Improve also the unit test: write a portable unit test.
................
  r87486 | eric.araujo | 2010-12-26 03:18:49 +0100 (dim., 26 déc. 2010) | 2 lines
  
  Fix typo spotted by Rodrigo Bernardo Pimentel (#9891)
................
  r87489 | eric.araujo | 2010-12-26 03:38:05 +0100 (dim., 26 déc. 2010) | 2 lines
  
  Remove unexistent parameter (#3216)
................
  r87492 | terry.reedy | 2010-12-26 04:48:35 +0100 (dim., 26 déc. 2010) | 1 line
  
  revert 87478
................
  r87493 | eric.araujo | 2010-12-26 18:53:27 +0100 (dim., 26 déc. 2010) | 2 lines
  
  Fix typo (#10770)
................
  r87496 | vinay.sajip | 2010-12-26 19:47:51 +0100 (dim., 26 déc. 2010) | 1 line
  
  Improved logging cookbook for logging with multiprocessing.
................
  r87497 | r.david.murray | 2010-12-26 20:54:29 +0100 (dim., 26 déc. 2010) | 10 lines
  
  #5258/#10642: print fn, line, traceback and continue when .pth file is broken
  
  If a .pth file contained an error, it could cause a traceback in site.py,
  terminating its processing.  In 2.7 and 3.2, the interpreter will then not
  start.  Previously, a message would print saying to use -v to get the
  traceback.  In either case, the traceback generated for a failed .pth file did
  not include the .pth filename, making it difficult to debug the problem.  Now
  site.py reports not only the .pth filename but also the line number causing the
  error, and just skips the remainder of the file.
................
  r87498 | vinay.sajip | 2010-12-26 22:22:33 +0100 (dim., 26 déc. 2010) | 1 line
  
  Added logging documentation cross-references.
................
  r87501 | r.david.murray | 2010-12-27 01:03:13 +0100 (lun., 27 déc. 2010) | 2 lines
  
  Escape file path before searching for it in output via regex
................
  r87504 | victor.stinner | 2010-12-27 02:49:26 +0100 (lun., 27 déc. 2010) | 1 line
  
  Issue #9738: Document encodings of error and warning functions
................
  r87505 | victor.stinner | 2010-12-27 02:49:29 +0100 (lun., 27 déc. 2010) | 1 line
  
  Issue #9738: document encodings of unicode functions
................
  r87506 | victor.stinner | 2010-12-27 02:49:31 +0100 (lun., 27 déc. 2010) | 1 line
  
  Issue #9738: Document encodings of AST, compiler, parser and PyRun functions
................
  r87507 | victor.stinner | 2010-12-27 03:39:20 +0100 (lun., 27 déc. 2010) | 1 line
  
  Issue #9738: Ooops, fix typos in my previous commit (r87506)
................
  r87508 | r.david.murray | 2010-12-27 05:31:48 +0100 (lun., 27 déc. 2010) | 5 lines
  
  Skip test that does not raise an error on Windows.
  
  I'm assuming that the putative path from the malformed
  pth file is simply not found and therefore ignored.
................
  r87512 | vinay.sajip | 2010-12-27 12:18:52 +0100 (lun., 27 déc. 2010) | 1 line
  
  Issue #10774: test_logging now removes temp files created during tests.
................
  r87513 | vinay.sajip | 2010-12-27 15:31:52 +0100 (lun., 27 déc. 2010) | 1 line
  
  Issue #10626: test_logging now preserves logger disabled states.
................
  r87514 | vinay.sajip | 2010-12-27 19:34:25 +0100 (lun., 27 déc. 2010) | 1 line
  
  Issue #10626: test_logging now preserves logger disabled states.
................
  r87516 | r.david.murray | 2010-12-27 21:09:32 +0100 (lun., 27 déc. 2010) | 5 lines
  
  #7056: runtest and runtest_inner don't use testdir, so drop it from their sigs
  
  I've only tested regular runs and -j runs.  If I've broken anything
  else I'm sure I'll hear about it sooner or later.
................
  r87517 | victor.stinner | 2010-12-27 21:10:36 +0100 (lun., 27 déc. 2010) | 3 lines
  
  Issue #10779: PyErr_WarnExplicit() decodes the filename from the filesystem
  encoding instead of UTF-8.
................
  r87518 | victor.stinner | 2010-12-27 21:12:13 +0100 (lun., 27 déc. 2010) | 3 lines
  
  Issue #10778: decoding_fgets() decodes the filename from the filesystem
  encoding instead of UTF-8.
................
  r87519 | victor.stinner | 2010-12-28 01:28:21 +0100 (mar., 28 déc. 2010) | 3 lines
  
  Issue #10780: PyErr_SetFromWindowsErrWithFilename() and
  PyErr_SetExcFromWindowsErrWithFilename() decode the filename from the
  filesystem encoding instead of UTF-8.
................
  r87520 | victor.stinner | 2010-12-28 01:59:02 +0100 (mar., 28 déc. 2010) | 3 lines
  
  Issue #8966: Remove the documentation of ctypes.set_conversion_mode()
  
  Function removed by r83195.
................
  r87521 | victor.stinner | 2010-12-28 01:59:03 +0100 (mar., 28 déc. 2010) | 3 lines
  
  Issue #10780: Remove commas at the end of the argument list
  
  Forbidden in C, stupid language!
................
  r87522 | georg.brandl | 2010-12-28 10:16:12 +0100 (mar., 28 déc. 2010) | 1 line
  
  Replace sys.maxint mention by sys.maxsize.
................
  r87523 | georg.brandl | 2010-12-28 10:18:24 +0100 (mar., 28 déc. 2010) | 1 line
  
  Remove confusing paragraph -- this is relevant only to advanced users anyway and does not belong into the tutorial.
................
  r87524 | georg.brandl | 2010-12-28 10:29:19 +0100 (mar., 28 déc. 2010) | 1 line
  
  Fix advice: call PyType_Ready to fill in ob_type of custom types.
................
  r87525 | georg.brandl | 2010-12-28 10:51:43 +0100 (mar., 28 déc. 2010) | 1 line
  
  #10679: install idle, pydoc, 2to3 scripts with X.Y suffix for make altinstall; create symlinks for make install.
................
  r87526 | georg.brandl | 2010-12-28 11:38:33 +0100 (mar., 28 déc. 2010) | 1 line
  
  #10777: fix iteration over dict keys while mutating the dict.
................
  r87527 | georg.brandl | 2010-12-28 11:56:20 +0100 (mar., 28 déc. 2010) | 1 line
  
  #10768: fix ScrolledText widget construction, and make the example work from the interactive shell.
................
  r87528 | georg.brandl | 2010-12-28 12:02:12 +0100 (mar., 28 déc. 2010) | 1 line
  
  Add news entry and clarify another.
................
  r87529 | victor.stinner | 2010-12-28 12:02:46 +0100 (mar., 28 déc. 2010) | 2 lines
  
  Issue #9738: Fix typo, ASCII-encoding string => ASCII-encoded string
................
  r87530 | georg.brandl | 2010-12-28 12:06:07 +0100 (mar., 28 déc. 2010) | 1 line
  
  #10767: update README in crashers; not all may have a bug entry and/or be fixed.
................
  r87531 | georg.brandl | 2010-12-28 12:08:17 +0100 (mar., 28 déc. 2010) | 1 line
  
  #10742: document readonly attribute of memoryviews.
................
  r87532 | georg.brandl | 2010-12-28 12:15:49 +0100 (mar., 28 déc. 2010) | 1 line
  
  #10781: clarify that *encoding* is not a parameter for Node objects in general.
................
  r87533 | georg.brandl | 2010-12-28 12:38:12 +0100 (mar., 28 déc. 2010) | 1 line
  
  Remove history; adapt a bit more to reST, since this will once be part of the dev guide.
................
  r87534 | georg.brandl | 2010-12-28 12:48:53 +0100 (mar., 28 déc. 2010) | 1 line
  
  Rewrap.
................
  r87535 | georg.brandl | 2010-12-28 12:49:41 +0100 (mar., 28 déc. 2010) | 1 line
  
  #10739: document that on Windows, socket.makefile() does not make a file that has a true file descriptor usable where such a thing is expected.
................
  r87536 | georg.brandl | 2010-12-28 12:53:25 +0100 (mar., 28 déc. 2010) | 1 line
  
  #10609: fix non-working dbm example.
................
  r87537 | victor.stinner | 2010-12-28 14:26:42 +0100 (mar., 28 déc. 2010) | 6 lines
  
  Issue #10783: struct.pack() doesn't encode implicitly unicode to UTF-8
  
   * Replace "bytes" by "bytes object" in struct error messages
   * Document the API change in What's new in Python 3.2
   * Fix test_wave
   * Remove also ugly implicit conversions in test_struct
................
  r87538 | victor.stinner | 2010-12-28 14:33:43 +0100 (mar., 28 déc. 2010) | 1 line
  
  Issue #10783: Fix test_sys, pack('c', ' ') => pack('c', b' ')
................
  r87539 | brian.curtin | 2010-12-28 15:31:47 +0100 (mar., 28 déc. 2010) | 3 lines
  
  Fix #9333. The symlink function is always available now, raising OSError
  when the user doesn't hold the symbolic link privilege rather than hiding it.
................
  r87542 | senthil.kumaran | 2010-12-28 16:55:16 +0100 (mar., 28 déc. 2010) | 3 lines
  
  Fix Issue10759 - html.parser.unescape() fails on HTML entities with incorrect syntax
................
  r87547 | brian.curtin | 2010-12-28 18:08:22 +0100 (mar., 28 déc. 2010) | 3 lines
  
  Minor doc update for #9333. Took out the phrasing about os.symlink not
  existing and mentioned the OSError possibility.
................
  r87548 | brian.curtin | 2010-12-28 18:12:43 +0100 (mar., 28 déc. 2010) | 3 lines
  
  This file was obsolted by a number of adjustments to the os.symlink tests
  on Windows, and is no longer needed by any tests or Lib/test/support.py
................
  r87549 | georg.brandl | 2010-12-28 19:30:18 +0100 (mar., 28 déc. 2010) | 1 line
  
  Add sys.flags.quiet attribute for the new -q option, as noted missing by Eric in #1772833.
................
  r87550 | r.david.murray | 2010-12-28 19:54:13 +0100 (mar., 28 déc. 2010) | 8 lines
  
  #9824: encode , and ; in cookie values so that browsers don't split on them
  
  There is a small chance of backward incompatibility here, but only for
  non-SimpleCookie applications reading SimpleCookie generated cookies.  Even
  then, any such ap is likely to be handling escaped values already, and it would
  take a fairly perverse implementation of unescaping to fail to unescape these
  newly escaped chars, so the risk seems minimal.
................
  r87553 | terry.reedy | 2010-12-28 20:30:19 +0100 (mar., 28 déc. 2010) | 2 lines
  
  Issue 10738: Fix webbrowser.Opera.raise_opts value.
................
  r87556 | brian.quinlan | 2010-12-28 22:14:34 +0100 (mar., 28 déc. 2010) | 1 line
  
  Does not install a logging handler. Fixes issue 10626.
................
  r87557 | victor.stinner | 2010-12-29 00:05:20 +0100 (mer., 29 déc. 2010) | 1 line
  
  Compile pgenmain.c and printgrammar.c with PGEN defined
................
  r87558 | victor.stinner | 2010-12-29 00:14:17 +0100 (mer., 29 déc. 2010) | 1 line
  
  Don't ignore pgen error (on "make Parser/pgen.stamp")
................
  r87559 | victor.stinner | 2010-12-29 00:35:10 +0100 (mer., 29 déc. 2010) | 1 line
  
  Issue #10783: rephrase the changelog (NEWS, What's new)
................
  r87560 | victor.stinner | 2010-12-29 00:39:51 +0100 (mer., 29 déc. 2010) | 1 line
  
  Rephrase PyUnicode_CompareWithASCIIString() documentation
................
  r87561 | brian.curtin | 2010-12-29 03:04:28 +0100 (mer., 29 déc. 2010) | 2 lines
  
  Fix #9333 on Windows XP, where os.symlink is not a possibility.
................
  r87562 | brian.curtin | 2010-12-29 03:41:07 +0100 (mer., 29 déc. 2010) | 2 lines
  
  Close stdout, clear ResourceWarning
................
  r87563 | victor.stinner | 2010-12-29 03:44:42 +0100 (mer., 29 déc. 2010) | 1 line
  
  Issue #10783: rephrase the changelog (new try)
................
  r87564 | senthil.kumaran | 2010-12-29 07:25:42 +0100 (mer., 29 déc. 2010) | 3 lines
  
  Fix Issue 10753 - Don't quote ;=, in the PATH_INFO envvar.
................
  r87567 | r.david.murray | 2010-12-29 17:57:24 +0100 (mer., 29 déc. 2010) | 2 lines
  
  Fix a comment typo and update another comment to match Python3 reality                                                                                                                                                                                                                 
................
  r87569 | terry.reedy | 2010-12-29 20:02:07 +0100 (mer., 29 déc. 2010) | 2 lines
  
  Minor clarification
................
  r87571 | r.david.murray | 2010-12-29 20:06:48 +0100 (mer., 29 déc. 2010) | 2 lines
  
  Fix same typo in docs.
................
  r87573 | senthil.kumaran | 2010-12-30 08:07:58 +0100 (jeu., 30 déc. 2010) | 3 lines
  
  Fix Issue10793 - hashlib documentation issue on return type of digest
................
  r87575 | martin.v.loewis | 2010-12-30 09:36:37 +0100 (jeu., 30 déc. 2010) | 2 lines
  
  Issue #10542: Document that identifiers use XID_Start XID_Continue*.
................
  r87577 | martin.v.loewis | 2010-12-30 15:55:47 +0100 (jeu., 30 déc. 2010) | 2 lines
  
  Build and install libpython3.so.
................
  r87579 | georg.brandl | 2010-12-30 18:22:33 +0100 (jeu., 30 déc. 2010) | 1 line
  
  Remove some of the old demos.  (Put a few somewhere else.)
................
  r87580 | georg.brandl | 2010-12-30 18:32:22 +0100 (jeu., 30 déc. 2010) | 1 line
  
  Clean up tools: remove "world" and "framer", move single SSL script to scripts/.
................
  r87581 | georg.brandl | 2010-12-30 18:36:17 +0100 (jeu., 30 déc. 2010) | 1 line
  
  Fix NameErrors.
................
  r87582 | michael.foord | 2010-12-30 20:36:29 +0100 (jeu., 30 déc. 2010) | 1 line
  
  Issue 10786: unittest.TextTestRunner default stream no longer bound at import time
................
  r87583 | georg.brandl | 2010-12-30 22:33:07 +0100 (jeu., 30 déc. 2010) | 1 line
  
  More cleanup: Move some demos into a dedicated Tools/demo dir, move 2to3 demo to Tools, and remove all the other Demo content.
................
  r87584 | georg.brandl | 2010-12-30 22:33:49 +0100 (jeu., 30 déc. 2010) | 1 line
  
  Remove the actual Demo dir.
................
  r87585 | georg.brandl | 2010-12-30 23:11:50 +0100 (jeu., 30 déc. 2010) | 1 line
  
  Harmonize docstrings.  Move redemo from Tools/scripts to Tools/demo.  Add a README file to Tools/demo.
................
  r87586 | georg.brandl | 2010-12-30 23:12:40 +0100 (jeu., 30 déc. 2010) | 1 line
  
  Remove mentions of the Demo directory.
................
  r87587 | georg.brandl | 2010-12-30 23:31:10 +0100 (jeu., 30 déc. 2010) | 1 line
  
  Add the missing __main__.py in the turtledemo package.  It seems to have been lost during some mass rename action (r86095).
................
  r87588 | georg.brandl | 2010-12-30 23:32:49 +0100 (jeu., 30 déc. 2010) | 1 line
  
  Update README, remove empty directory.
................
  r87589 | vinay.sajip | 2010-12-31 00:26:50 +0100 (ven., 31 déc. 2010) | 1 line
  
  Issue #10788: Changed test_logging setUp logic to provide more information.
................
  r87590 | r.david.murray | 2010-12-31 20:21:14 +0100 (ven., 31 déc. 2010) | 4 lines
  
  #9361: add some tests for calendar.leapdays
  
  Patch by John Chandler.
................
  r87593 | georg.brandl | 2011-01-01 00:00:03 +0100 (sam., 01 janv. 2011) | 1 line
  
  Happy New Year!  (CET edition)
................
  r87594 | raymond.hettinger | 2011-01-01 00:16:17 +0100 (sam., 01 janv. 2011) | 1 line
  
  Fix OrderedDict.setdefault() to work for subclasses that define __missing__().
................
  r87595 | raymond.hettinger | 2011-01-01 00:23:06 +0100 (sam., 01 janv. 2011) | 2 lines
  
  Typo.
................
  r87598 | terry.reedy | 2011-01-01 03:25:36 +0100 (sam., 01 janv. 2011) | 2 lines
  
  Issue 6285: catch missing IDLE help file.
................
  r87601 | terry.reedy | 2011-01-01 03:54:11 +0100 (sam., 01 janv. 2011) | 2 lines
  
  Issue 6285: add NEWS entry for 3.2.
................
  r87603 | georg.brandl | 2011-01-01 11:07:30 +0100 (sam., 01 janv. 2011) | 1 line
  
  Fix issue references.
................
  r87604 | georg.brandl | 2011-01-01 11:09:32 +0100 (sam., 01 janv. 2011) | 1 line
  
  #10801: In zipfile, support different encodings for the header and the filenames.  Patch by MvL, test by Eli Bendersky.
................
  r87606 | georg.brandl | 2011-01-01 11:42:31 +0100 (sam., 01 janv. 2011) | 1 line
  
  #10801: do not actually extract, just open() the files in the test zipfile.
................
  r87607 | benjamin.peterson | 2011-01-01 15:28:31 +0100 (sam., 01 janv. 2011) | 1 line
  
  update copyright to 2011
................
  r87610 | gregory.p.smith | 2011-01-01 22:18:46 +0100 (sam., 01 janv. 2011) | 2 lines
  
  post release bump
................
  r87611 | raymond.hettinger | 2011-01-01 23:38:00 +0100 (sam., 01 janv. 2011) | 1 line
  
  Make it easier to extend OrderedDict without breaking it.
................
  r87612 | raymond.hettinger | 2011-01-02 00:51:55 +0100 (dim., 02 janv. 2011) | 1 line
  
  Fix OrderedDic.pop() to work for subclasses that define  __missing__().
................
  r87615 | raymond.hettinger | 2011-01-02 09:03:33 +0100 (dim., 02 janv. 2011) | 4 lines
  
  Fix doctest to not rely on order of dictionary entries.
  Use super() instead of direct references to the dict superclass.
................
  r87627 | georg.brandl | 2011-01-02 15:23:43 +0100 (dim., 02 janv. 2011) | 1 line
  
  #1665333: add more docs for optparse.OptionGroup.
................
  r87628 | antoine.pitrou | 2011-01-02 17:16:09 +0100 (dim., 02 janv. 2011) | 3 lines
  
  Relax test condition a lot
................
  r87638 | georg.brandl | 2011-01-02 20:07:51 +0100 (dim., 02 janv. 2011) | 1 line
  
  Fix code indentation.
................
  r87639 | antoine.pitrou | 2011-01-02 20:34:03 +0100 (dim., 02 janv. 2011) | 4 lines
  
  Issue #10475: Don't hardcode compilers for LDSHARED/LDCXXSHARED on NetBSD
  and DragonFly BSD.  Patch by Nicolas Joly.
................
  r87642 | victor.stinner | 2011-01-02 20:50:36 +0100 (dim., 02 janv. 2011) | 3 lines
  
  Issue #10807: Remove base64, bz2, hex, quopri, rot13, uu and zlib codecs from
  the codec aliases. They are still accessible via codecs.lookup().
................
  r87646 | antoine.pitrou | 2011-01-02 21:45:21 +0100 (dim., 02 janv. 2011) | 3 lines
  
  Fix bad quoting in r87639. Caught by Arfrever.
................
  r87648 | alexander.belopolsky | 2011-01-02 21:48:22 +0100 (dim., 02 janv. 2011) | 1 line
  
  Issue #8013: Fixed time.asctime segfault when OS's asctime fails
................
  r87651 | gregory.p.smith | 2011-01-02 21:52:48 +0100 (dim., 02 janv. 2011) | 3 lines
  
  issue10802: fallback to pipe+fcntl when the pipe2 syscall fails with errno ENOSYS.
................
  r87653 | antoine.pitrou | 2011-01-02 23:06:53 +0100 (dim., 02 janv. 2011) | 3 lines
  
  Clarify behaviour of close() and shutdown() on sockets.
................
  r87654 | antoine.pitrou | 2011-01-02 23:09:27 +0100 (dim., 02 janv. 2011) | 3 lines
  
  Add a shutdown() call in the server example.
................
  r87655 | antoine.pitrou | 2011-01-02 23:12:22 +0100 (dim., 02 janv. 2011) | 3 lines
  
  Some nits.
................
  r87656 | alexander.belopolsky | 2011-01-02 23:16:10 +0100 (dim., 02 janv. 2011) | 1 line
  
  Issue #8013: Fixed test
................
  r87657 | georg.brandl | 2011-01-02 23:33:43 +0100 (dim., 02 janv. 2011) | 5 lines
  
  #8013 follow-up:
  * In asctime and ctime, properly remove the newline if the year has more than four digits
  * Consistent error message for both functions
  * Fix the test comments and add a check for the removed newline
................
  r87665 | martin.v.loewis | 2011-01-03 01:07:01 +0100 (lun., 03 janv. 2011) | 3 lines
  
  Issue #10798: Reject supporting concurrent.futures if the system has
  too few POSIX semaphores.
................
  r87666 | amaury.forgeotdarc | 2011-01-03 01:19:11 +0100 (lun., 03 janv. 2011) | 4 lines
  
  #8278: In the Windows implementation of stat() and utime(),
  use time_t instead of int.  This gives support for dates after 2038,
  at least when compiled with VS2003 or later, where time_t is 64bit.
................
  r87667 | martin.v.loewis | 2011-01-03 01:19:59 +0100 (lun., 03 janv. 2011) | 2 lines
  
  Skip hanging test.
................
  r87671 | raymond.hettinger | 2011-01-03 03:12:02 +0100 (lun., 03 janv. 2011) | 1 line
  
  Make C helper function more closely match the pure python version, and add tests.
................
  r87672 | raymond.hettinger | 2011-01-03 03:44:14 +0100 (lun., 03 janv. 2011) | 1 line
  
  Supply a reduce method for pickling.
................
  r87673 | brian.quinlan | 2011-01-03 03:56:39 +0100 (lun., 03 janv. 2011) | 1 line
  
  Removes the 'Call' class which is used to control execution order and is unreliable on Windows
................
  r87677 | senthil.kumaran | 2011-01-03 10:47:09 +0100 (lun., 03 janv. 2011) | 3 lines
  
  py3k implmentation of RSA algorithm,
................
  r87678 | senthil.kumaran | 2011-01-03 11:11:07 +0100 (lun., 03 janv. 2011) | 3 lines
  
  Reverting the mistaken commit r87677. Checked in py3rsa.py by mistake.
................
  r87679 | michael.foord | 2011-01-03 13:55:11 +0100 (lun., 03 janv. 2011) | 1 line
  
  Issue 10786: unittest documentation update.
................
  r87680 | victor.stinner | 2011-01-03 15:30:39 +0100 (lun., 03 janv. 2011) | 1 line
  
  test_sockserver: close servers when done
................
  r87681 | victor.stinner | 2011-01-03 15:30:41 +0100 (lun., 03 janv. 2011) | 3 lines
  
  test_timeout: move testRecvfromTimeout() to a UDP-specific test case
  
  Fix a ResourceWarning(unclosed socket).
................
  r87682 | victor.stinner | 2011-01-03 15:30:43 +0100 (lun., 03 janv. 2011) | 3 lines
  
  test_tkinter: use a context manager to close directly the pipe
  
  Patch written by Nadeem Vawda
................
  r87683 | victor.stinner | 2011-01-03 15:30:44 +0100 (lun., 03 janv. 2011) | 3 lines
  
  test_xmlrpc: close the transport when done
  
  Fix a ResourceWarning(unclosed socket). Patch written by Nadeem Vawda.
................
  r87684 | victor.stinner | 2011-01-03 15:30:46 +0100 (lun., 03 janv. 2011) | 3 lines
  
  test_socket: use context managers to close directly the socket
  
  Fix ResourceWarning(unclosed socket) warnings. Patch written by Nadeem Vawda.
................
  r87685 | michael.foord | 2011-01-03 16:39:49 +0100 (lun., 03 janv. 2011) | 1 line
  
  Issue 10502: addition of unittestgui to Tools/
................
  r87686 | victor.stinner | 2011-01-03 16:47:59 +0100 (lun., 03 janv. 2011) | 3 lines
  
  Issue #10816: multiprocessing.SocketClient() closes the socket on error
  
  Use a context manager to close immediatly the socket on error.
................
  r87687 | victor.stinner | 2011-01-03 17:12:39 +0100 (lun., 03 janv. 2011) | 1 line
  
  pydoc: close the DocServer when done
................
  r87688 | victor.stinner | 2011-01-03 17:36:00 +0100 (lun., 03 janv. 2011) | 1 line
  
  test_subprocess: close pipes at the end of test_pipe_cloexec_real_tools()
................
  r87689 | michael.foord | 2011-01-03 18:00:11 +0100 (lun., 03 janv. 2011) | 2 lines
  
  Enable unittest.TestCase to be instantiated without providing a method name.
  Changed unittestgui to show number of discovered tests in the status bar.
................
  r87691 | eric.araujo | 2011-01-03 18:51:11 +0100 (lun., 03 janv. 2011) | 2 lines
  
  Fix test_site for systems without unsetenv.  Reported by Zsolt Cserna.
................
  r87695 | antoine.pitrou | 2011-01-03 19:23:55 +0100 (lun., 03 janv. 2011) | 5 lines
  
  Issue #10806, issue #9905: Fix subprocess pipes when some of the standard
  file descriptors (0, 1, 2) are closed in the parent process.  Initial
  patch by Ross Lagerwall.
................
  r87698 | antoine.pitrou | 2011-01-03 19:53:50 +0100 (lun., 03 janv. 2011) | 4 lines
  
  Issue #7716: Under Solaris, don't assume existence of /usr/xpg4/bin/grep in
  the configure script but use $GREP instead.  Patch by Fabian Groffen.
................
  r87703 | michael.foord | 2011-01-03 20:13:02 +0100 (lun., 03 janv. 2011) | 1 line
  
  Update description of Tools/unicode
................
  r87704 | antoine.pitrou | 2011-01-03 21:38:52 +0100 (lun., 03 janv. 2011) | 5 lines
  
  Issue #6293: Have regrtest.py echo back sys.flags.  This is done by default
  in whole runs and enabled selectively using `--header` when running an
  explicit list of tests.  Original patch by Collin Winter.
................
  r87705 | antoine.pitrou | 2011-01-03 21:40:07 +0100 (lun., 03 janv. 2011) | 3 lines
  
  Mention --randseed in option list
................
  r87710 | gregory.p.smith | 2011-01-03 22:06:12 +0100 (lun., 03 janv. 2011) | 4 lines
  
  issue6643 - Two locks held within the threading module on each thread instance
  needed to be reinitialized after fork().  Adds tests to confirm that they are
  and that a potential deadlock and crasher bug are fixed (platform dependant).
................
  r87711 | gregory.p.smith | 2011-01-03 22:09:23 +0100 (lun., 03 janv. 2011) | 2 lines
  
  news for 6643
................
  r87712 | antoine.pitrou | 2011-01-03 22:15:48 +0100 (lun., 03 janv. 2011) | 3 lines
  
  Add a subprocess test of remapping standard file descriptors (issue #1187).
................
  r87713 | antoine.pitrou | 2011-01-03 23:12:43 +0100 (lun., 03 janv. 2011) | 3 lines
  
  Temporary debug output for intermittent failures in test_subprocess
................
  r87714 | antoine.pitrou | 2011-01-03 23:24:52 +0100 (lun., 03 janv. 2011) | 3 lines
  
  Add some more output
................
  r87716 | antoine.pitrou | 2011-01-04 00:42:01 +0100 (mar., 04 janv. 2011) | 3 lines
  
  Un-complicate some code
................
  r87717 | victor.stinner | 2011-01-04 00:56:12 +0100 (mar., 04 janv. 2011) | 1 line
  
  fix test_unittest: ignore DeprecationWarning on assertDictContainsSubset()
................
  r87718 | antoine.pitrou | 2011-01-04 01:00:31 +0100 (mar., 04 janv. 2011) | 4 lines
  
  Issue #10333: Remove ancient GC API, which has been deprecated since
  Python 2.2.
................
  r87719 | victor.stinner | 2011-01-04 01:04:44 +0100 (mar., 04 janv. 2011) | 1 line
  
  test_array: fix the DeprecationWarning('object.__init__() takes no parameters')
................
  r87720 | victor.stinner | 2011-01-04 01:04:46 +0100 (mar., 04 janv. 2011) | 1 line
  
  test_httplib: fix a DeprecationWarning, assertEquals=>assertEqual
................
  r87721 | antoine.pitrou | 2011-01-04 01:24:03 +0100 (mar., 04 janv. 2011) | 3 lines
  
  Issue #10267: Fix refleak in test_ttk_guionly.  Patch by Hirokazu Yamamoto.
................
  r87722 | victor.stinner | 2011-01-04 01:29:35 +0100 (mar., 04 janv. 2011) | 2 lines
  
  Issue #9015, #9611: FileIO.readinto(), FileIO.write() and os.write() clamp the
  length to 2^31-1 on Windows.
................
  r87728 | victor.stinner | 2011-01-04 03:07:34 +0100 (mar., 04 janv. 2011) | 3 lines
  
  Issue #8651: PyArg_Parse*() functions raise an OverflowError if the file
  doesn't have PY_SSIZE_T_CLEAN define and the size doesn't fit in an int
  (length bigger than 2^31-1).
................
  r87729 | victor.stinner | 2011-01-04 03:07:36 +0100 (mar., 04 janv. 2011) | 3 lines
  
  Issue #8650: zlib.compress() and zlib.decompress() raise an OverflowError if
  the input buffer length doesn't fit into an unsigned int (length bigger than
  2^32-1 bytes).
................
  r87730 | victor.stinner | 2011-01-04 12:00:45 +0100 (mar., 04 janv. 2011) | 2 lines
  
  Issue #10819: SocketIO.name property returns -1 when its closed, instead of
  raising a ValueError, to fix repr().
................
  r87731 | victor.stinner | 2011-01-04 12:16:48 +0100 (mar., 04 janv. 2011) | 3 lines
  
  Issue #8992: Simplify addcleanup() API
  
  Don't need to handle unknown destructor anymore.
................
  r87732 | victor.stinner | 2011-01-04 12:16:49 +0100 (mar., 04 janv. 2011) | 3 lines
  
  Issue #8992: convertsimple() doesn't need to fill msgbuf if an error occurred
  
  Return msgbug on error is enough.
................
  r87733 | victor.stinner | 2011-01-04 13:59:15 +0100 (mar., 04 janv. 2011) | 1 line
  
  Issue #9566: use Py_ssize_t instead of int
................
  r87734 | victor.stinner | 2011-01-04 14:15:39 +0100 (mar., 04 janv. 2011) | 1 line
  
  Issue #9015, #9611: stdprinter.write() clamps the length to 2^31-1 on Windows
................
  r87735 | vinay.sajip | 2011-01-04 14:58:49 +0100 (mar., 04 janv. 2011) | 1 line
  
  logging HOWTO: fixed markup for numbered handler list.
................
  r87736 | alexander.belopolsky | 2011-01-04 17:34:30 +0100 (mar., 04 janv. 2011) | 6 lines
  
  Issue #8013: time.asctime and time.ctime no longer call system asctime
  and ctime functions.  The year range for time.asctime is now 1900
  through maxint.  The range for time.ctime is the same as for
  time.localtime.  The string produced by these functions is longer than
  24 characters when year is greater than 9999.
................
  r87737 | alexander.belopolsky | 2011-01-04 18:08:04 +0100 (mar., 04 janv. 2011) | 1 line
  
  Issue #8013: Fix time.ctime test failure on 32-bit platforms.
................
  r87738 | alexander.belopolsky | 2011-01-04 18:15:52 +0100 (mar., 04 janv. 2011) | 1 line
  
  Whitespace cleanup
................
  r87739 | georg.brandl | 2011-01-04 18:27:13 +0100 (mar., 04 janv. 2011) | 1 line
  
  Fix exception catching.
................
  r87740 | gregory.p.smith | 2011-01-04 19:33:38 +0100 (mar., 04 janv. 2011) | 6 lines
  
  Fix the new bug introduced in the r87710 fix for issue 6643.  DummyThread
  deletes its _block attribute, deal with that.  This prevents an uncaught
  exception in a thread during test_thread.
  
  This refactors a bit to better match what I did in the r87727 backport to 2.7.
................
  r87744 | antoine.pitrou | 2011-01-04 20:07:07 +0100 (mar., 04 janv. 2011) | 4 lines
  
  In subprocess, wrap pipe fds before launching the child. Hopefully this
  will fix intermittent failures on some buildbots (issue #8458).
................
  r87746 | victor.stinner | 2011-01-04 22:58:10 +0100 (mar., 04 janv. 2011) | 1 line
  
  Issue #9566: explain why (int)len cannot underflow
................
  r87747 | victor.stinner | 2011-01-04 23:00:04 +0100 (mar., 04 janv. 2011) | 1 line
  
  Issue #9566: PyUnicode_FromFormatV() doesn't support %zi, use %zd instead
................
  r87748 | antoine.pitrou | 2011-01-04 23:54:30 +0100 (mar., 04 janv. 2011) | 3 lines
  
  Fix test_time under Windows
................
  r87749 | victor.stinner | 2011-01-05 01:19:28 +0100 (mer., 05 janv. 2011) | 4 lines
  
  test_unicode: use ctypes to test PyUnicode_FromFormat()
  
  Instead of _testcapi.format_unicode() because it has a limited API: it requires
  exactly one argument of type unicode.
................
  r87750 | r.david.murray | 2011-01-05 02:39:32 +0100 (mer., 05 janv. 2011) | 5 lines
  
  #10790: make append work when output codec is different from input codec
  
  There's still a bug here (the encode call shouldn't use the 'errors'
  paramter), but I'll fix that later.
................
  r87753 | victor.stinner | 2011-01-05 04:33:26 +0100 (mer., 05 janv. 2011) | 4 lines
  
  Remove arbitrary string length limits
  
  PyUnicode_FromFormat() and PyErr_Format() allocates a buffer of the needed
  size, it is no more a fixed-buffer of 500 bytes.
................
  r87754 | victor.stinner | 2011-01-05 04:33:28 +0100 (mer., 05 janv. 2011) | 1 line
  
  test_bytes: test PyBytes_FromFormat() using ctypes
................
  r87755 | victor.stinner | 2011-01-05 04:54:25 +0100 (mer., 05 janv. 2011) | 1 line
  
  Issue #10756: atexit normalizes the exception before displaying it.
................
  r87756 | victor.stinner | 2011-01-05 04:54:26 +0100 (mer., 05 janv. 2011) | 3 lines
  
  regrtest: close the new stdout and restore the original stdout at exit
  
  Fix a ResourceWarning(unclosed file).
................
  r87757 | victor.stinner | 2011-01-05 04:54:28 +0100 (mer., 05 janv. 2011) | 4 lines
  
  test_threading: use Popen.communicate() instead of .wait()
  
  Popen.communicate() avoids deadlocks and close the pipes when done. This commit
  fixes a ResourceWarning(unclosed pipe).
................
  r87758 | victor.stinner | 2011-01-05 04:56:22 +0100 (mer., 05 janv. 2011) | 1 line
  
  Issue #10756: add the author, Andreas Stührk
................
  r87759 | victor.stinner | 2011-01-05 04:58:54 +0100 (mer., 05 janv. 2011) | 1 line
  
  test_time: assertEquals => assertEqual
................
  r87760 | georg.brandl | 2011-01-05 11:59:48 +0100 (mer., 05 janv. 2011) | 1 line
  
  Fix duplicate end tag.
................
  r87761 | georg.brandl | 2011-01-05 12:00:25 +0100 (mer., 05 janv. 2011) | 1 line
  
  #10130: Prepare for building epub-format docs.
................
  r87762 | antoine.pitrou | 2011-01-05 19:37:22 +0100 (mer., 05 janv. 2011) | 3 lines
  
  Issue #5485: Add doc for expat.xmlparser.SetParamEntityParsing.
................
  r87765 | antoine.pitrou | 2011-01-05 19:44:14 +0100 (mer., 05 janv. 2011) | 4 lines
  
  Issue #5485: Add tests for the UseForeignDTD method of expat parser objects.
  Patch by Jean-Paul Calderone and Sandro Tosi.
................
  r87766 | raymond.hettinger | 2011-01-05 21:08:25 +0100 (mer., 05 janv. 2011) | 1 line
  
  Fix count of flag fields.  Being one short caused the 'quiet' option not to print.
................
  r87767 | raymond.hettinger | 2011-01-05 21:24:08 +0100 (mer., 05 janv. 2011) | 1 line
  
  Update tests and whatsnew for the 'quiet' flag
................
  r87768 | antoine.pitrou | 2011-01-05 22:03:42 +0100 (mer., 05 janv. 2011) | 4 lines
  
  Issue #7995: When calling accept() on a socket with a timeout, the returned
  socket is now always non-blocking, regardless of the operating system.
................
  r87769 | antoine.pitrou | 2011-01-05 22:17:36 +0100 (mer., 05 janv. 2011) | 3 lines
  
  Overhaul the documentation about socket timeouts.
................
  r87771 | georg.brandl | 2011-01-05 22:47:47 +0100 (mer., 05 janv. 2011) | 1 line
  
  On Py3k, -tt and -3 are no-op and unsupported respectively.
................
  r87772 | raymond.hettinger | 2011-01-05 23:27:49 +0100 (mer., 05 janv. 2011) | 1 line
  
  RC1 updates to whatsnew
................
  r87773 | raymond.hettinger | 2011-01-05 23:41:23 +0100 (mer., 05 janv. 2011) | 2 lines
  
  Remove mention of codes pending further discussion on transform()/untransform().
................
  r87774 | antoine.pitrou | 2011-01-05 23:43:26 +0100 (mer., 05 janv. 2011) | 3 lines
  
  Fix mistake in NEWS
................
  r87775 | raymond.hettinger | 2011-01-06 00:00:00 +0100 (jeu., 06 janv. 2011) | 2 lines
  
  Add more porting notes.
................
  r87776 | alexander.belopolsky | 2011-01-06 00:00:47 +0100 (jeu., 06 janv. 2011) | 5 lines
  
  - time.accept2dyear = True is now equivalent to time.accept2dyear = 1
  - removed unnecessary struct_time to tuple conversion
  - added more unit tests
  (See issue #10827 for discussion.)
................
  r87777 | victor.stinner | 2011-01-06 00:01:37 +0100 (jeu., 06 janv. 2011) | 4 lines
  
  imaplib: IMAP4 constructor closes the socket on error
  
  Fix a ResourceWarning(unclosed socket) if an exception is raised in the
  constructor after the creation of the socket. Patch written by Nadeem Vawda.
................
  r87778 | victor.stinner | 2011-01-06 00:01:38 +0100 (jeu., 06 janv. 2011) | 3 lines
  
  test_imaplib: reap_server() closes the server when done
  
  Fix a ResourceWarning(unclosed socket). Patch written by Nadeem Vawda.
................
  r87779 | victor.stinner | 2011-01-06 00:47:00 +0100 (jeu., 06 janv. 2011) | 3 lines
  
  test_atexit: fix code saving/restoring stdout and stderr
  
  That's why I prefer a single instruction per line :-)
................
  r87780 | victor.stinner | 2011-01-06 01:49:38 +0100 (jeu., 06 janv. 2011) | 3 lines
  
  Issue #10492: bdb.Bdb.run() only traces the execution of the code
  
  And not the compilation (if the input is a string).
................
  r87781 | raymond.hettinger | 2011-01-06 03:01:26 +0100 (jeu., 06 janv. 2011) | 2 lines
  
  Add PEP 3333 to whatsnew.
................
  r87782 | raymond.hettinger | 2011-01-06 03:08:30 +0100 (jeu., 06 janv. 2011) | 1 line
  
  Nits
................
  r87783 | raymond.hettinger | 2011-01-06 06:34:17 +0100 (jeu., 06 janv. 2011) | 1 line
  
  Issue 10825: Minor updates to the test suite.
................
  r87784 | antoine.pitrou | 2011-01-06 08:16:31 +0100 (jeu., 06 janv. 2011) | 3 lines
  
  Issue #10840: make it explicit that "s*" and friends provide contiguous memory.
................
  r87786 | antoine.pitrou | 2011-01-06 10:05:22 +0100 (jeu., 06 janv. 2011) | 4 lines
  
  Issue #1677694: Refactor and improve test_timeout.  Original patch by
  Björn Lindqvist.
................
  r87787 | georg.brandl | 2011-01-06 10:15:45 +0100 (jeu., 06 janv. 2011) | 1 line
  
  Remove doc for nonexisting parameter.
................
  r87788 | georg.brandl | 2011-01-06 10:23:19 +0100 (jeu., 06 janv. 2011) | 1 line
  
  itertools, operator and functools are not really "numeric" modules; move them into their own "functional" chapter.
................
  r87789 | georg.brandl | 2011-01-06 10:23:56 +0100 (jeu., 06 janv. 2011) | 1 line
  
  Fix various issues (mostly Python 2 relics) found by Jacques Ducasse.
................
  r87790 | georg.brandl | 2011-01-06 10:25:27 +0100 (jeu., 06 janv. 2011) | 1 line
  
  Add acks where acks are due.
................
  r87791 | georg.brandl | 2011-01-06 11:05:26 +0100 (jeu., 06 janv. 2011) | 1 line
  
  #10844: update copyright years in Mac plists.
................
  r87792 | antoine.pitrou | 2011-01-06 17:31:28 +0100 (jeu., 06 janv. 2011) | 3 lines
  
  Elaborate about the GIL.
................
  r87795 | alexander.belopolsky | 2011-01-06 17:45:25 +0100 (jeu., 06 janv. 2011) | 1 line
  
  Use PyOS_snprintf for better portability.
................
  r87796 | david.malcolm | 2011-01-06 18:01:36 +0100 (jeu., 06 janv. 2011) | 6 lines
  
  Issue #10655: Fix the build on PowerPC on Linux with GCC when building with
  timestamp profiling (--with-tsc): the preprocessor test for the PowerPC
  support now looks for "__powerpc__" as well as "__ppc__": the latter seems to
  only be present on OS X; the former is the correct one for Linux with GCC.
................
  r87797 | antoine.pitrou | 2011-01-06 18:17:04 +0100 (jeu., 06 janv. 2011) | 4 lines
  
  Issue #3839: wsgiref should not override a Content-Length header set by
  the application.  Initial patch by Clovis Fabricio.
................
  r87802 | antoine.pitrou | 2011-01-06 19:25:55 +0100 (jeu., 06 janv. 2011) | 6 lines
  
  Issue #7858: Raise an error properly when os.utime() fails under Windows
  on an existing file.
  
  (this does not seem to be easily testable)
................
  r87805 | martin.v.loewis | 2011-01-06 20:15:47 +0100 (jeu., 06 janv. 2011) | 2 lines
  
  Remove buffer API from stable ABI for now, see #10181.
................
  r87806 | martin.v.loewis | 2011-01-06 20:26:21 +0100 (jeu., 06 janv. 2011) | 2 lines
  
  Support comment lines and missing indices in typeslots.h.
................
  r87807 | georg.brandl | 2011-01-06 20:28:18 +0100 (jeu., 06 janv. 2011) | 1 line
  
  #10846: fix typo.
................
  r87808 | martin.v.loewis | 2011-01-06 20:28:31 +0100 (jeu., 06 janv. 2011) | 3 lines
  
  Drop bf_getbuffer/bf_releasebuffer from stable ABI,
  see #10181.
................
  r87810 | raymond.hettinger | 2011-01-06 21:55:29 +0100 (jeu., 06 janv. 2011) | 2 lines
  
  Typo.
................
  r87811 | alexander.belopolsky | 2011-01-06 22:57:06 +0100 (jeu., 06 janv. 2011) | 1 line
  
  Further simplify gettmarg()
................
  r87812 | brett.cannon | 2011-01-06 23:32:41 +0100 (jeu., 06 janv. 2011) | 2 lines
  
  Get --coverage to be an acceptable flag for test.regrtest again.
................
  r87813 | brett.cannon | 2011-01-07 00:08:16 +0100 (ven., 07 janv. 2011) | 1 line
  
  Undo an accidental commit in r87812.
................
  r87820 | georg.brandl | 2011-01-07 19:28:45 +0100 (ven., 07 janv. 2011) | 1 line
  
  #10856: document (Base)Exception.args better.
................
  r87821 | antoine.pitrou | 2011-01-07 19:33:07 +0100 (ven., 07 janv. 2011) | 3 lines
  
  Put link to source at the end. There's nothing edificating in threading.py.
................
  r87822 | antoine.pitrou | 2011-01-07 19:42:21 +0100 (ven., 07 janv. 2011) | 3 lines
  
  atexit.py doesn't exist
................
  r87823 | antoine.pitrou | 2011-01-07 19:43:14 +0100 (ven., 07 janv. 2011) | 3 lines
  
  Put those source links together
................
  r87824 | victor.stinner | 2011-01-07 19:47:22 +0100 (ven., 07 janv. 2011) | 5 lines
  
  Issue #10841: set binary mode on files; the parser translates newlines
  
  On Windows, set the binary mode on stdin, stdout, stderr and all
  io.FileIO objects (to not translate newlines, \r\n <=> \n). The Python parser
  translates newlines (\r\n => \n).
................
  r87825 | victor.stinner | 2011-01-07 19:56:19 +0100 (ven., 07 janv. 2011) | 1 line
  
  Issue #10841: don't translate newlines for pgen
................
  r87826 | antoine.pitrou | 2011-01-07 19:58:21 +0100 (ven., 07 janv. 2011) | 3 lines
  
  Put those "seealso"s together
................
  r87827 | antoine.pitrou | 2011-01-07 20:01:48 +0100 (ven., 07 janv. 2011) | 3 lines
  
  Group seealsos
................
  r87828 | antoine.pitrou | 2011-01-07 20:16:12 +0100 (ven., 07 janv. 2011) | 3 lines
  
  Mention multiprocessing.Queue in the queue docs
................
  r87829 | alexander.belopolsky | 2011-01-07 20:59:19 +0100 (ven., 07 janv. 2011) | 7 lines
  
  Issue #10827: Changed the rules for 2-digit years.  The time.asctime
  function will now format any year when time.accept2dyear is false and
  will accept years >= 1000 otherwise.  The year range accepted by
  time.mktime and time.strftime is still system dependent, but
  time.mktime will now accept full range supported by the OS. Conversion
  of 2-digit years to 4-digit is deprecated.
................
  r87830 | raymond.hettinger | 2011-01-07 21:33:09 +0100 (ven., 07 janv. 2011) | 2 lines
  
  Combine the two seealso sections.
................
  r87831 | georg.brandl | 2011-01-07 21:58:25 +0100 (ven., 07 janv. 2011) | 1 line
  
  Fix indent.
................
  r87832 | raymond.hettinger | 2011-01-07 22:04:30 +0100 (ven., 07 janv. 2011) | 2 lines
  
  Update the digest of PEP 3333 based on comments for Phillip Eby.
................
  r87833 | raymond.hettinger | 2011-01-07 22:17:56 +0100 (ven., 07 janv. 2011) | 1 line
  
  Revert r87823 which moved the source link to the wrong section.
................
  r87834 | antoine.pitrou | 2011-01-07 22:43:59 +0100 (ven., 07 janv. 2011) | 5 lines
  
  Issue #8020: Avoid a crash where the small objects allocator would read
  non-Python managed memory while it is being modified by another thread.
  Patch by Matt Bandy.
................
  r87835 | antoine.pitrou | 2011-01-07 22:47:02 +0100 (ven., 07 janv. 2011) | 3 lines
  
  Put NEWS entry in the right section.
................
  r87838 | raymond.hettinger | 2011-01-07 22:54:18 +0100 (ven., 07 janv. 2011) | 1 line
  
  Revert r87821 which moved the source link to the wrong section (from the module intro covering the module to a section on thread imports).
................
  r87839 | r.david.murray | 2011-01-07 22:57:25 +0100 (ven., 07 janv. 2011) | 9 lines
  
  Fix formatting of values with embedded newlines when rfc2047 encoding
  
  Before this patch if a value being encoded had an embedded newline,
  the line following the newline would have no leading whitespace,
  and the whitespace it did have was encoded into the word.  Now
  the existing whitespace gets turned into a blank, the way it does
  in other header reformatting, and the _continuation_ws gets added
  at the beginning of the encoded line.
................
  r87840 | r.david.murray | 2011-01-08 00:25:30 +0100 (sam., 08 janv. 2011) | 6 lines
  
  #10686: recode non-ASCII headers to 'unknown-8bit' instead of ?s.
  
  This applies only when generating strings from non-RFC compliant binary
  input; it makes the existing recoding behavior more consistent (ie:
  now no data is lost when recoding).
................
  r87843 | alexander.belopolsky | 2011-01-08 01:13:34 +0100 (sam., 08 janv. 2011) | 1 line
  
  Issue #1777412: extended year range of strftime down to 1000.
................
  r87844 | alexander.belopolsky | 2011-01-08 02:23:02 +0100 (sam., 08 janv. 2011) | 3 lines
  
  Fixed error handling branches.  Thanks
  Victor Stinner for pointing this out.
................
  r87845 | victor.stinner | 2011-01-08 02:56:31 +0100 (sam., 08 janv. 2011) | 4 lines
  
  Issue #1777412: strftime() accepts year >= 1 instead of year >= 1900
  
   * With Visual Studio, year have to be in [1; 9999]
   * Add more tests on the year field
................
  r87846 | victor.stinner | 2011-01-08 03:00:24 +0100 (sam., 08 janv. 2011) | 1 line
  
  Issue #1777412: test large years value for strftime('%Y')
................
  r87847 | victor.stinner | 2011-01-08 03:46:33 +0100 (sam., 08 janv. 2011) | 1 line
  
  Issue #1777412: fix test_time for Mac OS X and OpenIndiana
................
  r87848 | victor.stinner | 2011-01-08 04:06:52 +0100 (sam., 08 janv. 2011) | 3 lines
  
  Issue #1777412: Remove all limits on tm_year from time.strftime()
  
  The buildbots will tell us which platform does support or not negative years.
................
  r87849 | victor.stinner | 2011-01-08 04:16:05 +0100 (sam., 08 janv. 2011) | 1 line
  
  test_ssl: test SHA256 using sha256.tbs-internet.com instead of sha2.hboeck.de
................
  r87850 | victor.stinner | 2011-01-08 04:35:36 +0100 (sam., 08 janv. 2011) | 1 line
  
  Issue #10864: limit year to [1; 9999] for strftime() on Solaris
................
  r87853 | raymond.hettinger | 2011-01-08 08:01:56 +0100 (sam., 08 janv. 2011) | 4 lines
  
  Issue #10042: Fixed the total_ordering decorator to handle cross-type
  comparisons that could lead to infinite recursion.
................
  r87856 | raymond.hettinger | 2011-01-08 10:03:11 +0100 (sam., 08 janv. 2011) | 2 lines
  
  Issue #10813: Small improvement to decimal money format recipe.
................
  r87858 | raymond.hettinger | 2011-01-08 10:35:38 +0100 (sam., 08 janv. 2011) | 2 lines
  
  Issue 10533: Need example of using __missing__.
................
  r87859 | georg.brandl | 2011-01-08 10:45:43 +0100 (sam., 08 janv. 2011) | 1 line
  
  #10855: document close() semantics of wave objects.
................
  r87860 | antoine.pitrou | 2011-01-08 10:55:31 +0100 (sam., 08 janv. 2011) | 4 lines
  
  Issue #10859: Make `contextlib.GeneratorContextManager` officially
  private by renaming it to `_GeneratorContextManager`.
................
  r87861 | antoine.pitrou | 2011-01-08 11:23:29 +0100 (sam., 08 janv. 2011) | 3 lines
  
  Fix test_ssl after r87849
................
  r87862 | raymond.hettinger | 2011-01-08 11:26:53 +0100 (sam., 08 janv. 2011) | 3 lines
  
  Issue 9717:  Segregate and improve the documentation of "in-place" operators
  in the operator module.
................
  r87863 | antoine.pitrou | 2011-01-08 11:28:11 +0100 (sam., 08 janv. 2011) | 3 lines
  
  Add EHOSTUNREACH ('No route to host') to the errnos trapped by transient_internet().
................
  r87865 | raymond.hettinger | 2011-01-08 11:32:31 +0100 (sam., 08 janv. 2011) | 1 line
  
  Markup fix
................
  r87867 | victor.stinner | 2011-01-08 17:31:24 +0100 (sam., 08 janv. 2011) | 1 line
  
  Issue #1777412: document the change in the NEWS file
................
  r87868 | victor.stinner | 2011-01-08 17:37:47 +0100 (sam., 08 janv. 2011) | 1 line
  
  NEWS: merge #1777412 and #10827 entries
................
  r87869 | alexander.belopolsky | 2011-01-08 21:47:21 +0100 (sam., 08 janv. 2011) | 1 line
  
  Fixed documentation to reflect recent changes for years < 1900.
................
  r87870 | georg.brandl | 2011-01-08 22:04:25 +0100 (sam., 08 janv. 2011) | 1 line
  
  zlib only works with bytes objects.
................
  r87871 | raymond.hettinger | 2011-01-09 00:44:37 +0100 (dim., 09 janv. 2011) | 2 lines
  
  Issue #10357: Clarify what it means to be a mapping.
................
  r87873 | r.david.murray | 2011-01-09 03:35:24 +0100 (dim., 09 janv. 2011) | 12 lines
  
  #5871: protect against header injection attacks.
  
  This makes Header.encode throw a HeaderParseError if it winds up
  formatting a header such that a continuation line has no leading
  whitespace and looks like a header.  Since Header accepts values
  containing newlines and preserves them (and this is by design), without
  this fix any program that took user input (say, a subject in a web form)
  and passed it to the email package as a header was vulnerable to header
  injection attacks.  (As far as we know this has never been exploited.)
  
  Thanks to Jakub Wilk for reporting this vulnerability.
................
  r87876 | georg.brandl | 2011-01-09 08:38:51 +0100 (dim., 09 janv. 2011) | 1 line
  
  #10869: do not visit root node twice in ast.increment_lineno().
................
  r87877 | georg.brandl | 2011-01-09 08:50:48 +0100 (dim., 09 janv. 2011) | 1 line
  
  Add missing line.
................
  r87890 | georg.brandl | 2011-01-09 10:04:08 +0100 (dim., 09 janv. 2011) | 1 line
  
  Wrap some long examples and signatures.
................
  r87891 | georg.brandl | 2011-01-09 10:31:01 +0100 (dim., 09 janv. 2011) | 1 line
  
  #10871: "file" does not exist anymore in Python 3.  Also adapt the reprs of opened file objects.
................
  r87895 | lukasz.langa | 2011-01-09 19:18:53 +0100 (dim., 09 janv. 2011) | 5 lines
  
  #10874: test_urllib2 shouldn't use `is` operator for comparing strings
  
  Patch by Adreas Stührk.
................
  r87896 | martin.v.loewis | 2011-01-09 19:28:07 +0100 (dim., 09 janv. 2011) | 2 lines
  
  Add Ned Deily.
................
  r87897 | antoine.pitrou | 2011-01-09 21:38:15 +0100 (dim., 09 janv. 2011) | 6 lines
  
  Issue #10872: The repr() of TextIOWrapper objects now includes the mode
  if available.
  
  (at Georg's request)
................
  r87898 | raymond.hettinger | 2011-01-10 04:26:08 +0100 (lun., 10 janv. 2011) | 1 line
  
  Move source links to consistent location and remove wordy, big yellow boxes.
................
  r87899 | raymond.hettinger | 2011-01-10 06:40:57 +0100 (lun., 10 janv. 2011) | 2 lines
  
  Fix typos.
................
  r87900 | alexander.belopolsky | 2011-01-10 20:14:38 +0100 (lun., 10 janv. 2011) | 1 line
  
  Fixed a footnote reference
................
  r87901 | raymond.hettinger | 2011-01-10 20:54:11 +0100 (lun., 10 janv. 2011) | 1 line
  
  Separate source link from main text.
................
  r87902 | raymond.hettinger | 2011-01-10 22:16:07 +0100 (lun., 10 janv. 2011) | 1 line
  
  Missed two source links
................
  r87903 | raymond.hettinger | 2011-01-10 22:26:49 +0100 (lun., 10 janv. 2011) | 2 lines
  
  Misspelling.
................
  r87904 | terry.reedy | 2011-01-10 22:27:49 +0100 (lun., 10 janv. 2011) | 2 lines
  
  Issue #10875: Update Regular Expression HOWTO; patch by 'SilentGhost'.
................
  r87906 | alexander.belopolsky | 2011-01-10 22:55:34 +0100 (lun., 10 janv. 2011) | 1 line
  
  Added entries about removal of year 1900 limit.
................
  r87907 | alexander.belopolsky | 2011-01-10 22:58:52 +0100 (lun., 10 janv. 2011) | 1 line
  
  Removed time.ctime from the list of functions that take a time tuple argument
................
  r87908 | ned.deily | 2011-01-10 23:14:25 +0100 (lun., 10 janv. 2011) | 4 lines
  
  #10820: Fix OS X framework installs to support version-specific
          scripts (implemented in #10679).
................
  r87910 | alexander.belopolsky | 2011-01-10 23:56:14 +0100 (lun., 10 janv. 2011) | 1 line
  
  Issue #2568: Removed bogus rationale for supporting tm_sec=61.
................
  r87911 | victor.stinner | 2011-01-11 00:00:36 +0100 (mar., 11 janv. 2011) | 5 lines
  
  Issue #9566: Fix pyparse.xmlparser.ParseFile()
  
  Fix readinst() if file.read(n) returns a bytes object longer than n:
  return -1 instead of the the buffer size to raise an exception.
  Simplify also the function code.
................
  r87912 | terry.reedy | 2011-01-11 00:13:21 +0100 (mar., 11 janv. 2011) | 2 lines
  
  Issue #10875: Update Regular Expression HOWTO; last bit.
................
  r87914 | alexander.belopolsky | 2011-01-11 00:28:33 +0100 (mar., 11 janv. 2011) | 1 line
  
  Improved description of %Y directive.
................
  r87915 | alexander.belopolsky | 2011-01-11 00:31:51 +0100 (mar., 11 janv. 2011) | 1 line
  
  Improved  footnote for the %Y directive slightly.
................
  r87916 | raymond.hettinger | 2011-01-11 00:38:15 +0100 (mar., 11 janv. 2011) | 2 lines
  
  Fix typos and markup.
................
  r87917 | victor.stinner | 2011-01-11 01:04:12 +0100 (mar., 11 janv. 2011) | 1 line
  
  Issue #9611: remove useless and dangerous explicit conversion to size_t
................
  r87919 | alexander.belopolsky | 2011-01-11 02:21:25 +0100 (mar., 11 janv. 2011) | 4 lines
  
  Issue #1726687: time.mktime() will now correctly compute value one
  second before epoch.  Original patch by Peter Wang, reported by Martin
  Blais.
................
  r87920 | alexander.belopolsky | 2011-01-11 02:35:22 +0100 (mar., 11 janv. 2011) | 1 line
  
  Make mktime test more robust.
................
  r87921 | alexander.belopolsky | 2011-01-11 03:22:16 +0100 (mar., 11 janv. 2011) | 1 line
  
  This should fix mktime test on Windows
................
  r87922 | nick.coghlan | 2011-01-11 03:42:15 +0100 (mar., 11 janv. 2011) | 1 line
  
  developers.txt entry for Eli (at Brett's request)
................
  r87924 | raymond.hettinger | 2011-01-11 09:49:10 +0100 (mar., 11 janv. 2011) | 2 lines
  
  Add a todo.
................
  r87925 | nick.coghlan | 2011-01-11 11:05:20 +0100 (mar., 11 janv. 2011) | 1 line
  
  Issue 10556: test_zipimport_support implicitly imports too many modules (including _ssl) to safely clobber sys.modules after each test
................
  r87926 | eric.smith | 2011-01-11 11:24:34 +0100 (mar., 11 janv. 2011) | 1 line
  
  Typo.
................
  r87938 | raymond.hettinger | 2011-01-11 20:59:46 +0100 (mar., 11 janv. 2011) | 1 line
  
  Add entry for Barrier objects.
................
  r87939 | raymond.hettinger | 2011-01-11 21:51:45 +0100 (mar., 11 janv. 2011) | 2 lines
  
  Clean-up threading.Barrier example.
................
  r87940 | raymond.hettinger | 2011-01-11 22:13:26 +0100 (mar., 11 janv. 2011) | 2 lines
  
  Update the datetime and time section.
................
  r87941 | raymond.hettinger | 2011-01-11 22:20:20 +0100 (mar., 11 janv. 2011) | 1 line
  
  Update the email section
................
  r87942 | alexander.belopolsky | 2011-01-11 22:44:00 +0100 (mar., 11 janv. 2011) | 3 lines
  
  Issue #5109: array.array constructor will now use fast code when
  initial data is provided in an array object with correct type.
................
  r87943 | raymond.hettinger | 2011-01-11 23:08:55 +0100 (mar., 11 janv. 2011) | 2 lines
  
  Add comment.
................
  r87946 | terry.reedy | 2011-01-12 00:05:50 +0100 (mer., 12 janv. 2011) | 3 lines
  
  Issue #10225: Correct interactive Doc/howto/sorting.rst examples so doctest runs.
  Based on part of A. Belopolsky's patch.
................
  r87947 | raymond.hettinger | 2011-01-12 02:16:57 +0100 (mer., 12 janv. 2011) | 5 lines
  
  Revert r87946.  The virtues of readability and of examples that
  can be cut and pasted are more important than having a doctests
  on examples that already work.
................
  r87948 | nick.coghlan | 2011-01-12 04:15:52 +0100 (mer., 12 janv. 2011) | 1 line
  
  Issue 10889: Support slicing and indexing of large ranges (no docs changes, since, as far as I know, we never said anywhere that this *didn't* work)
................
  r87949 | benjamin.peterson | 2011-01-12 05:44:41 +0100 (mer., 12 janv. 2011) | 1 line
  
  fix weirdly ambigious sentence
................
  r87952 | benjamin.peterson | 2011-01-12 16:24:27 +0100 (mer., 12 janv. 2011) | 1 line
  
  move this test to test_descr; it's not abc specific
................
  r87953 | benjamin.peterson | 2011-01-12 16:25:02 +0100 (mer., 12 janv. 2011) | 1 line
  
  oops, wrong class
................
  r87954 | benjamin.peterson | 2011-01-12 16:34:01 +0100 (mer., 12 janv. 2011) | 1 line
  
  don't segfault on deleting __abstractmethods__ #10892
................
  r87957 | alexander.belopolsky | 2011-01-12 17:37:14 +0100 (mer., 12 janv. 2011) | 1 line
  
  Issue #10225: Fixed the simple mistakes in doctests.
................
  r87958 | antoine.pitrou | 2011-01-12 19:45:27 +0100 (mer., 12 janv. 2011) | 4 lines
  
  Issue #10822: Fix test_posix:test_getgroups failure under Solaris.  Patch
  by Ross Lagerwall.
................
  r87960 | benjamin.peterson | 2011-01-12 19:56:07 +0100 (mer., 12 janv. 2011) | 1 line
  
  use PyErr_SetString instead of PyErr_Format
................
  r87966 | raymond.hettinger | 2011-01-12 21:37:47 +0100 (mer., 12 janv. 2011) | 3 lines
  
  Remove function annotations that slipped into _abcoll.
  These are reserved for third-party use.
................
  r87968 | antoine.pitrou | 2011-01-12 21:46:37 +0100 (mer., 12 janv. 2011) | 4 lines
  
  Fix the expected memory use of utf-8 encoding.  Also, release the
  one reference to a huge object even when an exception is raised.
................
  r87969 | raymond.hettinger | 2011-01-12 21:52:39 +0100 (mer., 12 janv. 2011) | 1 line
  
  Remove the funky function annotation from numbers.py.
................
  r87971 | antoine.pitrou | 2011-01-12 22:19:59 +0100 (mer., 12 janv. 2011) | 3 lines
  
  Make test skipping message nicer, and remove the rather useless "overhead" parameter.
................
  r87972 | antoine.pitrou | 2011-01-12 22:40:20 +0100 (mer., 12 janv. 2011) | 3 lines
  
  Fix @bigmemtest when no limit is given by the user (oops)
................
  r87973 | antoine.pitrou | 2011-01-12 22:50:44 +0100 (mer., 12 janv. 2011) | 3 lines
  
  More informative skip message in @bigaddrspace
................
  r87974 | antoine.pitrou | 2011-01-12 22:58:39 +0100 (mer., 12 janv. 2011) | 3 lines
  
  A better message again
................
  r87975 | antoine.pitrou | 2011-01-12 23:02:45 +0100 (mer., 12 janv. 2011) | 3 lines
  
  Fix test_bigaddrspace (some tests didn't trigger the expected MemoryError)
................
  r87978 | raymond.hettinger | 2011-01-13 00:39:31 +0100 (jeu., 13 janv. 2011) | 4 lines
  
  Issue #10899: No function type annotations in the standard library.
  Removed function type annotations from _pyio.py.
................
  r87980 | raymond.hettinger | 2011-01-13 03:31:25 +0100 (jeu., 13 janv. 2011) | 1 line
  
  Issue 10899: Remove function type annotations from the stdlib
................
  r87981 | raymond.hettinger | 2011-01-13 03:52:26 +0100 (jeu., 13 janv. 2011) | 1 line
  
  Issue 10899: Remove function type annotations from the stdlib
................
  r87982 | benjamin.peterson | 2011-01-13 05:22:54 +0100 (jeu., 13 janv. 2011) | 1 line
  
  plug reference leak
................
  r87983 | georg.brandl | 2011-01-13 08:13:06 +0100 (jeu., 13 janv. 2011) | 1 line
  
  More PEP 8: no space around "=" in argument lists.
................
  r87984 | georg.brandl | 2011-01-13 08:24:40 +0100 (jeu., 13 janv. 2011) | 1 line
  
  Add semicolon for consistency.
................
  r87986 | georg.brandl | 2011-01-13 08:31:18 +0100 (jeu., 13 janv. 2011) | 1 line
  
  Fix the example output of count().
................
  r87988 | raymond.hettinger | 2011-01-13 19:15:51 +0100 (jeu., 13 janv. 2011) | 5 lines
  
  Issue #10899:  Move function type annotations into docstrings.
  
  Note, the docstrings (for the most part) were already very thorough
  and included type information.
................
  r87989 | raymond.hettinger | 2011-01-13 20:08:04 +0100 (jeu., 13 janv. 2011) | 1 line
  
  Issue 10899: Remove function type annotations from the stdlib
................
  r87990 | alexander.belopolsky | 2011-01-13 22:58:44 +0100 (jeu., 13 janv. 2011) | 5 lines
  
  Issue #9268: Documented -m pickletools usage.
  
  Also added a source code link.
................
  r87991 | eli.bendersky | 2011-01-14 08:31:14 +0100 (ven., 14 janv. 2011) | 2 lines
  
  Remove call to nonexisting function (relic from Python 2.x) under #ifdef __INSURE__. Issue 9844
................
  r87993 | eli.bendersky | 2011-01-14 09:25:03 +0100 (ven., 14 janv. 2011) | 2 lines
  
  Issue #10902: Fix reference to run* methods
................
  r87996 | victor.stinner | 2011-01-14 13:52:12 +0100 (ven., 14 janv. 2011) | 1 line
  
  Add encoding and errors arguments to urllib.parse_qs() and urllib.parse_qsl()
................
  r87997 | victor.stinner | 2011-01-14 14:05:19 +0100 (ven., 14 janv. 2011) | 1 line
  
  test_urlparse: add tests for encoding and errors arguments
................
  r87998 | victor.stinner | 2011-01-14 14:05:21 +0100 (ven., 14 janv. 2011) | 3 lines
  
  Issue #4953: cgi.FieldStorage and cgi.parse() parse the request as bytes, not
  as unicode, and accept binary files. Add encoding and errors attributes to
  cgi.FieldStorage.
................
  r87999 | victor.stinner | 2011-01-14 14:08:27 +0100 (ven., 14 janv. 2011) | 1 line
  
  cgi: use isinstance(x, list) instead of type(x) == type([])
................
  r88000 | victor.stinner | 2011-01-14 14:31:45 +0100 (ven., 14 janv. 2011) | 1 line
  
  urllib doc: add versionchanged sections for parse_qs() and parse_qsl()
................
  r88001 | victor.stinner | 2011-01-14 15:11:45 +0100 (ven., 14 janv. 2011) | 1 line
  
  Issue #4953: add the author of the patch
................
  r88003 | ned.deily | 2011-01-15 05:37:12 +0100 (sam., 15 janv. 2011) | 5 lines
  
  #10907: Warn OS X 10.6 IDLE users to use ActiveState Tcl/Tk 8.5,
          rather than the currently problematic Apple-supplied one,
          when running with the 64-/32-bit installer variant.
................
  r88004 | ned.deily | 2011-01-15 05:44:12 +0100 (sam., 15 janv. 2011) | 4 lines
  
  #10907: Update OS X installer build README to better reflect
          current build practices.
................
  r88005 | ned.deily | 2011-01-15 06:05:53 +0100 (sam., 15 janv. 2011) | 5 lines
  
  #10843: Install the Tools directory on OS X in the applications
          Extras (/Applications/Python 3.n/Extras/) where the Demo
          directory had previous been installed.
................
  r88006 | ned.deily | 2011-01-15 06:29:12 +0100 (sam., 15 janv. 2011) | 6 lines
  
  #10843: Update third-party library versions used in OS X 32-bit
          installer builds: bzip2 1.0.6, readline 6.1.2, SQLite 3.7.4
          (with FTS3/FTS4 and RTREE enabled), and ncursesw 5.5 (wide-char
          support enabled).
................
  r88007 | ned.deily | 2011-01-15 06:44:21 +0100 (sam., 15 janv. 2011) | 5 lines
  
  Remove spurious copy of Mac/IDLE/idlemain.py left over from
  conversion from Python 2 build process.  The correct version
  is in Mac/IDLE/IDLE.app/Contents/Resources/
................
  r88008 | ned.deily | 2011-01-15 06:53:33 +0100 (sam., 15 janv. 2011) | 2 lines
  
  Add self to mac platform area in maintainers.rst.
................
  r88009 | eli.bendersky | 2011-01-15 11:23:34 +0100 (sam., 15 janv. 2011) | 2 lines
  
  Issue #10912: Clarify the documentation of PyObject_RichCompareBool. Thanks to Devin Jeanpierre for spotting the problem.
................
  r88011 | antoine.pitrou | 2011-01-15 12:37:11 +0100 (sam., 15 janv. 2011) | 4 lines
  
  Fix the GIL with subinterpreters. Hopefully this will allow mod_wsgi to work with 3.2.
  (we need some tests for this)
................
  r88012 | antoine.pitrou | 2011-01-15 12:39:23 +0100 (sam., 15 janv. 2011) | 3 lines
  
  Avoid ResourceWarnings in ccbench
................
  r88013 | antoine.pitrou | 2011-01-15 12:44:17 +0100 (sam., 15 janv. 2011) | 3 lines
  
  Standard streams use file descriptors, not FILE pointers.
................
  r88014 | antoine.pitrou | 2011-01-15 12:57:42 +0100 (sam., 15 janv. 2011) | 3 lines
  
  Restructure a bit
................
  r88015 | antoine.pitrou | 2011-01-15 13:10:48 +0100 (sam., 15 janv. 2011) | 3 lines
  
  Improve description of issues
................
  r88016 | antoine.pitrou | 2011-01-15 13:21:53 +0100 (sam., 15 janv. 2011) | 3 lines
  
  Add mention of how to switch interpreters
................
  r88017 | antoine.pitrou | 2011-01-15 13:54:19 +0100 (sam., 15 janv. 2011) | 3 lines
  
  Reword and restructure the GIL API doc
................
  r88018 | antoine.pitrou | 2011-01-15 14:11:48 +0100 (sam., 15 janv. 2011) | 4 lines
  
  Issue #10913: Deprecate misleading functions PyEval_AcquireLock() and
  PyEval_ReleaseLock().  The thread-state aware APIs should be used instead.
................
  r88021 | antoine.pitrou | 2011-01-15 15:31:49 +0100 (sam., 15 janv. 2011) | 3 lines
  
  Nits
................
  r88022 | antoine.pitrou | 2011-01-15 17:17:07 +0100 (sam., 15 janv. 2011) | 7 lines
  
  Issue #10916: mmap should not segfault when a file is mapped using 0 as
  length and a non-zero offset, and an attempt to read past the end of file
  is made (IndexError is raised instead).  Patch by Ross Lagerwall.
  
  Requested by Georg.
................
  r88026 | georg.brandl | 2011-01-15 17:44:11 +0100 (sam., 15 janv. 2011) | 1 line
  
  Update pydoc topics.
................
  r88028 | georg.brandl | 2011-01-15 17:45:03 +0100 (sam., 15 janv. 2011) | 1 line
  
  Update to 1.0.7.
................
  r88032 | georg.brandl | 2011-01-15 18:03:02 +0100 (sam., 15 janv. 2011) | 1 line
  
  Fix a few doc errors, mostly undefined keywords.
................
  r88033 | georg.brandl | 2011-01-15 18:05:20 +0100 (sam., 15 janv. 2011) | 1 line
  
  Fix "make suspicious" errors and update ignore file.
................
  r88035 | georg.brandl | 2011-01-15 18:08:53 +0100 (sam., 15 janv. 2011) | 1 line
  
  Bump to 3.2rc1.
................
  r88036 | antoine.pitrou | 2011-01-15 18:25:58 +0100 (sam., 15 janv. 2011) | 3 lines
  
  Fix mmap and test_mmap under Windows too (followup to r88022)
................
  r88040 | martin.v.loewis | 2011-01-15 20:43:18 +0100 (sam., 15 janv. 2011) | 2 lines
  
  Package zip_cp437_header.zip.
  Don't try to package subprocessdata/*.py twice.
................
  r88041 | georg.brandl | 2011-01-16 09:44:50 +0100 (dim., 16 janv. 2011) | 1 line
  
  Post-release updates.
................
  r88042 | georg.brandl | 2011-01-16 10:11:45 +0100 (dim., 16 janv. 2011) | 1 line
  
  Fix two small issues.
................
  r88043 | raymond.hettinger | 2011-01-16 10:16:27 +0100 (dim., 16 janv. 2011) | 1 line
  
  Remove out-of-date comment
................
  r88044 | raymond.hettinger | 2011-01-16 10:18:59 +0100 (dim., 16 janv. 2011) | 2 lines
  
  Clean-up comment.
................
  r88047 | nick.coghlan | 2011-01-16 14:08:48 +0100 (dim., 16 janv. 2011) | 1 line
  
  Add missing NEWS entry for r87948
................
  r88048 | georg.brandl | 2011-01-16 15:17:26 +0100 (dim., 16 janv. 2011) | 1 line
  
  Rewrap and punctuation consistency.
................
  r88049 | antoine.pitrou | 2011-01-16 19:16:09 +0100 (dim., 16 janv. 2011) | 3 lines
  
  Better description of SSL-related changes
................
  r88050 | antoine.pitrou | 2011-01-16 19:16:52 +0100 (dim., 16 janv. 2011) | 3 lines
  
  Fix misindent
................
  r88051 | antoine.pitrou | 2011-01-16 19:21:12 +0100 (dim., 16 janv. 2011) | 3 lines
  
  Get proper credit
................
  r88052 | raymond.hettinger | 2011-01-16 19:22:06 +0100 (dim., 16 janv. 2011) | 3 lines
  
  Issue 10889: Added entry for handling of indexing and slicing with ranges bigger than sys.maxsize.
................
  r88053 | antoine.pitrou | 2011-01-16 19:29:34 +0100 (dim., 16 janv. 2011) | 4 lines
  
  Mention the new context parameter to FTP_TLS, and the small API change
  in subprocess.Popen.
................
  r88054 | antoine.pitrou | 2011-01-16 19:34:09 +0100 (dim., 16 janv. 2011) | 3 lines
  
  Mention HTTP 0.9's partial demise.
................
  r88055 | antoine.pitrou | 2011-01-16 19:41:36 +0100 (dim., 16 janv. 2011) | 3 lines
  
  More SSL-related stuff
................
  r88056 | antoine.pitrou | 2011-01-16 19:45:17 +0100 (dim., 16 janv. 2011) | 3 lines
  
  Mention deprecation of PyEval_{Acquire,Release}Lock().
................
  r88057 | matthias.klose | 2011-01-16 21:57:01 +0100 (dim., 16 janv. 2011) | 2 lines
  
  rangeobject.c (compute_slice_indices): Make function static.
................
  r88058 | brett.cannon | 2011-01-16 22:02:09 +0100 (dim., 16 janv. 2011) | 1 line
  
  Placeholder sentence pointing out that imoprtlib has updated (as well as deprecated) ABCs thanks to the new .pyc situation.
................
  r88063 | benjamin.peterson | 2011-01-17 20:24:34 +0100 (lun., 17 janv. 2011) | 4 lines
  
  turn some checks into assertions, since they are implied by the caller
  
  Reviewed by Georg.
................
  r88066 | benjamin.peterson | 2011-01-17 20:44:46 +0100 (lun., 17 janv. 2011) | 1 line
  
  correct assertion
................
  r88069 | benjamin.peterson | 2011-01-17 20:54:55 +0100 (lun., 17 janv. 2011) | 1 line
  
  remove unneeded assertion
................
  r88072 | raymond.hettinger | 2011-01-17 22:05:07 +0100 (lun., 17 janv. 2011) | 2 lines
  
  Note that two-phase cyclic barriers are suitable for use in loops.
................
  r88073 | brett.cannon | 2011-01-17 22:12:54 +0100 (lun., 17 janv. 2011) | 1 line
  
  Short README on gdb support.
................
  r88074 | raymond.hettinger | 2011-01-17 22:29:58 +0100 (lun., 17 janv. 2011) | 2 lines
  
  Tidy-up the ssl section.
................
  r88075 | raymond.hettinger | 2011-01-17 22:55:40 +0100 (lun., 17 janv. 2011) | 2 lines
  
  Fix-up the XXX for importlib.abc.
................
  r88076 | raymond.hettinger | 2011-01-17 23:33:11 +0100 (lun., 17 janv. 2011) | 2 lines
  
  Wording nits.
................
  r88077 | raymond.hettinger | 2011-01-18 00:10:55 +0100 (mar., 18 janv. 2011) | 2 lines
  
  Beautify code examples.
................
  r88078 | raymond.hettinger | 2011-01-18 00:39:39 +0100 (mar., 18 janv. 2011) | 2 lines
  
  The example for configparser was weird.
................
  r88079 | raymond.hettinger | 2011-01-18 00:42:17 +0100 (mar., 18 janv. 2011) | 2 lines
  
  Add an import to the logging example
................
  r88080 | benjamin.peterson | 2011-01-18 00:49:51 +0100 (mar., 18 janv. 2011) | 1 line
  
  very out of date file
................
  r88083 | raymond.hettinger | 2011-01-18 01:02:40 +0100 (mar., 18 janv. 2011) | 2 lines
  
  Nits.
................
  r88084 | raymond.hettinger | 2011-01-18 01:19:30 +0100 (mar., 18 janv. 2011) | 2 lines
  
  Add example for the abc module.
................
  r88085 | raymond.hettinger | 2011-01-18 01:30:24 +0100 (mar., 18 janv. 2011) | 2 lines
  
  More nits.
................
  r88092 | raymond.hettinger | 2011-01-18 08:15:39 +0100 (mar., 18 janv. 2011) | 2 lines
  
  Nits.
................
  r88093 | raymond.hettinger | 2011-01-18 09:28:01 +0100 (mar., 18 janv. 2011) | 2 lines
  
  More nits.
................
  r88094 | raymond.hettinger | 2011-01-18 10:01:34 +0100 (mar., 18 janv. 2011) | 2 lines
  
  Typos.
................
  r88097 | antoine.pitrou | 2011-01-18 19:57:52 +0100 (mar., 18 janv. 2011) | 4 lines
  
  Issue #10451: memoryview objects could allow to mutate a readable buffer.
  Initial patch by Ross Lagerwall.
................
  r88100 | raymond.hettinger | 2011-01-18 21:25:04 +0100 (mar., 18 janv. 2011) | 3 lines
  
  Reword the OrderedDict entry to emphasize the default behavior,
  to show equivalent code, and to provide a use case.
................
  r88101 | raymond.hettinger | 2011-01-18 22:14:27 +0100 (mar., 18 janv. 2011) | 2 lines
  
  Missing word.
................
  r88102 | raymond.hettinger | 2011-01-18 23:58:33 +0100 (mar., 18 janv. 2011) | 2 lines
  
  Expand barrier example to show time-outs.
................
  r88103 | david.malcolm | 2011-01-19 00:45:53 +0100 (mer., 19 janv. 2011) | 2 lines
  
  Fix typo in example of barrier timeouts from r88102
................
  r88104 | brett.cannon | 2011-01-19 01:49:06 +0100 (mer., 19 janv. 2011) | 2 lines
  
  Klocwork scan site no longer available.
................
  r88105 | raymond.hettinger | 2011-01-19 05:14:34 +0100 (mer., 19 janv. 2011) | 2 lines
  
  Add examples for inspect.
................
  r88106 | raymond.hettinger | 2011-01-19 05:24:57 +0100 (mer., 19 janv. 2011) | 2 lines
  
  Improve looks by replacing a bullet list with a table.
................
  r88107 | raymond.hettinger | 2011-01-19 05:43:45 +0100 (mer., 19 janv. 2011) | 2 lines
  
  Expand entry for pydoc.
................
  r88108 | georg.brandl | 2011-01-19 09:42:03 +0100 (mer., 19 janv. 2011) | 1 line
  
  Suppress trailing spaces in table paragraphs.
................
  r88109 | raymond.hettinger | 2011-01-19 09:44:33 +0100 (mer., 19 janv. 2011) | 2 lines
  
  Fix markup.
................
  r88111 | antoine.pitrou | 2011-01-19 16:21:35 +0100 (mer., 19 janv. 2011) | 4 lines
  
  Issue #10898: Allow compiling the posix module when the C library defines
  a symbol named FSTAT.
................
  r88114 | alexander.belopolsky | 2011-01-19 20:53:30 +0100 (mer., 19 janv. 2011) | 5 lines
  
  Issue #10934: Fixed and expanded Internaldate2tuple() and
  Time2Internaldate() documentation.  Thanks Joe Peterson for the report
  and the original patch.
................
  r88115 | georg.brandl | 2011-01-19 21:05:49 +0100 (mer., 19 janv. 2011) | 1 line
  
  #10944: add c_bool to types table.
................
  r88117 | brett.cannon | 2011-01-20 00:08:44 +0100 (jeu., 20 janv. 2011) | 1 line
  
  Rename AIX-NOTES to something that follows the convention in Misc.
................
  r88118 | brett.cannon | 2011-01-20 04:56:50 +0100 (jeu., 20 janv. 2011) | 2 lines
  
  Move maintainers.rst into the devguide and rename it the Experts Index.
................
  r88119 | raymond.hettinger | 2011-01-20 05:03:19 +0100 (jeu., 20 janv. 2011) | 1 line
  
  Add more examples
................
  r88120 | raymond.hettinger | 2011-01-20 05:12:37 +0100 (jeu., 20 janv. 2011) | 2 lines
  
  Add hasattr() example.
................
  r88121 | raymond.hettinger | 2011-01-20 10:04:39 +0100 (jeu., 20 janv. 2011) | 4 lines
  
  Make an entry for the os module's bytes accessors.
  Split codecs into a separate section.  Rewrite
  the Unicode section.
................
  r88122 | raymond.hettinger | 2011-01-20 10:47:04 +0100 (jeu., 20 janv. 2011) | 2 lines
  
  Add an entry for the code repository.
................
  r88125 | brett.cannon | 2011-01-20 20:30:51 +0100 (jeu., 20 janv. 2011) | 1 line
  
  Move README.Emacs to the devguide.
................
  r88126 | brett.cannon | 2011-01-20 20:33:06 +0100 (jeu., 20 janv. 2011) | 1 line
  
  Move README.gdb to the devguide.
................
  r88127 | brett.cannon | 2011-01-20 20:34:35 +0100 (jeu., 20 janv. 2011) | 1 line
  
  Remove some outdated files from Misc.
................
  r88128 | brett.cannon | 2011-01-20 20:36:12 +0100 (jeu., 20 janv. 2011) | 1 line
  
  Update Misc/README.
................
  r88129 | brett.cannon | 2011-01-20 20:42:08 +0100 (jeu., 20 janv. 2011) | 1 line
  
  Move developers.txt to the devguide.
................
  r88130 | alexander.belopolsky | 2011-01-20 20:51:31 +0100 (jeu., 20 janv. 2011) | 1 line
  
  Corrected the entry about new year range in the time module.
................
  r88131 | antoine.pitrou | 2011-01-20 22:07:24 +0100 (jeu., 20 janv. 2011) | 6 lines
  
  Issue #10955: Fix a potential crash when trying to mmap() a file past its
  length.  Initial patch by Ross Lagerwall.
  
  This fixes a regression introduced by r88022.
................
  r88134 | raymond.hettinger | 2011-01-21 04:00:00 +0100 (ven., 21 janv. 2011) | 2 lines
  
  Clarify what changed with respect to date ranges and two-digit years.
................
  r88135 | raymond.hettinger | 2011-01-21 05:59:00 +0100 (ven., 21 janv. 2011) | 2 lines
  
  Add example for __wrapped__.
................
  r88136 | raymond.hettinger | 2011-01-21 10:18:19 +0100 (ven., 21 janv. 2011) | 2 lines
  
  Use a Latin-1 example that won't break the LaTeX PDF build.
................
  r88137 | antoine.pitrou | 2011-01-21 22:37:32 +0100 (ven., 21 janv. 2011) | 3 lines
  
  Fix JSON docs about loads() accepting only str objects, not bytes.
................
  r88139 | vinay.sajip | 2011-01-22 00:35:57 +0100 (sam., 22 janv. 2011) | 1 line
  
  Issue #10949: Improved robustness of rotating file handlers.
................
  r88140 | victor.stinner | 2011-01-22 11:30:29 +0100 (sam., 22 janv. 2011) | 6 lines
  
  Issue #10955: zipimport uses ASCII at bootstrap
  
  zipimport uses ASCII encoding instead of cp497 to decode filenames, at
  bootstrap, if the codec registry is not ready yet. It is still possible to have
  non-ASCII filenames using the Unicode flag (UTF-8 encoding) for file entries in
  the ZIP file.
................
  r88141 | victor.stinner | 2011-01-22 11:33:01 +0100 (sam., 22 janv. 2011) | 1 line
  
  Issue #10955: fix NEWS entry
................
  r88142 | armin.ronacher | 2011-01-22 14:13:05 +0100 (sam., 22 janv. 2011) | 5 lines
  
  Issue #10980: encode headers with latin1 instead of ASCII in the HTTP server.
  This makes the implementation of PEP 3333 compliant servers on top of
  BaseHTTPServer possible.
................
  r88143 | armin.ronacher | 2011-01-22 14:44:22 +0100 (sam., 22 janv. 2011) | 7 lines
  
  To match the behaviour of HTTP server, the HTTP client library now also encodes
  headers with iso-8859-1 (latin1) encoding.  It was already doing that for
  incoming headers which makes this behaviour now consistent in both incoming and
  outgoing direction.
................
  r88144 | georg.brandl | 2011-01-22 23:06:24 +0100 (sam., 22 janv. 2011) | 1 line
  
  #10983: fix several bugs in the _tunnel implementation that seem to have missed while porting between branches.  A unittest is needed!
................
  r88145 | victor.stinner | 2011-01-23 01:11:58 +0100 (dim., 23 janv. 2011) | 1 line
  
  Issue #10955: Fix typo in NEWS, cp497 => cp437
................
  r88146 | raymond.hettinger | 2011-01-23 12:29:08 +0100 (dim., 23 janv. 2011) | 1 line
  
  Add entry for shutil's archiving operations.
................
  r88147 | antoine.pitrou | 2011-01-23 18:12:25 +0100 (dim., 23 janv. 2011) | 3 lines
  
  Issue #10987: Fix the recursion limit handling in the _pickle module.
................
  r88149 | raymond.hettinger | 2011-01-23 22:05:46 +0100 (dim., 23 janv. 2011) | 1 line
  
  Add entry for reprlib.
................
  r88150 | raymond.hettinger | 2011-01-23 22:13:27 +0100 (dim., 23 janv. 2011) | 2 lines
  
  Add tracker references.
................
  r88151 | raymond.hettinger | 2011-01-23 22:32:18 +0100 (dim., 23 janv. 2011) | 2 lines
  
  minor clean-up.
................
  r88152 | raymond.hettinger | 2011-01-23 22:33:36 +0100 (dim., 23 janv. 2011) | 1 line
  
  Fix typo.
................
  r88153 | brett.cannon | 2011-01-24 00:06:05 +0100 (lun., 24 janv. 2011) | 6 lines
  
  Skip a recursion depth check test when running under CPython and have a trace
  function set. Otherwise a Python fatal error about hitting an unrecoverable
  recursion depth gets triggered.
  
  Closes issue #10985. Code review by Georg Brandl.
................
  r88154 | raymond.hettinger | 2011-01-24 02:18:30 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Add entries for array, asyncore, csv, compileall, and ast.
................
  r88155 | raymond.hettinger | 2011-01-24 02:51:49 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Add entries for dis, dbm, and ctypes.
................
  r88156 | raymond.hettinger | 2011-01-24 05:52:27 +0100 (lun., 24 janv. 2011) | 1 line
  
  Make the type consistent for hashlib algorithm constants.  (Reviewed by Benjamin).
................
  r88157 | raymond.hettinger | 2011-01-24 06:07:13 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Add entry for hashlib and expand the GC entry.
................
  r88158 | raymond.hettinger | 2011-01-24 06:26:00 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Add entry for the html module.
................
  r88159 | raymond.hettinger | 2011-01-24 10:01:27 +0100 (lun., 24 janv. 2011) | 1 line
  
  Add section for urllib.parse.
................
  r88160 | raymond.hettinger | 2011-01-24 10:17:24 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Add entry for hash_info().
................
  r88161 | raymond.hettinger | 2011-01-24 11:11:12 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Fix markup and add todo.
................
  r88162 | raymond.hettinger | 2011-01-24 17:28:06 +0100 (lun., 24 janv. 2011) | 1 line
  
  Missing source links.
................
  r88163 | raymond.hettinger | 2011-01-24 19:19:01 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Typos.
................
  r88164 | r.david.murray | 2011-01-24 20:34:58 +0100 (lun., 24 janv. 2011) | 12 lines
  
  #10960: fix 'stat' links, link to lstat from stat, general tidy of stat doc.
  
  Original patch by Michal Nowikowski, with some additions and wording
  fixes by me. 
  
  I changed the wording from 'Performs a stat system call' to 'Performs
  the equivalent of a stat system call', since on Windows there are no
  stat/lstat system calls involved.  I also extended Michal's breakout
  of the attributes into a list to the other paragraphs, and rearranged
  the order of the paragraphs in the 'stat' docs to make it flow
  better and put it in what I think is a more logical/useful order.
................
  r88165 | georg.brandl | 2011-01-24 20:53:18 +0100 (lun., 24 janv. 2011) | 1 line
  
  Typo fix.
................
  r88166 | georg.brandl | 2011-01-24 20:59:08 +0100 (lun., 24 janv. 2011) | 1 line
  
  Fix label syntax.
................
  r88170 | terry.reedy | 2011-01-24 21:48:40 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Update last tix code example for 3.x, as already done for previous examples.
................
  r88171 | steven.bethard | 2011-01-24 22:02:50 +0100 (lun., 24 janv. 2011) | 1 line
  
  Issue #9509: make argarse properly handle IOErrors raised by argparse.FileType. Approved by Georg in the tracker.
................
  r88172 | terry.reedy | 2011-01-24 22:36:03 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Issue #11000 ast.parse parses source, not just expressions.
................
  r88174 | ned.deily | 2011-01-24 22:46:44 +0100 (lun., 24 janv. 2011) | 6 lines
  
  #10974: IDLE no longer crashes if its recent files list includes files
          with non-ASCII characters in their path names.
  
          (with approval of release manager for 3.2rc2)
................
  r88176 | raymond.hettinger | 2011-01-24 23:14:42 +0100 (lun., 24 janv. 2011) | 2 lines
  
  Add entry for io.BytesIO.getbuffer().
................
  r88178 | benjamin.peterson | 2011-01-25 01:00:28 +0100 (mar., 25 janv. 2011) | 1 line
  
  another pretty crasher served up by pypy
................
  r88179 | brett.cannon | 2011-01-25 01:56:18 +0100 (mar., 25 janv. 2011) | 1 line
  
  Ignore the gdb.py file under OS X.
................
  r88180 | raymond.hettinger | 2011-01-25 03:35:58 +0100 (mar., 25 janv. 2011) | 2 lines
  
  Add entry for the math module.
................
  r88181 | raymond.hettinger | 2011-01-25 03:38:59 +0100 (mar., 25 janv. 2011) | 2 lines
  
  Nits.
................
  r88182 | raymond.hettinger | 2011-01-25 06:53:27 +0100 (mar., 25 janv. 2011) | 2 lines
  
  Typo.
................
  r88183 | raymond.hettinger | 2011-01-25 07:58:01 +0100 (mar., 25 janv. 2011) | 1 line
  
  Add math.erfc and turtledemo.
................
  r88184 | raymond.hettinger | 2011-01-25 08:46:07 +0100 (mar., 25 janv. 2011) | 2 lines
  
  Add entries for select and site.
................
  r88185 | raymond.hettinger | 2011-01-25 09:01:01 +0100 (mar., 25 janv. 2011) | 2 lines
  
  Typo.
................
  r88186 | antoine.pitrou | 2011-01-25 17:28:44 +0100 (mar., 25 janv. 2011) | 3 lines
  
  Fix the doc for PIPE_BUF
................
  r88187 | antoine.pitrou | 2011-01-25 18:24:57 +0100 (mar., 25 janv. 2011) | 3 lines
  
  Fix the description of PIPE_BUF
................
  r88188 | brett.cannon | 2011-01-25 19:26:35 +0100 (mar., 25 janv. 2011) | 3 lines
  
  Tighten the restrictions on the test_sys test which triggers a fatal error when
  run with tracing turned on.
................
  r88191 | raymond.hettinger | 2011-01-25 22:32:39 +0100 (mar., 25 janv. 2011) | 9 lines
  
  Issue #11004:  Repair edge case in deque.count().
  (Reviewed by Georg Brandl.)
  
  Also made similar changes to deque.reverse() though this wasn't
  strictly necessary (the edge case cannot occur with two pointers
  moving to meet in the middle).  Making the change in reverse()
  was more a matter of future-proofing.
................
  r88196 | victor.stinner | 2011-01-26 00:15:47 +0100 (mer., 26 janv. 2011) | 3 lines
  
  fix import in email.message_from_binary_file()
  
  Parser => BytesParser
................
  r88197 | victor.stinner | 2011-01-26 01:39:19 +0100 (mer., 26 janv. 2011) | 1 line
  
  Fix BytesGenerator._handle_text() if the message has no payload (None)
................
  r88198 | raymond.hettinger | 2011-01-26 02:13:26 +0100 (mer., 26 janv. 2011) | 2 lines
  
  Add a few imports to examples.
................
  r88199 | r.david.murray | 2011-01-26 03:31:37 +0100 (mer., 26 janv. 2011) | 2 lines
  
  Revert r88197.  I'll refix correctly once there is a test.
................
  r88200 | raymond.hettinger | 2011-01-26 20:36:13 +0100 (mer., 26 janv. 2011) | 2 lines
  
  Markup nits.
................
  r88201 | raymond.hettinger | 2011-01-26 21:34:14 +0100 (mer., 26 janv. 2011) | 7 lines
  
  Issue #11014: Make 'filter' argument in tarfile.Tarfile.add() into a
  keyword-only argument.  The preceding positional argument was deprecated,
  so it made no sense to add filter as a positional argument.
  
  (Patch reviewed by Brian Curtin and Anthony Long.)
................
  r88203 | r.david.murray | 2011-01-26 22:21:32 +0100 (mer., 26 janv. 2011) | 4 lines
  
  #11019: Make BytesGenerator handle Message with None body.
  
  Bug discovery and initial patch by Victor Stinner.
................
  r88204 | antoine.pitrou | 2011-01-27 00:29:28 +0100 (jeu., 27 janv. 2011) | 4 lines
  
  Issue #11018: fix a test to not be a no-op in test_bz2.
  Found by Nadeem Vawda, reviewed by Brett.
................
  r88207 | raymond.hettinger | 2011-01-27 01:06:54 +0100 (jeu., 27 janv. 2011) | 6 lines
  
  Issue #11020: Command-line pyclbr was broken because of missing 2-to-3
  conversion.
  
  (Patch reviewed by David Murray.)
................
  r88209 | raymond.hettinger | 2011-01-27 02:20:32 +0100 (jeu., 27 janv. 2011) | 1 line
  
  More source links.
................
  r88210 | raymond.hettinger | 2011-01-27 06:48:56 +0100 (jeu., 27 janv. 2011) | 2 lines
  
  Add an entry for tarfile.
................
  r88211 | raymond.hettinger | 2011-01-27 07:10:18 +0100 (jeu., 27 janv. 2011) | 2 lines
  
  Update todo list.
................
  r88212 | raymond.hettinger | 2011-01-27 07:46:54 +0100 (jeu., 27 janv. 2011) | 2 lines
  
  Add missing attributions.
................
  r88213 | raymond.hettinger | 2011-01-27 08:34:45 +0100 (jeu., 27 janv. 2011) | 2 lines
  
  More typical sample invocation of tarfile.
................
  r88214 | vinay.sajip | 2011-01-27 20:14:16 +0100 (jeu., 27 janv. 2011) | 1 line
  
  Issue 11008: docs updated to show versionadded for dictConfig.
................
  r88215 | raymond.hettinger | 2011-01-27 21:38:46 +0100 (jeu., 27 janv. 2011) | 1 line
  
  More source links
................
  r88220 | lukasz.langa | 2011-01-28 12:57:30 +0100 (ven., 28 janv. 2011) | 3 lines
  
  #11027: documented how to override SECTCRE 
................
  r88221 | michael.foord | 2011-01-28 20:51:48 +0100 (ven., 28 janv. 2011) | 3 lines
  
  Issue 10573: revert unittest docs to first / second
  Minor internal change to unittest.TestCase.assertCountEqual
  Reviewed by R. David Murray
................
  r88222 | eric.smith | 2011-01-28 21:23:25 +0100 (ven., 28 janv. 2011) | 1 line
  
  Added a placeholder for str.format_map, as discussed with Raymond. My prose is horrible, some cleanup is required.
................
  r88223 | raymond.hettinger | 2011-01-29 09:51:57 +0100 (sam., 29 janv. 2011) | 3 lines
  
  Add entry for str.format_map().
  Add bullet list and reference to documentation section.
................
  r88226 | eric.smith | 2011-01-29 12:15:35 +0100 (sam., 29 janv. 2011) | 3 lines
  
  Issue #11302: missing type check on _string.formatter_field_name_split and _string.formatter_parser caused crash.
  
  Originial patch by haypo, reviewed by me, okayed by Georg.
................
  r88228 | victor.stinner | 2011-01-29 12:31:20 +0100 (sam., 29 janv. 2011) | 3 lines
  
  Issue #10989: Fix a crash on SSLContext.load_verify_locations(None, True).
  
  Patch reviewed by Antoine Pitrou, okayed by Georg Brandl.
................
  r88230 | giampaolo.rodola | 2011-01-29 14:24:33 +0100 (sam., 29 janv. 2011) | 1 line
  
  fix reference to issue where the addition of select.PIPE_BUF was discussed
................
  r88231 | alexander.belopolsky | 2011-01-29 18:19:08 +0100 (sam., 29 janv. 2011) | 4 lines
  
  Issue #10939: Fixed imaplib.Internaldate2tuple(). Thanks Joe Peterson
  for the report and the patch.  Reviewed by Georg Brandl.
................
  r88232 | ned.deily | 2011-01-29 19:29:01 +0100 (sam., 29 janv. 2011) | 5 lines
  
  Issue #10940: Workaround an IDLE hang on Mac OS X 10.6 when using the
  menu accelerators for Open Module, Go to Line, and New Indent Width.
  The accelerators still work but no longer appear in the menu items.
................
  r88234 | ned.deily | 2011-01-29 19:43:56 +0100 (sam., 29 janv. 2011) | 5 lines
  
  Issue #11053: Fix IDLE "Syntax Error" windows to behave as in 2.x,
  preventing a confusing hung appearance on OS X with the windows
  obscured.  (with release manager approval for 3.2rc2)
................
  r88235 | ned.deily | 2011-01-29 19:56:28 +0100 (sam., 29 janv. 2011) | 5 lines
  
  Issue #11054: Allow Mac OS X installer builds to again work on 10.5 with
  the system-provided Python.  Also, properly guard a new Python 3 only
  installer build step so that build-installer.py can stay compatible
  with the 2.7 version.  (with release manager approval for 3.2rc2)
................
  r88236 | ned.deily | 2011-01-29 20:10:26 +0100 (sam., 29 janv. 2011) | 3 lines
  
  Issue 11052: Correct IDLE menu accelerators on Mac OS X for Save
  commands.  (with release manager approval for 3.2rc2)
................
  r88239 | alexander.belopolsky | 2011-01-29 20:49:40 +0100 (sam., 29 janv. 2011) | 1 line
  
  Issue #10939: Make Internaldate2tuple test more robust.
................
  r88240 | eric.araujo | 2011-01-29 21:32:11 +0100 (sam., 29 janv. 2011) | 6 lines
  
  Protect logging call against None argument (fixes #11045).
  
  Initial patch by Kelsey Hightower.  Approved by Raymond.  A test was
  non-trivial to write without calling the private function directly, so
  we moved that for later.
................
  r88244 | raymond.hettinger | 2011-01-30 01:39:00 +0100 (dim., 30 janv. 2011) | 2 lines
  
  Typos.
................
  r88245 | raymond.hettinger | 2011-01-30 01:55:47 +0100 (dim., 30 janv. 2011) | 4 lines
  
  Add section for http.client.
  Link to OS X build instructions.
  Add back issue references for datetime.
................
  r88246 | raymond.hettinger | 2011-01-30 02:10:07 +0100 (dim., 30 janv. 2011) | 2 lines
  
  Markup nits.
................
  r88247 | nick.coghlan | 2011-01-30 02:24:08 +0100 (dim., 30 janv. 2011) | 1 line
  
  Issue #10845: Improve compatibility between multiprocessing on Windows and package, zipfile and directory execution (Reviewed by Antoine Pitrou and approved by Georg Brandl)
................
  r88251 | raymond.hettinger | 2011-01-30 06:37:16 +0100 (dim., 30 janv. 2011) | 2 lines
  
  List known build/install problems for OS X.
................
  r88252 | r.david.murray | 2011-01-30 07:21:28 +0100 (dim., 30 janv. 2011) | 16 lines
  
  #9124: mailbox now accepts binary input and uses binary internally
  
  Although this patch contains API changes and is rather weighty for an
  RC phase, the mailbox module was essentially unusable without the patch
  since it would produce UnicodeErrors when handling non-ascii input
  at arbitrary and somewhat mysterious places, and any non-trivial amount
  of email processing will encounter messages with non-ascii bytes.
  The release manager approved the patch application.
  
  The changes allow binary input, and reject non-ASCII string input early
  with a useful message instead of failing mysteriously later.  Binary
  is used internally for reading and writing the mailbox files.  StringIO
  and Text file input are deprecated.
  
  Initial patch by Victor Stinner, validated and expanded by R. David Murray.
................
  r88256 | raymond.hettinger | 2011-01-30 08:56:03 +0100 (dim., 30 janv. 2011) | 2 lines
  
  Add entry for the mailbox fixups.
................
  r88258 | georg.brandl | 2011-01-30 09:16:07 +0100 (dim., 30 janv. 2011) | 3 lines
  
  #11069: fix the IDLE Stack Viewer, by not using "list" as a variable name.
  Original patch by Brian Curtin, reviewed by me.
................
  r88259 | raymond.hettinger | 2011-01-30 09:20:37 +0100 (dim., 30 janv. 2011) | 2 lines
  
  Clarify the status of get_string() and recommend using the binary API.
................
  r88261 | georg.brandl | 2011-01-30 09:37:19 +0100 (dim., 30 janv. 2011) | 4 lines
  
  #10961: fix exception handling in new pydoc server code.
  Patch by Ron Adam, reviewed by Eric Araujo.
................
  r88263 | georg.brandl | 2011-01-30 13:19:35 +0100 (dim., 30 janv. 2011) | 1 line
  
  #10680: fix mutually exclusive arguments in argument groups.
................
  r88264 | georg.brandl | 2011-01-30 15:00:32 +0100 (dim., 30 janv. 2011) | 1 line
  
  Update pydoc topics.
................
  r88265 | georg.brandl | 2011-01-30 15:02:36 +0100 (dim., 30 janv. 2011) | 1 line
  
  Update suspicious ignore file.
................
  r88266 | georg.brandl | 2011-01-30 15:03:33 +0100 (dim., 30 janv. 2011) | 1 line
  
  Bump version.
................
  r88271 | eli.bendersky | 2011-01-31 05:05:52 +0100 (lun., 31 janv. 2011) | 3 lines
  
  Fix some grammar and typos
................
  r88272 | eli.bendersky | 2011-01-31 05:10:23 +0100 (lun., 31 janv. 2011) | 3 lines
  
  Fix PEP-8 violation in argparse usage example (similar examples in argparse.rst do follow PEP-8)
................
  r88273 | eli.bendersky | 2011-01-31 05:21:40 +0100 (lun., 31 janv. 2011) | 3 lines
  
  Mention new parameter and attributes of the difflib.SequenceMatcher class added in 3.2 (issue 2986)
................
  r88274 | raymond.hettinger | 2011-01-31 07:14:48 +0100 (lun., 31 janv. 2011) | 4 lines
  
  Fix minor grammar nits.
  Revert r88272 -- the examples are more readable with spacing.
  Add todos for difflib and logging.
................
  r88275 | raymond.hettinger | 2011-01-31 07:34:47 +0100 (lun., 31 janv. 2011) | 2 lines
  
  Recommend use of the tracker during the RC phase or just before a beta.
................
  r88276 | georg.brandl | 2011-01-31 11:39:57 +0100 (lun., 31 janv. 2011) | 1 line
  
  Post-release updates.
................
  r88280 | alexander.belopolsky | 2011-01-31 20:27:55 +0100 (lun., 31 janv. 2011) | 3 lines
  
  Issue #11081: Fixed struct.__all__. Reviewed by Georg Brandl.
................
  r88281 | brian.curtin | 2011-01-31 20:35:02 +0100 (lun., 31 janv. 2011) | 2 lines
  
  #11083 typo: RuntimeException -> RuntimeError
................
  r88284 | antoine.pitrou | 2011-01-31 22:08:57 +0100 (lun., 31 janv. 2011) | 4 lines
  
  Issue #8275: Fix passing of callback arguments with ctypes under Win64.
  Patch by Stan Mihai. Ok'ed by Georg.
................
  r88299 | eric.smith | 2011-02-01 22:31:22 +0100 (mar., 01 févr. 2011) | 1 line
  
  Wording fix.
................
  r88301 | antoine.pitrou | 2011-02-02 00:43:46 +0100 (mer., 02 févr. 2011) | 3 lines
  
  Add a svn:ignore for PC/python3dll.obj
................
  r88302 | raymond.hettinger | 2011-02-02 00:54:43 +0100 (mer., 02 févr. 2011) | 8 lines
  
  Get command-line doctest of Lib/decimal.py to work again.
  
  If tested as '__main__' instead 'decimal', the tracebacks would
  abbreviate 'decimal.Inexact' as 'Inexact', breaking the doctests.
  
  (Reviewed by Antoine.)
................
  r88322 | raymond.hettinger | 2011-02-02 22:12:39 +0100 (mer., 02 févr. 2011) | 1 line
  
  Punctuation typo.
................
  r88329 | georg.brandl | 2011-02-03 08:08:25 +0100 (jeu., 03 févr. 2011) | 1 line
  
  Punctuation typos.
................
  r88330 | georg.brandl | 2011-02-03 08:46:41 +0100 (jeu., 03 févr. 2011) | 1 line
  
  Remove lots of spaces within exception message.
................
  r88331 | brett.cannon | 2011-02-03 23:01:54 +0100 (jeu., 03 févr. 2011) | 1 line
  
  Add a HOWTO on how to port from Python 2 to Python 3.
................
  r88332 | brett.cannon | 2011-02-03 23:14:58 +0100 (jeu., 03 févr. 2011) | 1 line
  
  use 3-space indents.
................
  r88333 | martin.v.loewis | 2011-02-04 20:09:02 +0100 (ven., 04 févr. 2011) | 1 line
  
  Issue #11118: Fix bogus export of None in python3.dll.
................
  r88334 | antoine.pitrou | 2011-02-04 21:11:11 +0100 (ven., 04 févr. 2011) | 3 lines
  
  Mention that seek and tell over a TextIOWrapper can be very slow.
................
  r88337 | brett.cannon | 2011-02-04 21:24:02 +0100 (ven., 04 févr. 2011) | 5 lines
  
  There was a possibility that the initialization of _sqlite, when it failed,
  would lead to a decref of a NULL.
  
  Fixes issue #11110.
................
  r88340 | antoine.pitrou | 2011-02-05 11:43:57 +0100 (sam., 05 févr. 2011) | 3 lines
  
  Update info in the GUI FAQ
................
  r88341 | antoine.pitrou | 2011-02-05 11:57:17 +0100 (sam., 05 févr. 2011) | 3 lines
  
  Mention Cython and remove obsolete alternatives
................
  r88342 | antoine.pitrou | 2011-02-05 12:04:01 +0100 (sam., 05 févr. 2011) | 3 lines
  
  Update test of "why is Python installed" FAQ.
................
  r88343 | antoine.pitrou | 2011-02-05 12:18:34 +0100 (sam., 05 févr. 2011) | 3 lines
  
  Mention concurrent.futures and update answers about the GIL.
................
  r88344 | antoine.pitrou | 2011-02-05 12:24:15 +0100 (sam., 05 févr. 2011) | 3 lines
  
  Mention asyncore and Twisted in the library FAQ.
................
  r88345 | antoine.pitrou | 2011-02-05 12:40:05 +0100 (sam., 05 févr. 2011) | 3 lines
  
  Mention -b and -bb
................
  r88346 | antoine.pitrou | 2011-02-05 12:53:39 +0100 (sam., 05 févr. 2011) | 3 lines
  
  Fix entries pertaining to file I/O
................
  r88347 | antoine.pitrou | 2011-02-05 13:01:07 +0100 (sam., 05 févr. 2011) | 4 lines
  
  Soften the wording about tracebacks. Reference cycles *don't*
  prevent garbage collection! (fortunately)
................
  r88348 | antoine.pitrou | 2011-02-05 13:13:38 +0100 (sam., 05 févr. 2011) | 3 lines
  
  Everybody hates this one :) (bytes indexing)
................
  r88349 | eric.araujo | 2011-02-05 17:03:12 +0100 (sam., 05 févr. 2011) | 2 lines
  
  Use an internal reference instead of hard-coded URI.
................
  r88350 | martin.v.loewis | 2011-02-05 21:26:52 +0100 (sam., 05 févr. 2011) | 2 lines
  
  Issue #11121: Fix building with --enable-shared.
................
  r88351 | martin.v.loewis | 2011-02-05 21:35:29 +0100 (sam., 05 févr. 2011) | 3 lines
  
  Issue #11067: Add PyType_GetFlags, to support PyUnicode_Check 
  in the limited ABI
................
  r88352 | gregory.p.smith | 2011-02-05 22:47:25 +0100 (sam., 05 févr. 2011) | 3 lines
  
  issue7678 - Properly document how to replace a shell pipeline so that SIGPIPE
  happens when the end exits before the beginning.
................
  r88355 | brett.cannon | 2011-02-05 23:05:05 +0100 (sam., 05 févr. 2011) | 7 lines
  
  Re-arrange and clarify some __future__ import statements.
  
  The absolute_import statement got moved to a new Python 2.5 and Newer section
  as it was available since then. The division statement got moved to Common
  Gotchas since it has been around for so long that any modern Python program can
  use it.
................
  r88356 | brett.cannon | 2011-02-05 23:16:40 +0100 (sam., 05 févr. 2011) | 1 line
  
  Soften wording on doctest.
................
  r88357 | brett.cannon | 2011-02-05 23:22:47 +0100 (sam., 05 févr. 2011) | 1 line
  
  Mention that people going the source compatibility route should run 2to3 to find pain points.
................
  r88358 | raymond.hettinger | 2011-02-06 07:11:29 +0100 (dim., 06 févr. 2011) | 2 lines
  
  Small markup and wording tweaks for the sorting-howto.
................
  r88359 | raymond.hettinger | 2011-02-06 21:08:57 +0100 (dim., 06 févr. 2011) | 2 lines
  
  Issue #11071: Various improvements to whatsnew.
................
  r88360 | raymond.hettinger | 2011-02-06 22:00:38 +0100 (dim., 06 févr. 2011) | 2 lines
  
  Fix awkwardly rendered sentence.
................
  r88361 | raymond.hettinger | 2011-02-07 05:00:24 +0100 (lun., 07 févr. 2011) | 2 lines
  
  Typo.  Doh!
................
  r88362 | eli.bendersky | 2011-02-07 05:19:57 +0100 (lun., 07 févr. 2011) | 6 lines
  
  Fix some typos and grammar
  
  [commit during RC with Brett's approval]
................
  r88363 | eli.bendersky | 2011-02-07 05:44:19 +0100 (lun., 07 févr. 2011) | 3 lines
  
  Fix some typos and grammar
................
  r88364 | georg.brandl | 2011-02-07 13:10:46 +0100 (lun., 07 févr. 2011) | 1 line
  
  #11138: fix order of fill and align specifiers.
................
  r88365 | georg.brandl | 2011-02-07 13:13:58 +0100 (lun., 07 févr. 2011) | 1 line
  
  #8691: document that right alignment is default for numbers.
................
  r88366 | georg.brandl | 2011-02-07 13:36:54 +0100 (lun., 07 févr. 2011) | 2 lines
  
  #11132: pass optimize parameter to recursive call in compileall.compile_dir().  Reviewed by Eric A.
................
  r88367 | raymond.hettinger | 2011-02-07 13:51:05 +0100 (lun., 07 févr. 2011) | 2 lines
  
  Add link to  table for Tcl/Tk issues on the Mac.
................
  r88368 | nick.coghlan | 2011-02-07 14:43:07 +0100 (lun., 07 févr. 2011) | 2 lines
  
  Issue 10971: Make test_zipimport_support once again compatible with refleak hunting (reviewed by Georg Brandl)
................
  r88369 | georg.brandl | 2011-02-07 16:30:45 +0100 (lun., 07 févr. 2011) | 1 line
  
  Consistent heading spacing, and fix two typos.
................
  r88370 | georg.brandl | 2011-02-07 16:44:27 +0100 (lun., 07 févr. 2011) | 1 line
  
  Spelling fixes.
................
  r88371 | antoine.pitrou | 2011-02-07 16:58:11 +0100 (lun., 07 févr. 2011) | 3 lines
  
  Clarify that IMAP4() implicitly calls open(), and that logout() implicitly calls shutdown().
................
  r88374 | ned.deily | 2011-02-07 17:44:19 +0100 (lun., 07 févr. 2011) | 5 lines
  
  Issue #11079: The /Applications/Python x.x folder created by the Mac
  OS X installers no longer includes an Extras directory.  The Tools
  directory is now installed in the framework under share/doc.
................
  r88375 | ned.deily | 2011-02-07 17:48:28 +0100 (lun., 07 févr. 2011) | 5 lines
  
  - Issue #11079: The /Applications/Python x.x folder created by the Mac
  OS X installers now includes a link to the installed documentation
  plus another in the framework share/doc directory.
................
  r88377 | antoine.pitrou | 2011-02-08 00:10:33 +0100 (mar., 08 févr. 2011) | 4 lines
  
  Issue #11141: Fix the shelve documentation to use a list, not a range object.
  Patch by SilentGhost.
................
  r88381 | raymond.hettinger | 2011-02-09 19:16:32 +0100 (mer., 09 févr. 2011) | 2 lines
  
  Typo.
................
  r88382 | terry.reedy | 2011-02-09 20:21:00 +0100 (mer., 09 févr. 2011) | 2 lines
  
  Add 'pysqlite' before version 2.6.0
................
  r88383 | brett.cannon | 2011-02-09 23:55:13 +0100 (mer., 09 févr. 2011) | 1 line
  
  Tweak wording about equality comparison.
................
  r88384 | raymond.hettinger | 2011-02-10 09:09:36 +0100 (jeu., 10 févr. 2011) | 1 line
  
  Add missing source links.
................
  r88385 | raymond.hettinger | 2011-02-10 10:20:26 +0100 (jeu., 10 févr. 2011) | 2 lines
  
  Add an entry for logging.
................
  r88386 | raymond.hettinger | 2011-02-10 10:43:04 +0100 (jeu., 10 févr. 2011) | 2 lines
  
  Fix nits.
................
  r88387 | giampaolo.rodola | 2011-02-10 19:42:36 +0100 (jeu., 10 févr. 2011) | 1 line
  
  get rid of asyncore.dispatcher's debug attribute, which is no longer used (assuming it ever was).
................
  r88388 | raymond.hettinger | 2011-02-11 01:03:03 +0100 (ven., 11 févr. 2011) | 2 lines
  
  Insert missing section heading (noticed by Victor Stinner).
................
  r88389 | raymond.hettinger | 2011-02-11 01:08:38 +0100 (ven., 11 févr. 2011) | 2 lines
  
  Missing paren.
................
  r88394 | senthil.kumaran | 2011-02-11 12:25:47 +0100 (ven., 11 févr. 2011) | 3 lines
  
  Fixed issue11082 - Reject str for POST data with a TypeError. Document the need to explicitly encode to bytes when using urlencode.
................
  r88395 | giampaolo.rodola | 2011-02-11 14:04:18 +0100 (ven., 11 févr. 2011) | 4 lines
  
  asyncore: introduce a new 'closed' attribute to make sure that dispatcher gets closed only once.
  In different occasions close() might be called more than once, causing problems with already disconnected sockets/dispatchers.
................
  r88396 | giampaolo.rodola | 2011-02-11 15:01:46 +0100 (ven., 11 févr. 2011) | 1 line
  
  reverting r88395 and r88387 as per http://mail.python.org/pipermail/python-dev/2011-February/108005.html
................
  r88399 | martin.v.loewis | 2011-02-11 21:44:40 +0100 (ven., 11 févr. 2011) | 2 lines
  
  Add uuid for 3.2rc3.
................
  r88400 | martin.v.loewis | 2011-02-11 21:47:49 +0100 (ven., 11 févr. 2011) | 3 lines
  
  Issue #11135: Remove redundant doc field from PyType_Spec.
  Reviewed by Georg Brandl.
................
  r88401 | martin.v.loewis | 2011-02-11 21:50:24 +0100 (ven., 11 févr. 2011) | 3 lines
  
  Issue #11134: Add missing fields to typeslots.h.
  Reviewed by Georg Brandl.
................
  r88402 | r.david.murray | 2011-02-11 23:37:16 +0100 (ven., 11 févr. 2011) | 2 lines
  
  Fix argument name typo in compileall docs.
................
  r88403 | r.david.murray | 2011-02-11 23:47:17 +0100 (ven., 11 févr. 2011) | 3 lines
  
  #11116: roll back on error during add so mailbox isn't left corrupted.
................
  r88407 | r.david.murray | 2011-02-12 01:03:31 +0100 (sam., 12 févr. 2011) | 2 lines
  
  Fix #11116 fix on Windows (close file before removing in MH code)
................
  r88411 | georg.brandl | 2011-02-13 10:54:12 +0100 (dim., 13 févr. 2011) | 1 line
  
  Update pydoc topics.
................
  r88412 | georg.brandl | 2011-02-13 10:59:39 +0100 (dim., 13 févr. 2011) | 1 line
  
  Fix markup error and update suspicious ignores.
................
  r88413 | georg.brandl | 2011-02-13 11:00:57 +0100 (dim., 13 févr. 2011) | 1 line
  
  Bump for 3.2rc3.
................
  r88420 | georg.brandl | 2011-02-14 07:35:00 +0100 (lun., 14 févr. 2011) | 1 line
  
  Post-release updates.
................
  r88421 | raymond.hettinger | 2011-02-14 19:18:49 +0100 (lun., 14 févr. 2011) | 1 line
  
  Fix accumulate() example. (Reported by David Murray.)
................
  r88423 | georg.brandl | 2011-02-15 13:41:17 +0100 (mar., 15 févr. 2011) | 1 line
  
  Apply logging SocketHandler doc update by Vinay.
................
  r88424 | georg.brandl | 2011-02-15 13:44:43 +0100 (mar., 15 févr. 2011) | 1 line
  
  Remove editing slip.
................
  r88426 | georg.brandl | 2011-02-15 16:44:51 +0100 (mar., 15 févr. 2011) | 1 line
  
  #941346: Fix broken shared library build on AIX. Patch by Sebastien Sable, review by Antoine Pitrou.
................
  r88430 | georg.brandl | 2011-02-15 20:48:59 +0100 (mar., 15 févr. 2011) | 1 line
  
  #730467: Another small AIX fix.
................
  r88431 | raymond.hettinger | 2011-02-17 20:05:53 +0100 (jeu., 17 févr. 2011) | 2 lines
  
  Fix an import and add a citation.
................
  r88432 | raymond.hettinger | 2011-02-17 20:19:44 +0100 (jeu., 17 févr. 2011) | 2 lines
  
  Fix-up logging.dictConfig() example.
................
  r88434 | raymond.hettinger | 2011-02-18 01:53:55 +0100 (ven., 18 févr. 2011) | 1 line
  
  Doc fixups.
................
  r88435 | brett.cannon | 2011-02-18 02:34:28 +0100 (ven., 18 févr. 2011) | 5 lines
  
  Update the porting HOWTO to be a little less harsh on using 2to3.
  
  Patch reviewed by Raymond Hettinger, permission from Georg Brandl to commit
  during an RC.
................
  r88438 | georg.brandl | 2011-02-19 09:44:47 +0100 (sam., 19 févr. 2011) | 1 line
  
  #10709: add back an updated AIX-NOTES (as README.AIX).
................
  r88439 | georg.brandl | 2011-02-19 09:47:14 +0100 (sam., 19 févr. 2011) | 1 line
  
  #11222: fix non-framework shared library build on Mac, patch by Ned Deily.
................
  r88440 | georg.brandl | 2011-02-19 09:58:23 +0100 (sam., 19 févr. 2011) | 1 line
  
  #11184: Fix large file support on AIX.
................
  r88441 | eric.araujo | 2011-02-19 19:06:50 +0100 (sam., 19 févr. 2011) | 2 lines
  
  Some more grammar fixes/typos for what’s new (approved by Raymond; #11071)
................
  r88442 | eric.araujo | 2011-02-19 19:46:02 +0100 (sam., 19 févr. 2011) | 2 lines
  
  Fix two typos in what’s new (#11234).
................
  r88443 | georg.brandl | 2011-02-19 22:47:02 +0100 (sam., 19 févr. 2011) | 1 line
  
  #11249: in PyType_FromSpec, copy tp_doc slot since it usually will point to a static string literal which should not be deallocated together with the type.
................
  r88444 | georg.brandl | 2011-02-20 11:22:41 +0100 (dim., 20 févr. 2011) | 1 line
  
  Topic and suspicious update.
................
  r88445 | georg.brandl | 2011-02-20 11:29:04 +0100 (dim., 20 févr. 2011) | 1 line
  
  Version bump to 3.2 final.
................
  r88447 | georg.brandl | 2011-02-20 11:33:21 +0100 (dim., 20 févr. 2011) | 2 lines
  
  Bump to 3.3a0.
................
  r88448 | georg.brandl | 2011-02-20 11:37:07 +0100 (dim., 20 févr. 2011) | 1 line
  
  Bump trunk to 3.3 alpha 0.
................
  r88449 | georg.brandl | 2011-02-20 11:41:31 +0100 (dim., 20 févr. 2011) | 1 line
  
  More automated version replacement.
................
  r88451 | georg.brandl | 2011-02-20 12:18:09 +0100 (dim., 20 févr. 2011) | 1 line
  
  Remove unittest methods scheduled for removal in 3.3 -- makes the unittest test suite pass again.
................
  r88456 | martin.v.loewis | 2011-02-21 17:24:00 +0100 (lun., 21 févr. 2011) | 2 lines
  
  - Check for NULL result in PyType_FromSpec.
................
  r88459 | raymond.hettinger | 2011-02-21 18:54:36 +0100 (lun., 21 févr. 2011) | 1 line
  
  Issue 10160: Both single-arg and multi-arg calls have been sped-up.
................
  r88460 | antoine.pitrou | 2011-02-21 19:03:13 +0100 (lun., 21 févr. 2011) | 4 lines
  
  Issue #10276: Fix the results of zlib.crc32() and zlib.adler32() on buffers
  larger than 4GB.  Patch by Nadeem Vawda.
................
  r88463 | georg.brandl | 2011-02-21 19:37:01 +0100 (lun., 21 févr. 2011) | 1 line
  
  3.2 is stable now.
................
  r88464 | antoine.pitrou | 2011-02-21 20:05:08 +0100 (lun., 21 févr. 2011) | 3 lines
  
  Fix issues on 32-bit systems introduced by r88460
................
  r88465 | brett.cannon | 2011-02-21 20:24:10 +0100 (lun., 21 févr. 2011) | 2 lines
  
  Ignore Vim .swp files.
................
  r88466 | antoine.pitrou | 2011-02-21 20:28:40 +0100 (lun., 21 févr. 2011) | 3 lines
  
  Fix compile error under MSVC introduced by r88460.
................
  r88467 | brett.cannon | 2011-02-21 20:29:56 +0100 (lun., 21 févr. 2011) | 11 lines
  
  Issue #10990: Prevent tests from clobbering a set trace function.
  
  Many tests simply didn't care if they unset a pre-existing trace function. This
  made test coverage impossible. This patch fixes various tests to put back any
  pre-existing trace function. It also introduces test.support.no_tracing as a
  decorator which will temporarily unset the trace function for tests which
  simply fail otherwise.
  
  Thanks to Kristian Vlaardingerbroek for helping to find the cause of various
  trace function unsets.
................
  r88470 | raymond.hettinger | 2011-02-21 20:42:11 +0100 (lun., 21 févr. 2011) | 4 lines
  
  Issue #11089: Fix performance issue limiting the use of ConfigParser()
  with large config files.
................
  r88474 | raymond.hettinger | 2011-02-21 20:58:37 +0100 (lun., 21 févr. 2011) | 1 line
  
  Issue 11263: Fix link to source code.
................
  r88475 | ned.deily | 2011-02-21 21:44:27 +0100 (lun., 21 févr. 2011) | 3 lines
  
  Issue #11268: Prevent Mac OS X Installer failure if Documentation
  package had previously been installed.
................
  r88476 | victor.stinner | 2011-02-21 21:51:28 +0100 (lun., 21 févr. 2011) | 7 lines
  
  Remove bootstrap code of PyUnicode_AsEncodedString()
  
  Issue #11187: Remove bootstrap code (use ASCII) of
  PyUnicode_AsEncodedString(), it was replaced by a better fallback (use
  the locale encoding) in PyUnicode_EncodeFSDefault().
  
  Prepare also empty sections in NEWS.
................
  r88478 | victor.stinner | 2011-02-21 21:58:02 +0100 (lun., 21 févr. 2011) | 4 lines
  
  compileall uses repr() to format filenames/paths
  
  Issue #11169: compileall module uses repr() to format filenames and paths to
  escape surrogate characters and show spaces.
................
  r88480 | victor.stinner | 2011-02-21 22:05:50 +0100 (lun., 21 févr. 2011) | 6 lines
  
  Remove filename variable from ceval.c
  
  Issue #11168: Remove filename debug variable from PyEval_EvalFrameEx().
  It encoded the Unicode filename to UTF-8, but the encoding fails on
  undecodable filename (on surrogate characters) which raises an unexpected
  UnicodeEncodeError on recursion limit.
................
  r88481 | victor.stinner | 2011-02-21 22:13:44 +0100 (lun., 21 févr. 2011) | 4 lines
  
  Fix PyUnicode_FromFormatV("%c") for non-BMP char
  
  Issue #10830: Fix PyUnicode_FromFormatV("%c") for non-BMP characters on
  narrow build.
................
  r88484 | antoine.pitrou | 2011-02-21 22:55:48 +0100 (lun., 21 févr. 2011) | 4 lines
  
  Issue #10826: Prevent sporadic failure in test_subprocess on Solaris due
  to open door files.
................
  r88486 | antoine.pitrou | 2011-02-22 00:41:12 +0100 (mar., 22 févr. 2011) | 5 lines
  
  Issue #4681: Allow mmap() to work on file sizes and offsets larger than
  4GB, even on 32-bit builds.  Initial patch by Ross Lagerwall, adapted for
  32-bit Windows.
................
  r88490 | raymond.hettinger | 2011-02-22 01:41:50 +0100 (mar., 22 févr. 2011) | 6 lines
  
  Issue #11085: Moved collections abstract base classes into a separate module
  called collections.abc, following the pattern used by importlib.abc.  For
  backwards compatibility, the names continue to also be imported into the
  collections module.
................
  r88491 | raymond.hettinger | 2011-02-22 02:48:33 +0100 (mar., 22 févr. 2011) | 1 line
  
  Have the test filename match the module filename.
................
  r88492 | raymond.hettinger | 2011-02-22 02:55:36 +0100 (mar., 22 févr. 2011) | 1 line
  
  Factor-out common code for helper classes.
................
  r88493 | brett.cannon | 2011-02-22 03:42:41 +0100 (mar., 22 févr. 2011) | 1 line
  
  Ignore __pycache__ in Lib/collections.
................
  r88494 | brett.cannon | 2011-02-22 04:04:06 +0100 (mar., 22 févr. 2011) | 10 lines
  
  Issue #10992: make tests pass when run under coverage.
  
  Various tests fail when run under coverage. A primary culprit is refcount tests
  which fail as the counts are thrown off by the coverage code. A new decorator
  -- test.support.refcount_test -- is used to decorate tests which test refcounts
  and to skip them when running under coverage. Other tests simply fail because
  of changes in the system (e.g., __local__ suddenly appearing).
  
  Thanks to Kristian Vlaardingerbroek for helping to diagnose the test failures.
................
  r88496 | brett.cannon | 2011-02-22 04:14:12 +0100 (mar., 22 févr. 2011) | 4 lines
  
  Issue #10512: close the log file in cgi when running tests.
  
  Thanks to Nadeem Vawda for the find and an initial fix.
................
  r88498 | brett.cannon | 2011-02-22 04:25:12 +0100 (mar., 22 févr. 2011) | 8 lines
  
  Issue #11074: Make 'tokenize' so it can be reloaded.
  
  The module stored away the 'open' object as found in the global namespace
  (which fell through to the built-in namespace) since it defined its own 'open'.
  Problem is that if you reloaded the module it then grabbed the 'open' defined
  in the previous load, leading to code that infinite recursed. Switched to
  simply call builtins.open directly.
................
  r88500 | sean.reifschneider | 2011-02-22 11:55:44 +0100 (mar., 22 févr. 2011) | 2 lines
  
  Issue #10924: Adding salt and Modular Crypt Format to crypt library.
................
  r88501 | giampaolo.rodola | 2011-02-22 16:56:20 +0100 (mar., 22 févr. 2011) | 1 line
  
  smtlib.py PEP8 normalization via pep8.py script.
................
  r88503 | brett.cannon | 2011-02-22 20:12:43 +0100 (mar., 22 févr. 2011) | 1 line
  
  Add lib2to3.__main__ to make it easier for debugging purposes to run 2to3.
................
  r88505 | giampaolo.rodola | 2011-02-22 20:24:33 +0100 (mar., 22 févr. 2011) | 1 line
  
  In FTP.close() method, make sure to also close the socket object, not only the file.
................
  r88506 | brett.cannon | 2011-02-22 21:15:44 +0100 (mar., 22 févr. 2011) | 2 lines
  
  Issue #8914: fix various warnings from the Clang static analyzer v254.
................
  r88507 | brett.cannon | 2011-02-22 21:17:14 +0100 (mar., 22 févr. 2011) | 1 line
  
  Fix test.test_crypt.test_methods() to pass on OS X.
................
  r88511 | antoine.pitrou | 2011-02-22 22:42:56 +0100 (mar., 22 févr. 2011) | 4 lines
  
  Issue #11277: finally fix Snow Leopard crash following r88460.
  (probably an OS-related issue with mmap)
................
  r88512 | brett.cannon | 2011-02-22 22:48:06 +0100 (mar., 22 févr. 2011) | 3 lines
  
  Make Lib/crypt.py meet PEP 8 standards. This also led to a tweak in the new API
  by making methods() into a module attribute as it is statically calculated.
................
  r88513 | brett.cannon | 2011-02-22 22:55:51 +0100 (mar., 22 févr. 2011) | 1 line
  
  A crypt algorithm may not be available by returning None.
................
  r88515 | victor.stinner | 2011-02-23 00:12:28 +0100 (mer., 23 févr. 2011) | 4 lines
  
  Issue #3080: Mark PyWin_FindRegisteredModule() as private
  
  This function was not declared in Python public API (in any .h file) and not
  documented. Mark it as private to prepare a change of its API.
................
  r88516 | victor.stinner | 2011-02-23 00:16:19 +0100 (mer., 23 févr. 2011) | 3 lines
  
  Issue #3080: Remove unused argument of _PyImport_GetDynLoadFunc()
  
  The first argument, fqname, was not used.
................
  r88517 | victor.stinner | 2011-02-23 00:38:34 +0100 (mer., 23 févr. 2011) | 1 line
  
  Issue #3080: document encoding used by import functions
................
  r88519 | victor.stinner | 2011-02-23 01:02:00 +0100 (mer., 23 févr. 2011) | 5 lines
  
  Issue #3080: Mark _PyImport_FindBuiltin() argument as constant
  
  And as a consequence, mark also name argument of
  _PyImport_FindExtensionUnicode() constant too. But I plan to change this
  argument type to PyObject* later.
................
  r88520 | victor.stinner | 2011-02-23 01:21:43 +0100 (mer., 23 févr. 2011) | 4 lines
  
  Issue #3080: Add PyModule_GetNameObject()
  
  repr(module) uses %R to format module name and filenames, instead of '%s' and
  '%U', so surrogates from undecodable bytes in a filename (PEP 383) are escaped.
................
  r88521 | raymond.hettinger | 2011-02-23 01:46:28 +0100 (mer., 23 févr. 2011) | 1 line
  
  Fix imports from collections.abc
................
  r88523 | georg.brandl | 2011-02-23 08:30:12 +0100 (mer., 23 févr. 2011) | 1 line
  
  Add new subdirectory to LIBSUBDIRS.
................
  r88524 | georg.brandl | 2011-02-23 08:31:24 +0100 (mer., 23 févr. 2011) | 1 line
  
  Indent "versionadded" properly.
................
  r88525 | raymond.hettinger | 2011-02-23 08:56:53 +0100 (mer., 23 févr. 2011) | 1 line
  
  Add tests for the _ChainMap helper class.
................
  r88527 | victor.stinner | 2011-02-23 12:29:28 +0100 (mer., 23 févr. 2011) | 1 line
  
  dynload_dl.c: replace tabs by spaces
................
  r88528 | lars.gustaebel | 2011-02-23 12:42:22 +0100 (mer., 23 févr. 2011) | 16 lines
  
  Issue #11224: Improved sparse file read support (r85916) introduced a
  regression in _FileInFile which is used in file-like objects returned
  by TarFile.extractfile(). The inefficient design of the
  _FileInFile.read() method causes various dramatic side-effects and
  errors:
  
    - The data segment of a file member is read completely into memory
      every(!) time a small block is accessed. This is not only slow
      but may cause unexpected MemoryErrors with very large files.
    - Reading members from compressed tar archives is even slower
      because of the excessive backwards seeking which is done when the
      same data segment is read over and over again.
    - As a backwards seek on a TarFile opened in stream mode is not
      possible, using extractfile() fails with a StreamError.
................
  r88530 | victor.stinner | 2011-02-23 13:07:37 +0100 (mer., 23 févr. 2011) | 4 lines
  
  Issue #11272: Fix input() and sys.stdin for Windows newline
  
  On Windows, input() strips '\r' (and not only '\n'), and sys.stdin uses
  universal newline (replace '\r\n' by '\n').
................
  r88533 | victor.stinner | 2011-02-23 15:14:48 +0100 (mer., 23 févr. 2011) | 3 lines
  
  Issue #3080: Fix test_reprlib on Windows
  
  Fix the test for last module changes (r88520).
................
  r88534 | brett.cannon | 2011-02-23 19:48:52 +0100 (mer., 23 févr. 2011) | 1 line
  
  Revert r88503 as Benjamin's request.
................
  r88538 | raymond.hettinger | 2011-02-24 01:08:13 +0100 (jeu., 24 févr. 2011) | 1 line
  
  Issue #11304: Input/output tutorial - PI is rounded not truncated.
................
  r88539 | benjamin.peterson | 2011-02-24 02:41:46 +0100 (jeu., 24 févr. 2011) | 9 lines
  
  Merged revisions 88535 via svnmerge from 
  svn+ssh://pythondev@svn.python.org/sandbox/trunk/2to3/lib2to3
  
  ........
    r88535 | brett.cannon | 2011-02-23 13:46:46 -0600 (Wed, 23 Feb 2011) | 1 line
    
    Add lib2to3.__main__ for easy testing from the console.
  ........
................
  r88540 | benjamin.peterson | 2011-02-24 03:46:00 +0100 (jeu., 24 févr. 2011) | 1 line
  
  this seems to be pointlessly nested
................
  r88541 | benjamin.peterson | 2011-02-24 03:53:05 +0100 (jeu., 24 févr. 2011) | 1 line
  
  rewrite
................
  r88545 | eric.araujo | 2011-02-24 19:03:10 +0100 (jeu., 24 févr. 2011) | 2 lines
  
  Allow usage of SomeABC.register as a class decorator.  Patch by Edoardo Spadolini (#10868).
................
  r88546 | alexander.belopolsky | 2011-02-24 20:40:09 +0100 (jeu., 24 févr. 2011) | 3 lines
  
  Issue #11286: Fixed unpickling of empty 2.x strings.
................
  r88550 | antoine.pitrou | 2011-02-24 21:50:49 +0100 (jeu., 24 févr. 2011) | 4 lines
  
  Issue #11286: Raise a ValueError from calling PyMemoryView_FromBuffer with
  a buffer struct having a NULL data pointer.
................
  r88552 | giampaolo.rodola | 2011-02-24 21:59:48 +0100 (jeu., 24 févr. 2011) | 1 line
  
  Adds Python 3.3 what's new document.
................
  r88553 | alexander.belopolsky | 2011-02-25 02:14:14 +0100 (ven., 25 févr. 2011) | 5 lines
  
  Issue #11311: Short-circuit default encoding case in
  PyUnicode_Decode() and PyUnicode_AsEncodedString().  Thanks Ezio
  Melotti for the tests and the review.
................
  r88554 | eli.bendersky | 2011-02-25 06:47:53 +0100 (ven., 25 févr. 2011) | 3 lines
  
  Issue #10516: adding list.clear() and list.copy() methods
................
  r88558 | eli.bendersky | 2011-02-25 11:14:17 +0100 (ven., 25 févr. 2011) | 3 lines
  
  Removed fcmp and FUZZ from test.support, following the discussion on python-dev:
  http://mail.python.org/pipermail/python-dev/2011-January/107735.html
................
  r88567 | georg.brandl | 2011-02-25 12:03:15 +0100 (ven., 25 févr. 2011) | 1 line
  
  Remove unused m4 define.
................
  r88574 | georg.brandl | 2011-02-25 12:28:22 +0100 (ven., 25 févr. 2011) | 1 line
  
  Add 3.3 whatsnew to index.
................
  r88575 | benjamin.peterson | 2011-02-25 15:01:05 +0100 (ven., 25 févr. 2011) | 1 line
  
  run autoconf
................
  r88576 | benjamin.peterson | 2011-02-25 15:05:42 +0100 (ven., 25 févr. 2011) | 1 line
  
  rewrite with assertIs
................
  r88577 | antoine.pitrou | 2011-02-25 15:19:48 +0100 (ven., 25 févr. 2011) | 3 lines
  
  Make svn:eol-style's more consistent
................
  r88578 | antoine.pitrou | 2011-02-25 15:31:09 +0100 (ven., 25 févr. 2011) | 3 lines
  
  More eol-style's
................
  r88579 | antoine.pitrou | 2011-02-25 15:32:24 +0100 (ven., 25 févr. 2011) | 3 lines
  
  Fix .hgeol
................
  r88580 | giampaolo.rodola | 2011-02-25 15:39:16 +0100 (ven., 25 févr. 2011) | 1 line
  
  Issue 10882: add os.sendfile(). (patch provided by Ross Lagerwall)
................
  r88581 | giampaolo.rodola | 2011-02-25 15:50:57 +0100 (ven., 25 févr. 2011) | 1 line
  
  (issue 11232) - fix asyncore documentation issue (patch by Sandro Tosi)
................
  r88584 | georg.brandl | 2011-02-25 16:21:47 +0100 (ven., 25 févr. 2011) | 1 line
  
  Regenerate configure after r88580.
................
  r88585 | georg.brandl | 2011-02-25 16:23:18 +0100 (ven., 25 févr. 2011) | 1 line
  
  Rename internal helper function and make it static.
................
  r88586 | marc-andre.lemburg | 2011-02-25 16:42:01 +0100 (ven., 25 févr. 2011) | 10 lines
  
  Normalize the encoding names for Latin-1 and UTF-8 to
  'latin-1' and 'utf-8'.
  
  These are optimized in the Python Unicode implementation
  to result in more direct processing, bypassing the codec
  registry.
  
  Also see issue11303.
................
  r88587 | vinay.sajip | 2011-02-25 16:56:55 +0100 (ven., 25 févr. 2011) | 1 line
  
  Improved QueueListener implementation - queue sentinel addition made extensible.
................
  r88588 | vinay.sajip | 2011-02-25 17:05:26 +0100 (ven., 25 févr. 2011) | 1 line
  
  Documented QueueListener change.
................
  r88589 | vinay.sajip | 2011-02-25 18:02:43 +0100 (ven., 25 févr. 2011) | 1 line
  
  logging: enabled test which was intermittently failing on buildbots.
................
  r88602 | alexander.belopolsky | 2011-02-25 20:19:57 +0100 (ven., 25 févr. 2011) | 4 lines
  
  Issue #11303: Added shortcuts for utf8 and latin1 encodings.
  Documented the list of optimized encodings as CPython implementation
  detail.
................
  r88603 | giampaolo.rodola | 2011-02-25 21:01:05 +0100 (ven., 25 févr. 2011) | 1 line
  
  Skip os.sendfile() test if threading module is not available.
................
  r88604 | giampaolo.rodola | 2011-02-25 21:05:48 +0100 (ven., 25 févr. 2011) | 1 line
  
  (issue 11214) - fix asyncore.strerror test failure on AIX
................
  r88607 | antoine.pitrou | 2011-02-25 21:27:33 +0100 (ven., 25 févr. 2011) | 5 lines
  
  Issue #11114: Fix catastrophic performance of tell() on text files (up
  to 1000x faster in some cases).  It is still one to two order of magnitudes
  slower than binary tell().
................
  r88608 | giampaolo.rodola | 2011-02-25 21:57:54 +0100 (ven., 25 févr. 2011) | 1 line
  
  Issue 10784: adds os.getpriority() and os.setpriority() functions.
................
  r88609 | giampaolo.rodola | 2011-02-25 22:00:10 +0100 (ven., 25 févr. 2011) | 1 line
  
  Update Misc/NEWS to include os.getpriority() and os.setpriority() addition.
................
  r88610 | antoine.pitrou | 2011-02-25 22:24:11 +0100 (ven., 25 févr. 2011) | 4 lines
  
  Issue #10956: Buffered I/O classes retry reading or writing after a signal
  has arrived and the handler returned successfully.
................
  r88613 | eric.araujo | 2011-02-25 22:40:34 +0100 (ven., 25 févr. 2011) | 2 lines
  
  Add missing read() in distutils doc.
................
  r88616 | giampaolo.rodola | 2011-02-25 22:46:01 +0100 (ven., 25 févr. 2011) | 1 line
  
  (issue 11323) - attempt to fix solaris buildbot failure for os.sendfile(). Also fixed an AttributeError in get/set priority tests.
................
  r88618 | antoine.pitrou | 2011-02-25 23:07:43 +0100 (ven., 25 févr. 2011) | 7 lines
  
  Issue #6064: Add a `daemon` keyword argument to the threading.Thread
  and multiprocessing.Process constructors in order to override the
  default behaviour of inheriting the daemonic property from the current
  thread/process.
................
  r88619 | giampaolo.rodola | 2011-02-25 23:21:22 +0100 (ven., 25 févr. 2011) | 1 line
  
  Issue 11177: asyncore's create_socket() arguments can now be omitted.
................
  r88620 | giampaolo.rodola | 2011-02-25 23:28:24 +0100 (ven., 25 févr. 2011) | 1 line
  
  Issue 11291: poplib suppresses errors on QUIT.
................
  r88621 | vinay.sajip | 2011-02-25 23:45:25 +0100 (ven., 25 févr. 2011) | 1 line
  
  test_logging: Added more diagnostics for buildbot failures.
................
  r88622 | antoine.pitrou | 2011-02-26 00:07:44 +0100 (sam., 26 févr. 2011) | 5 lines
  
  Issue #7322: Trying to read from a socket's file-like object after a timeout
  occurred now raises an error instead of silently losing data.
  Patch by Ross Lagerwall.
................
  r88624 | antoine.pitrou | 2011-02-26 00:25:17 +0100 (sam., 26 févr. 2011) | 4 lines
  
  Issue #4761: Add the *at() family of functions (openat(), etc.) to the posix
  module.  Patch by Ross Lagerwall.
................
  r88625 | antoine.pitrou | 2011-02-26 00:41:16 +0100 (sam., 26 févr. 2011) | 3 lines
  
  Issue #10755: Add the posix.fdlistdir() function.  Patch by Ross Lagerwall.
................
  r88626 | antoine.pitrou | 2011-02-26 01:22:09 +0100 (sam., 26 févr. 2011) | 3 lines
  
  Fix compilation warning in Modules/posixmodule.c.
................
  r88627 | antoine.pitrou | 2011-02-26 01:22:25 +0100 (sam., 26 févr. 2011) | 3 lines
  
  Fix AttributeError.
................
  r88628 | raymond.hettinger | 2011-02-26 02:02:51 +0100 (sam., 26 févr. 2011) | 3 lines
  
  Issue #11297: Add collections.ChainMap()
................
  r88629 | alexander.belopolsky | 2011-02-26 02:02:56 +0100 (sam., 26 févr. 2011) | 1 line
  
  PEP 7 conformance changes (whitespace only).
................
  r88630 | raymond.hettinger | 2011-02-26 03:48:44 +0100 (sam., 26 févr. 2011) | 2 lines
  
  Make Py3.x style "import builtins"
................
  r88631 | senthil.kumaran | 2011-02-26 04:44:03 +0100 (sam., 26 févr. 2011) | 2 lines
  
  Fix Issue10228 - Refleak run of test_dbm fails when several dbm modules are available (Patch by Ray.Allen)
................
  r88632 | vinay.sajip | 2011-02-26 07:37:04 +0100 (sam., 26 févr. 2011) | 1 line
  
  test_logging: diagnostic code changes.
................


Added:
   python/branches/pep-3151/Doc/c-api/codec.rst
      - copied unchanged from r88632, /python/branches/py3k/Doc/c-api/codec.rst
   python/branches/pep-3151/Doc/howto/logging-cookbook.rst
      - copied unchanged from r88632, /python/branches/py3k/Doc/howto/logging-cookbook.rst
   python/branches/pep-3151/Doc/howto/logging.rst
      - copied unchanged from r88632, /python/branches/py3k/Doc/howto/logging.rst
   python/branches/pep-3151/Doc/howto/pyporting.rst
      - copied unchanged from r88632, /python/branches/py3k/Doc/howto/pyporting.rst
   python/branches/pep-3151/Doc/library/collections.abc.rst
      - copied unchanged from r88632, /python/branches/py3k/Doc/library/collections.abc.rst
   python/branches/pep-3151/Doc/library/functional.rst
      - copied unchanged from r88632, /python/branches/py3k/Doc/library/functional.rst
   python/branches/pep-3151/Doc/library/logging.config.rst
      - copied unchanged from r88632, /python/branches/py3k/Doc/library/logging.config.rst
   python/branches/pep-3151/Doc/library/logging.handlers.rst
      - copied unchanged from r88632, /python/branches/py3k/Doc/library/logging.handlers.rst
   python/branches/pep-3151/Doc/whatsnew/3.3.rst
      - copied unchanged from r88632, /python/branches/py3k/Doc/whatsnew/3.3.rst
   python/branches/pep-3151/Include/typeslots.h
      - copied unchanged from r88632, /python/branches/py3k/Include/typeslots.h
   python/branches/pep-3151/Lib/collections/   (props changed)
      - copied from r88632, /python/branches/py3k/Lib/collections/
   python/branches/pep-3151/Lib/crypt.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/crypt.py
   python/branches/pep-3151/Lib/encodings/base64_codec.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/encodings/base64_codec.py
   python/branches/pep-3151/Lib/encodings/bz2_codec.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/encodings/bz2_codec.py
   python/branches/pep-3151/Lib/encodings/hex_codec.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/encodings/hex_codec.py
   python/branches/pep-3151/Lib/encodings/quopri_codec.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/encodings/quopri_codec.py
   python/branches/pep-3151/Lib/encodings/rot_13.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/encodings/rot_13.py
   python/branches/pep-3151/Lib/encodings/uu_codec.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/encodings/uu_codec.py
   python/branches/pep-3151/Lib/encodings/zlib_codec.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/encodings/zlib_codec.py
   python/branches/pep-3151/Lib/lib2to3/__main__.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/lib2to3/__main__.py
   python/branches/pep-3151/Lib/pydoc_data/_pydoc.css
      - copied unchanged from r88632, /python/branches/py3k/Lib/pydoc_data/_pydoc.css
   python/branches/pep-3151/Lib/test/__main__.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/test/__main__.py
   python/branches/pep-3151/Lib/test/crashers/underlying_dict.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/test/crashers/underlying_dict.py
   python/branches/pep-3151/Lib/test/json_tests/   (props changed)
      - copied from r88632, /python/branches/py3k/Lib/test/json_tests/
   python/branches/pep-3151/Lib/test/subprocessdata/
      - copied from r88632, /python/branches/py3k/Lib/test/subprocessdata/
   python/branches/pep-3151/Lib/test/test_configparser.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/test/test_configparser.py
   python/branches/pep-3151/Lib/test/zip_cp437_header.zip
      - copied unchanged from r88632, /python/branches/py3k/Lib/test/zip_cp437_header.zip
   python/branches/pep-3151/Lib/turtledemo/__main__.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/turtledemo/__main__.py
   python/branches/pep-3151/Lib/unittest/test/_test_warnings.py
      - copied unchanged from r88632, /python/branches/py3k/Lib/unittest/test/_test_warnings.py
   python/branches/pep-3151/Misc/README.AIX
      - copied unchanged from r88632, /python/branches/py3k/Misc/README.AIX
   python/branches/pep-3151/Misc/RPM/python-3.3.spec
      - copied unchanged from r88632, /python/branches/py3k/Misc/RPM/python-3.3.spec
   python/branches/pep-3151/Modules/_cryptmodule.c
      - copied unchanged from r88632, /python/branches/py3k/Modules/_cryptmodule.c
   python/branches/pep-3151/Modules/xxlimited.c
      - copied unchanged from r88632, /python/branches/py3k/Modules/xxlimited.c
   python/branches/pep-3151/Objects/typeslots.inc
      - copied unchanged from r88632, /python/branches/py3k/Objects/typeslots.inc
   python/branches/pep-3151/Objects/typeslots.py
      - copied unchanged from r88632, /python/branches/py3k/Objects/typeslots.py
   python/branches/pep-3151/PC/os2emx/python33.def
      - copied unchanged from r88632, /python/branches/py3k/PC/os2emx/python33.def
   python/branches/pep-3151/PC/python3.def
      - copied unchanged from r88632, /python/branches/py3k/PC/python3.def
   python/branches/pep-3151/PC/python3.mak
      - copied unchanged from r88632, /python/branches/py3k/PC/python3.mak
   python/branches/pep-3151/PC/python33gen.py
      - copied unchanged from r88632, /python/branches/py3k/PC/python33gen.py
   python/branches/pep-3151/PC/python33stub.def
      - copied unchanged from r88632, /python/branches/py3k/PC/python33stub.def
   python/branches/pep-3151/PC/python3dll.c
      - copied unchanged from r88632, /python/branches/py3k/PC/python3dll.c
   python/branches/pep-3151/PCbuild/python3dll.vcproj
      - copied unchanged from r88632, /python/branches/py3k/PCbuild/python3dll.vcproj
   python/branches/pep-3151/PCbuild/xxlimited.vcproj
      - copied unchanged from r88632, /python/branches/py3k/PCbuild/xxlimited.vcproj
   python/branches/pep-3151/Tools/demo/
      - copied from r88632, /python/branches/py3k/Tools/demo/
   python/branches/pep-3151/Tools/parser/
      - copied from r88632, /python/branches/py3k/Tools/parser/
   python/branches/pep-3151/Tools/scripts/abitype.py
      - copied unchanged from r88632, /python/branches/py3k/Tools/scripts/abitype.py
   python/branches/pep-3151/Tools/scripts/find-uname.py
      - copied unchanged from r88632, /python/branches/py3k/Tools/scripts/find-uname.py
   python/branches/pep-3151/Tools/scripts/get-remote-certificate.py
      - copied unchanged from r88632, /python/branches/py3k/Tools/scripts/get-remote-certificate.py
   python/branches/pep-3151/Tools/test2to3/   (props changed)
      - copied from r88632, /python/branches/py3k/Tools/test2to3/
   python/branches/pep-3151/Tools/unittestgui/
      - copied from r88632, /python/branches/py3k/Tools/unittestgui/
Removed:
   python/branches/pep-3151/Demo/
   python/branches/pep-3151/Lib/_abcoll.py
   python/branches/pep-3151/Lib/collections.py
   python/branches/pep-3151/Lib/json/tests/
   python/branches/pep-3151/Lib/test/symlink_support.py
   python/branches/pep-3151/Lib/test/test_cfgparser.py
   python/branches/pep-3151/Mac/Extras.ReadMe.txt
   python/branches/pep-3151/Mac/IDLE/idlemain.py
   python/branches/pep-3151/Misc/AIX-NOTES
   python/branches/pep-3151/Misc/PURIFY.README
   python/branches/pep-3151/Misc/README.Emacs
   python/branches/pep-3151/Misc/README.OpenBSD
   python/branches/pep-3151/Misc/README.klocwork
   python/branches/pep-3151/Misc/RFD
   python/branches/pep-3151/Misc/RPM/python-3.2.spec
   python/branches/pep-3151/Misc/cheatsheet
   python/branches/pep-3151/Misc/developers.txt
   python/branches/pep-3151/Misc/maintainers.rst
   python/branches/pep-3151/Misc/pymemcompat.h
   python/branches/pep-3151/Misc/setuid-prog.c
   python/branches/pep-3151/Modules/cryptmodule.c
   python/branches/pep-3151/PC/os2emx/python27.def
   python/branches/pep-3151/Tools/framer/
   python/branches/pep-3151/Tools/scripts/redemo.py
   python/branches/pep-3151/Tools/ssl/
   python/branches/pep-3151/Tools/world/
   python/branches/pep-3151/runtests.sh
Modified:
   python/branches/pep-3151/   (props changed)
   python/branches/pep-3151/.gitignore
   python/branches/pep-3151/.hgeol
   python/branches/pep-3151/.hgignore
   python/branches/pep-3151/Doc/ACKS.txt
   python/branches/pep-3151/Doc/Makefile
   python/branches/pep-3151/Doc/README.txt
   python/branches/pep-3151/Doc/c-api/arg.rst
   python/branches/pep-3151/Doc/c-api/buffer.rst
   python/branches/pep-3151/Doc/c-api/code.rst
   python/branches/pep-3151/Doc/c-api/exceptions.rst
   python/branches/pep-3151/Doc/c-api/import.rst
   python/branches/pep-3151/Doc/c-api/init.rst
   python/branches/pep-3151/Doc/c-api/intro.rst
   python/branches/pep-3151/Doc/c-api/list.rst
   python/branches/pep-3151/Doc/c-api/module.rst
   python/branches/pep-3151/Doc/c-api/object.rst
   python/branches/pep-3151/Doc/c-api/slice.rst
   python/branches/pep-3151/Doc/c-api/type.rst
   python/branches/pep-3151/Doc/c-api/typeobj.rst
   python/branches/pep-3151/Doc/c-api/unicode.rst
   python/branches/pep-3151/Doc/c-api/utilities.rst
   python/branches/pep-3151/Doc/c-api/veryhigh.rst
   python/branches/pep-3151/Doc/conf.py
   python/branches/pep-3151/Doc/copyright.rst
   python/branches/pep-3151/Doc/distutils/apiref.rst
   python/branches/pep-3151/Doc/distutils/uploading.rst
   python/branches/pep-3151/Doc/documenting/markup.rst
   python/branches/pep-3151/Doc/documenting/style.rst
   python/branches/pep-3151/Doc/extending/embedding.rst
   python/branches/pep-3151/Doc/extending/extending.rst
   python/branches/pep-3151/Doc/extending/windows.rst
   python/branches/pep-3151/Doc/faq/design.rst
   python/branches/pep-3151/Doc/faq/extending.rst
   python/branches/pep-3151/Doc/faq/gui.rst
   python/branches/pep-3151/Doc/faq/installed.rst
   python/branches/pep-3151/Doc/faq/library.rst
   python/branches/pep-3151/Doc/faq/programming.rst
   python/branches/pep-3151/Doc/glossary.rst
   python/branches/pep-3151/Doc/howto/index.rst
   python/branches/pep-3151/Doc/howto/regex.rst
   python/branches/pep-3151/Doc/howto/sorting.rst
   python/branches/pep-3151/Doc/howto/unicode.rst
   python/branches/pep-3151/Doc/howto/webservers.rst
   python/branches/pep-3151/Doc/includes/email-mime.py
   python/branches/pep-3151/Doc/includes/mp_newtype.py
   python/branches/pep-3151/Doc/includes/sqlite3/adapter_point_1.py
   python/branches/pep-3151/Doc/includes/sqlite3/adapter_point_2.py
   python/branches/pep-3151/Doc/includes/sqlite3/converter_point.py
   python/branches/pep-3151/Doc/includes/tzinfo-examples.py
   python/branches/pep-3151/Doc/install/index.rst
   python/branches/pep-3151/Doc/library/2to3.rst
   python/branches/pep-3151/Doc/library/__future__.rst
   python/branches/pep-3151/Doc/library/_dummy_thread.rst
   python/branches/pep-3151/Doc/library/_thread.rst
   python/branches/pep-3151/Doc/library/abc.rst
   python/branches/pep-3151/Doc/library/aifc.rst
   python/branches/pep-3151/Doc/library/allos.rst
   python/branches/pep-3151/Doc/library/argparse.rst
   python/branches/pep-3151/Doc/library/array.rst
   python/branches/pep-3151/Doc/library/ast.rst
   python/branches/pep-3151/Doc/library/asynchat.rst
   python/branches/pep-3151/Doc/library/asyncore.rst
   python/branches/pep-3151/Doc/library/atexit.rst
   python/branches/pep-3151/Doc/library/base64.rst
   python/branches/pep-3151/Doc/library/bdb.rst
   python/branches/pep-3151/Doc/library/bisect.rst
   python/branches/pep-3151/Doc/library/builtins.rst
   python/branches/pep-3151/Doc/library/calendar.rst
   python/branches/pep-3151/Doc/library/cgi.rst
   python/branches/pep-3151/Doc/library/cmd.rst
   python/branches/pep-3151/Doc/library/codecs.rst
   python/branches/pep-3151/Doc/library/collections.rst
   python/branches/pep-3151/Doc/library/colorsys.rst
   python/branches/pep-3151/Doc/library/compileall.rst
   python/branches/pep-3151/Doc/library/concurrent.futures.rst
   python/branches/pep-3151/Doc/library/configparser.rst
   python/branches/pep-3151/Doc/library/contextlib.rst
   python/branches/pep-3151/Doc/library/crypt.rst
   python/branches/pep-3151/Doc/library/csv.rst
   python/branches/pep-3151/Doc/library/ctypes.rst
   python/branches/pep-3151/Doc/library/curses.rst
   python/branches/pep-3151/Doc/library/datatypes.rst
   python/branches/pep-3151/Doc/library/datetime.rst
   python/branches/pep-3151/Doc/library/dbm.rst
   python/branches/pep-3151/Doc/library/decimal.rst
   python/branches/pep-3151/Doc/library/difflib.rst
   python/branches/pep-3151/Doc/library/dis.rst
   python/branches/pep-3151/Doc/library/doctest.rst
   python/branches/pep-3151/Doc/library/dummy_threading.rst
   python/branches/pep-3151/Doc/library/email.charset.rst
   python/branches/pep-3151/Doc/library/email.generator.rst
   python/branches/pep-3151/Doc/library/email.header.rst
   python/branches/pep-3151/Doc/library/email.message.rst
   python/branches/pep-3151/Doc/library/email.util.rst
   python/branches/pep-3151/Doc/library/exceptions.rst
   python/branches/pep-3151/Doc/library/filecmp.rst
   python/branches/pep-3151/Doc/library/fileformats.rst
   python/branches/pep-3151/Doc/library/fileinput.rst
   python/branches/pep-3151/Doc/library/fnmatch.rst
   python/branches/pep-3151/Doc/library/fractions.rst
   python/branches/pep-3151/Doc/library/ftplib.rst
   python/branches/pep-3151/Doc/library/functions.rst
   python/branches/pep-3151/Doc/library/functools.rst
   python/branches/pep-3151/Doc/library/getopt.rst
   python/branches/pep-3151/Doc/library/gettext.rst
   python/branches/pep-3151/Doc/library/glob.rst
   python/branches/pep-3151/Doc/library/grp.rst
   python/branches/pep-3151/Doc/library/gzip.rst
   python/branches/pep-3151/Doc/library/hashlib.rst
   python/branches/pep-3151/Doc/library/heapq.rst
   python/branches/pep-3151/Doc/library/hmac.rst
   python/branches/pep-3151/Doc/library/html.entities.rst
   python/branches/pep-3151/Doc/library/html.parser.rst
   python/branches/pep-3151/Doc/library/html.rst
   python/branches/pep-3151/Doc/library/http.client.rst
   python/branches/pep-3151/Doc/library/http.cookiejar.rst
   python/branches/pep-3151/Doc/library/http.cookies.rst
   python/branches/pep-3151/Doc/library/http.server.rst
   python/branches/pep-3151/Doc/library/idle.rst
   python/branches/pep-3151/Doc/library/imaplib.rst
   python/branches/pep-3151/Doc/library/imghdr.rst
   python/branches/pep-3151/Doc/library/imp.rst
   python/branches/pep-3151/Doc/library/importlib.rst
   python/branches/pep-3151/Doc/library/index.rst
   python/branches/pep-3151/Doc/library/inspect.rst
   python/branches/pep-3151/Doc/library/io.rst
   python/branches/pep-3151/Doc/library/itertools.rst
   python/branches/pep-3151/Doc/library/json.rst
   python/branches/pep-3151/Doc/library/keyword.rst
   python/branches/pep-3151/Doc/library/linecache.rst
   python/branches/pep-3151/Doc/library/logging.rst
   python/branches/pep-3151/Doc/library/mailbox.rst
   python/branches/pep-3151/Doc/library/mailcap.rst
   python/branches/pep-3151/Doc/library/mimetypes.rst
   python/branches/pep-3151/Doc/library/modulefinder.rst
   python/branches/pep-3151/Doc/library/msilib.rst
   python/branches/pep-3151/Doc/library/multiprocessing.rst
   python/branches/pep-3151/Doc/library/netrc.rst
   python/branches/pep-3151/Doc/library/nntplib.rst
   python/branches/pep-3151/Doc/library/numeric.rst
   python/branches/pep-3151/Doc/library/operator.rst
   python/branches/pep-3151/Doc/library/optparse.rst
   python/branches/pep-3151/Doc/library/os.path.rst
   python/branches/pep-3151/Doc/library/os.rst
   python/branches/pep-3151/Doc/library/parser.rst
   python/branches/pep-3151/Doc/library/pdb.rst
   python/branches/pep-3151/Doc/library/pickle.rst
   python/branches/pep-3151/Doc/library/pickletools.rst
   python/branches/pep-3151/Doc/library/pipes.rst
   python/branches/pep-3151/Doc/library/pkgutil.rst
   python/branches/pep-3151/Doc/library/platform.rst
   python/branches/pep-3151/Doc/library/plistlib.rst
   python/branches/pep-3151/Doc/library/poplib.rst
   python/branches/pep-3151/Doc/library/pprint.rst
   python/branches/pep-3151/Doc/library/profile.rst
   python/branches/pep-3151/Doc/library/pty.rst
   python/branches/pep-3151/Doc/library/py_compile.rst
   python/branches/pep-3151/Doc/library/pyclbr.rst
   python/branches/pep-3151/Doc/library/pydoc.rst
   python/branches/pep-3151/Doc/library/pyexpat.rst
   python/branches/pep-3151/Doc/library/queue.rst
   python/branches/pep-3151/Doc/library/quopri.rst
   python/branches/pep-3151/Doc/library/random.rst
   python/branches/pep-3151/Doc/library/re.rst
   python/branches/pep-3151/Doc/library/reprlib.rst
   python/branches/pep-3151/Doc/library/resource.rst
   python/branches/pep-3151/Doc/library/rlcompleter.rst
   python/branches/pep-3151/Doc/library/runpy.rst
   python/branches/pep-3151/Doc/library/sched.rst
   python/branches/pep-3151/Doc/library/select.rst
   python/branches/pep-3151/Doc/library/shelve.rst
   python/branches/pep-3151/Doc/library/shlex.rst
   python/branches/pep-3151/Doc/library/shutil.rst
   python/branches/pep-3151/Doc/library/site.rst
   python/branches/pep-3151/Doc/library/smtpd.rst
   python/branches/pep-3151/Doc/library/smtplib.rst
   python/branches/pep-3151/Doc/library/sndhdr.rst
   python/branches/pep-3151/Doc/library/socket.rst
   python/branches/pep-3151/Doc/library/socketserver.rst
   python/branches/pep-3151/Doc/library/someos.rst
   python/branches/pep-3151/Doc/library/sqlite3.rst
   python/branches/pep-3151/Doc/library/ssl.rst
   python/branches/pep-3151/Doc/library/stat.rst
   python/branches/pep-3151/Doc/library/stdtypes.rst
   python/branches/pep-3151/Doc/library/string.rst
   python/branches/pep-3151/Doc/library/struct.rst
   python/branches/pep-3151/Doc/library/subprocess.rst
   python/branches/pep-3151/Doc/library/sunau.rst
   python/branches/pep-3151/Doc/library/symbol.rst
   python/branches/pep-3151/Doc/library/sys.rst
   python/branches/pep-3151/Doc/library/sysconfig.rst
   python/branches/pep-3151/Doc/library/tabnanny.rst
   python/branches/pep-3151/Doc/library/tarfile.rst
   python/branches/pep-3151/Doc/library/telnetlib.rst
   python/branches/pep-3151/Doc/library/tempfile.rst
   python/branches/pep-3151/Doc/library/test.rst
   python/branches/pep-3151/Doc/library/textwrap.rst
   python/branches/pep-3151/Doc/library/threading.rst
   python/branches/pep-3151/Doc/library/time.rst
   python/branches/pep-3151/Doc/library/timeit.rst
   python/branches/pep-3151/Doc/library/tkinter.rst
   python/branches/pep-3151/Doc/library/tkinter.tix.rst
   python/branches/pep-3151/Doc/library/token.rst
   python/branches/pep-3151/Doc/library/tokenize.rst
   python/branches/pep-3151/Doc/library/trace.rst
   python/branches/pep-3151/Doc/library/turtle.rst
   python/branches/pep-3151/Doc/library/types.rst
   python/branches/pep-3151/Doc/library/unicodedata.rst
   python/branches/pep-3151/Doc/library/unittest.rst
   python/branches/pep-3151/Doc/library/urllib.parse.rst
   python/branches/pep-3151/Doc/library/urllib.request.rst
   python/branches/pep-3151/Doc/library/uu.rst
   python/branches/pep-3151/Doc/library/warnings.rst
   python/branches/pep-3151/Doc/library/wave.rst
   python/branches/pep-3151/Doc/library/weakref.rst
   python/branches/pep-3151/Doc/library/webbrowser.rst
   python/branches/pep-3151/Doc/library/xdrlib.rst
   python/branches/pep-3151/Doc/library/xml.dom.minidom.rst
   python/branches/pep-3151/Doc/library/xml.dom.pulldom.rst
   python/branches/pep-3151/Doc/library/xml.etree.elementtree.rst
   python/branches/pep-3151/Doc/library/xmlrpc.client.rst
   python/branches/pep-3151/Doc/library/xmlrpc.server.rst
   python/branches/pep-3151/Doc/library/zipfile.rst
   python/branches/pep-3151/Doc/library/zlib.rst
   python/branches/pep-3151/Doc/license.rst
   python/branches/pep-3151/Doc/make.bat   (contents, props changed)
   python/branches/pep-3151/Doc/reference/compound_stmts.rst
   python/branches/pep-3151/Doc/reference/datamodel.rst
   python/branches/pep-3151/Doc/reference/executionmodel.rst
   python/branches/pep-3151/Doc/reference/expressions.rst
   python/branches/pep-3151/Doc/reference/lexical_analysis.rst
   python/branches/pep-3151/Doc/reference/simple_stmts.rst
   python/branches/pep-3151/Doc/tools/sphinxext/download.html
   python/branches/pep-3151/Doc/tools/sphinxext/indexcontent.html
   python/branches/pep-3151/Doc/tools/sphinxext/indexsidebar.html
   python/branches/pep-3151/Doc/tools/sphinxext/pyspecific.py
   python/branches/pep-3151/Doc/tools/sphinxext/static/basic.css
   python/branches/pep-3151/Doc/tools/sphinxext/susp-ignored.csv
   python/branches/pep-3151/Doc/tutorial/inputoutput.rst
   python/branches/pep-3151/Doc/tutorial/interpreter.rst
   python/branches/pep-3151/Doc/tutorial/introduction.rst
   python/branches/pep-3151/Doc/tutorial/stdlib.rst
   python/branches/pep-3151/Doc/tutorial/stdlib2.rst
   python/branches/pep-3151/Doc/using/cmdline.rst
   python/branches/pep-3151/Doc/whatsnew/2.0.rst
   python/branches/pep-3151/Doc/whatsnew/2.1.rst
   python/branches/pep-3151/Doc/whatsnew/2.2.rst
   python/branches/pep-3151/Doc/whatsnew/2.4.rst
   python/branches/pep-3151/Doc/whatsnew/2.7.rst
   python/branches/pep-3151/Doc/whatsnew/3.0.rst
   python/branches/pep-3151/Doc/whatsnew/3.2.rst
   python/branches/pep-3151/Doc/whatsnew/index.rst
   python/branches/pep-3151/Include/Python.h
   python/branches/pep-3151/Include/abstract.h
   python/branches/pep-3151/Include/ast.h
   python/branches/pep-3151/Include/bytearrayobject.h
   python/branches/pep-3151/Include/bytes_methods.h
   python/branches/pep-3151/Include/bytesobject.h
   python/branches/pep-3151/Include/cellobject.h
   python/branches/pep-3151/Include/ceval.h
   python/branches/pep-3151/Include/classobject.h
   python/branches/pep-3151/Include/code.h
   python/branches/pep-3151/Include/codecs.h
   python/branches/pep-3151/Include/compile.h
   python/branches/pep-3151/Include/complexobject.h
   python/branches/pep-3151/Include/datetime.h
   python/branches/pep-3151/Include/descrobject.h
   python/branches/pep-3151/Include/dictobject.h
   python/branches/pep-3151/Include/dtoa.h
   python/branches/pep-3151/Include/eval.h
   python/branches/pep-3151/Include/fileobject.h
   python/branches/pep-3151/Include/floatobject.h
   python/branches/pep-3151/Include/frameobject.h
   python/branches/pep-3151/Include/funcobject.h
   python/branches/pep-3151/Include/genobject.h
   python/branches/pep-3151/Include/import.h
   python/branches/pep-3151/Include/listobject.h
   python/branches/pep-3151/Include/longintrepr.h
   python/branches/pep-3151/Include/longobject.h
   python/branches/pep-3151/Include/marshal.h
   python/branches/pep-3151/Include/memoryobject.h
   python/branches/pep-3151/Include/methodobject.h
   python/branches/pep-3151/Include/modsupport.h
   python/branches/pep-3151/Include/moduleobject.h
   python/branches/pep-3151/Include/object.h
   python/branches/pep-3151/Include/objimpl.h
   python/branches/pep-3151/Include/parsetok.h
   python/branches/pep-3151/Include/patchlevel.h
   python/branches/pep-3151/Include/pyarena.h
   python/branches/pep-3151/Include/pyatomic.h
   python/branches/pep-3151/Include/pycapsule.h
   python/branches/pep-3151/Include/pyctype.h
   python/branches/pep-3151/Include/pydebug.h
   python/branches/pep-3151/Include/pyerrors.h
   python/branches/pep-3151/Include/pygetopt.h
   python/branches/pep-3151/Include/pymath.h
   python/branches/pep-3151/Include/pyport.h
   python/branches/pep-3151/Include/pystate.h
   python/branches/pep-3151/Include/pystrtod.h
   python/branches/pep-3151/Include/pythonrun.h
   python/branches/pep-3151/Include/pythread.h
   python/branches/pep-3151/Include/pytime.h
   python/branches/pep-3151/Include/setobject.h
   python/branches/pep-3151/Include/sliceobject.h
   python/branches/pep-3151/Include/structseq.h
   python/branches/pep-3151/Include/symtable.h
   python/branches/pep-3151/Include/sysmodule.h
   python/branches/pep-3151/Include/timefuncs.h
   python/branches/pep-3151/Include/token.h
   python/branches/pep-3151/Include/traceback.h
   python/branches/pep-3151/Include/tupleobject.h
   python/branches/pep-3151/Include/ucnhash.h
   python/branches/pep-3151/Include/unicodeobject.h
   python/branches/pep-3151/Include/warnings.h
   python/branches/pep-3151/Include/weakrefobject.h
   python/branches/pep-3151/LICENSE
   python/branches/pep-3151/Lib/_pyio.py
   python/branches/pep-3151/Lib/_weakrefset.py
   python/branches/pep-3151/Lib/abc.py
   python/branches/pep-3151/Lib/argparse.py
   python/branches/pep-3151/Lib/ast.py
   python/branches/pep-3151/Lib/asynchat.py
   python/branches/pep-3151/Lib/asyncore.py
   python/branches/pep-3151/Lib/base64.py
   python/branches/pep-3151/Lib/bdb.py
   python/branches/pep-3151/Lib/cgi.py
   python/branches/pep-3151/Lib/codecs.py
   python/branches/pep-3151/Lib/compileall.py
   python/branches/pep-3151/Lib/concurrent/futures/_base.py
   python/branches/pep-3151/Lib/concurrent/futures/process.py
   python/branches/pep-3151/Lib/configparser.py
   python/branches/pep-3151/Lib/contextlib.py
   python/branches/pep-3151/Lib/ctypes/test/test_callbacks.py
   python/branches/pep-3151/Lib/ctypes/test/test_keeprefs.py
   python/branches/pep-3151/Lib/ctypes/test/test_memfunctions.py
   python/branches/pep-3151/Lib/ctypes/test/test_python_api.py
   python/branches/pep-3151/Lib/ctypes/test/test_refcounts.py
   python/branches/pep-3151/Lib/ctypes/test/test_stringptr.py
   python/branches/pep-3151/Lib/datetime.py
   python/branches/pep-3151/Lib/dbm/dumb.py
   python/branches/pep-3151/Lib/decimal.py
   python/branches/pep-3151/Lib/difflib.py
   python/branches/pep-3151/Lib/distutils/__init__.py
   python/branches/pep-3151/Lib/distutils/archive_util.py
   python/branches/pep-3151/Lib/distutils/command/bdist_wininst.py
   python/branches/pep-3151/Lib/distutils/command/build_ext.py
   python/branches/pep-3151/Lib/distutils/command/install.py
   python/branches/pep-3151/Lib/distutils/dir_util.py
   python/branches/pep-3151/Lib/distutils/msvc9compiler.py
   python/branches/pep-3151/Lib/distutils/sysconfig.py
   python/branches/pep-3151/Lib/distutils/tests/test_archive_util.py
   python/branches/pep-3151/Lib/distutils/tests/test_bdist.py
   python/branches/pep-3151/Lib/distutils/tests/test_bdist_dumb.py
   python/branches/pep-3151/Lib/distutils/tests/test_build.py
   python/branches/pep-3151/Lib/distutils/tests/test_build_clib.py
   python/branches/pep-3151/Lib/distutils/tests/test_build_ext.py
   python/branches/pep-3151/Lib/distutils/tests/test_check.py
   python/branches/pep-3151/Lib/distutils/tests/test_cmd.py
   python/branches/pep-3151/Lib/distutils/tests/test_config.py
   python/branches/pep-3151/Lib/distutils/tests/test_config_cmd.py
   python/branches/pep-3151/Lib/distutils/tests/test_core.py
   python/branches/pep-3151/Lib/distutils/tests/test_cygwinccompiler.py
   python/branches/pep-3151/Lib/distutils/tests/test_dep_util.py
   python/branches/pep-3151/Lib/distutils/tests/test_dir_util.py
   python/branches/pep-3151/Lib/distutils/tests/test_dist.py
   python/branches/pep-3151/Lib/distutils/tests/test_extension.py
   python/branches/pep-3151/Lib/distutils/tests/test_file_util.py
   python/branches/pep-3151/Lib/distutils/tests/test_filelist.py
   python/branches/pep-3151/Lib/distutils/tests/test_install.py
   python/branches/pep-3151/Lib/distutils/tests/test_install_data.py
   python/branches/pep-3151/Lib/distutils/tests/test_install_headers.py
   python/branches/pep-3151/Lib/distutils/tests/test_install_lib.py
   python/branches/pep-3151/Lib/distutils/tests/test_log.py
   python/branches/pep-3151/Lib/distutils/tests/test_msvc9compiler.py
   python/branches/pep-3151/Lib/distutils/tests/test_register.py
   python/branches/pep-3151/Lib/distutils/tests/test_sdist.py
   python/branches/pep-3151/Lib/distutils/tests/test_spawn.py
   python/branches/pep-3151/Lib/distutils/tests/test_sysconfig.py
   python/branches/pep-3151/Lib/distutils/tests/test_text_file.py
   python/branches/pep-3151/Lib/distutils/tests/test_upload.py
   python/branches/pep-3151/Lib/distutils/tests/test_util.py
   python/branches/pep-3151/Lib/distutils/tests/test_version.py
   python/branches/pep-3151/Lib/doctest.py
   python/branches/pep-3151/Lib/email/__init__.py
   python/branches/pep-3151/Lib/email/_parseaddr.py
   python/branches/pep-3151/Lib/email/charset.py
   python/branches/pep-3151/Lib/email/generator.py
   python/branches/pep-3151/Lib/email/header.py
   python/branches/pep-3151/Lib/email/message.py
   python/branches/pep-3151/Lib/email/test/test_email.py
   python/branches/pep-3151/Lib/email/utils.py
   python/branches/pep-3151/Lib/fractions.py
   python/branches/pep-3151/Lib/ftplib.py
   python/branches/pep-3151/Lib/functools.py
   python/branches/pep-3151/Lib/getpass.py
   python/branches/pep-3151/Lib/gettext.py
   python/branches/pep-3151/Lib/gzip.py
   python/branches/pep-3151/Lib/hashlib.py
   python/branches/pep-3151/Lib/html/parser.py
   python/branches/pep-3151/Lib/http/client.py
   python/branches/pep-3151/Lib/http/cookies.py
   python/branches/pep-3151/Lib/http/server.py
   python/branches/pep-3151/Lib/idlelib/Bindings.py
   python/branches/pep-3151/Lib/idlelib/EditorWindow.py
   python/branches/pep-3151/Lib/idlelib/FileList.py
   python/branches/pep-3151/Lib/idlelib/IOBinding.py
   python/branches/pep-3151/Lib/idlelib/PyShell.py
   python/branches/pep-3151/Lib/idlelib/RemoteObjectBrowser.py
   python/branches/pep-3151/Lib/idlelib/ScriptBinding.py
   python/branches/pep-3151/Lib/idlelib/config-keys.def
   python/branches/pep-3151/Lib/idlelib/idle.bat
   python/branches/pep-3151/Lib/idlelib/idlever.py
   python/branches/pep-3151/Lib/idlelib/macosxSupport.py
   python/branches/pep-3151/Lib/imaplib.py
   python/branches/pep-3151/Lib/importlib/_bootstrap.py
   python/branches/pep-3151/Lib/importlib/abc.py
   python/branches/pep-3151/Lib/importlib/test/import_/test___package__.py
   python/branches/pep-3151/Lib/importlib/test/import_/test_caching.py
   python/branches/pep-3151/Lib/importlib/test/import_/test_fromlist.py
   python/branches/pep-3151/Lib/importlib/test/import_/test_meta_path.py
   python/branches/pep-3151/Lib/inspect.py
   python/branches/pep-3151/Lib/json/__init__.py
   python/branches/pep-3151/Lib/lib2to3/   (props changed)
   python/branches/pep-3151/Lib/lib2to3/fixes/fix_urllib.py
   python/branches/pep-3151/Lib/lib2to3/main.py
   python/branches/pep-3151/Lib/lib2to3/refactor.py
   python/branches/pep-3151/Lib/lib2to3/tests/test_refactor.py
   python/branches/pep-3151/Lib/lib2to3/tests/test_util.py
   python/branches/pep-3151/Lib/logging/__init__.py
   python/branches/pep-3151/Lib/logging/handlers.py
   python/branches/pep-3151/Lib/mailbox.py
   python/branches/pep-3151/Lib/mimetypes.py
   python/branches/pep-3151/Lib/multiprocessing/__init__.py
   python/branches/pep-3151/Lib/multiprocessing/connection.py
   python/branches/pep-3151/Lib/multiprocessing/dummy/__init__.py
   python/branches/pep-3151/Lib/multiprocessing/dummy/connection.py
   python/branches/pep-3151/Lib/multiprocessing/forking.py
   python/branches/pep-3151/Lib/multiprocessing/heap.py
   python/branches/pep-3151/Lib/multiprocessing/managers.py
   python/branches/pep-3151/Lib/multiprocessing/pool.py
   python/branches/pep-3151/Lib/multiprocessing/process.py
   python/branches/pep-3151/Lib/multiprocessing/queues.py
   python/branches/pep-3151/Lib/multiprocessing/reduction.py
   python/branches/pep-3151/Lib/multiprocessing/sharedctypes.py
   python/branches/pep-3151/Lib/multiprocessing/synchronize.py
   python/branches/pep-3151/Lib/multiprocessing/util.py
   python/branches/pep-3151/Lib/netrc.py
   python/branches/pep-3151/Lib/numbers.py
   python/branches/pep-3151/Lib/os.py
   python/branches/pep-3151/Lib/pdb.py
   python/branches/pep-3151/Lib/poplib.py
   python/branches/pep-3151/Lib/pstats.py
   python/branches/pep-3151/Lib/py_compile.py
   python/branches/pep-3151/Lib/pyclbr.py
   python/branches/pep-3151/Lib/pydoc.py
   python/branches/pep-3151/Lib/pydoc_data/topics.py
   python/branches/pep-3151/Lib/random.py
   python/branches/pep-3151/Lib/reprlib.py
   python/branches/pep-3151/Lib/shelve.py
   python/branches/pep-3151/Lib/shutil.py
   python/branches/pep-3151/Lib/site.py
   python/branches/pep-3151/Lib/smtpd.py
   python/branches/pep-3151/Lib/smtplib.py
   python/branches/pep-3151/Lib/socket.py
   python/branches/pep-3151/Lib/sqlite3/test/dbapi.py
   python/branches/pep-3151/Lib/sqlite3/test/types.py
   python/branches/pep-3151/Lib/sre_parse.py
   python/branches/pep-3151/Lib/string.py
   python/branches/pep-3151/Lib/struct.py
   python/branches/pep-3151/Lib/subprocess.py
   python/branches/pep-3151/Lib/sysconfig.py
   python/branches/pep-3151/Lib/tabnanny.py
   python/branches/pep-3151/Lib/tarfile.py
   python/branches/pep-3151/Lib/telnetlib.py
   python/branches/pep-3151/Lib/tempfile.py
   python/branches/pep-3151/Lib/test/buffer_tests.py
   python/branches/pep-3151/Lib/test/cmath_testcases.txt
   python/branches/pep-3151/Lib/test/crashers/README
   python/branches/pep-3151/Lib/test/datetimetester.py
   python/branches/pep-3151/Lib/test/decimaltestdata/abs.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/add.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/base.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/clamp.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/compare.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/decDouble.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/decQuad.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/decSingle.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/divide.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/divideint.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/inexact.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/max.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/min.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/minus.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/multiply.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/plus.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/power.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/quantize.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/randomBound32.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/randoms.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/reduce.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/remainder.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/remainderNear.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/rescale.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/rounding.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/samequantum.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/squareroot.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/subtract.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/testall.decTest   (props changed)
   python/branches/pep-3151/Lib/test/decimaltestdata/tointegral.decTest   (props changed)
   python/branches/pep-3151/Lib/test/fork_wait.py
   python/branches/pep-3151/Lib/test/list_tests.py
   python/branches/pep-3151/Lib/test/lock_tests.py
   python/branches/pep-3151/Lib/test/outstanding_bugs.py
   python/branches/pep-3151/Lib/test/pickletester.py
   python/branches/pep-3151/Lib/test/pydoc_mod.py
   python/branches/pep-3151/Lib/test/pystone.py
   python/branches/pep-3151/Lib/test/regrtest.py
   python/branches/pep-3151/Lib/test/script_helper.py
   python/branches/pep-3151/Lib/test/seq_tests.py
   python/branches/pep-3151/Lib/test/sha256.pem
   python/branches/pep-3151/Lib/test/string_tests.py
   python/branches/pep-3151/Lib/test/support.py
   python/branches/pep-3151/Lib/test/test__locale.py
   python/branches/pep-3151/Lib/test/test_abc.py
   python/branches/pep-3151/Lib/test/test_argparse.py
   python/branches/pep-3151/Lib/test/test_array.py
   python/branches/pep-3151/Lib/test/test_ast.py
   python/branches/pep-3151/Lib/test/test_asyncore.py
   python/branches/pep-3151/Lib/test/test_atexit.py
   python/branches/pep-3151/Lib/test/test_augassign.py
   python/branches/pep-3151/Lib/test/test_base64.py
   python/branches/pep-3151/Lib/test/test_bigaddrspace.py
   python/branches/pep-3151/Lib/test/test_bigmem.py
   python/branches/pep-3151/Lib/test/test_bool.py
   python/branches/pep-3151/Lib/test/test_builtin.py
   python/branches/pep-3151/Lib/test/test_bytes.py
   python/branches/pep-3151/Lib/test/test_bz2.py
   python/branches/pep-3151/Lib/test/test_calendar.py
   python/branches/pep-3151/Lib/test/test_capi.py
   python/branches/pep-3151/Lib/test/test_cgi.py
   python/branches/pep-3151/Lib/test/test_charmapcodec.py
   python/branches/pep-3151/Lib/test/test_class.py
   python/branches/pep-3151/Lib/test/test_cmath.py
   python/branches/pep-3151/Lib/test/test_cmd_line.py
   python/branches/pep-3151/Lib/test/test_code.py
   python/branches/pep-3151/Lib/test/test_codeccallbacks.py
   python/branches/pep-3151/Lib/test/test_codecs.py
   python/branches/pep-3151/Lib/test/test_codeop.py
   python/branches/pep-3151/Lib/test/test_collections.py
   python/branches/pep-3151/Lib/test/test_compileall.py
   python/branches/pep-3151/Lib/test/test_complex.py
   python/branches/pep-3151/Lib/test/test_concurrent_futures.py
   python/branches/pep-3151/Lib/test/test_contextlib.py
   python/branches/pep-3151/Lib/test/test_copyreg.py
   python/branches/pep-3151/Lib/test/test_crypt.py
   python/branches/pep-3151/Lib/test/test_csv.py
   python/branches/pep-3151/Lib/test/test_dbm.py
   python/branches/pep-3151/Lib/test/test_dbm_gnu.py
   python/branches/pep-3151/Lib/test/test_decimal.py
   python/branches/pep-3151/Lib/test/test_deque.py
   python/branches/pep-3151/Lib/test/test_descr.py
   python/branches/pep-3151/Lib/test/test_descrtut.py
   python/branches/pep-3151/Lib/test/test_dict.py
   python/branches/pep-3151/Lib/test/test_difflib.py
   python/branches/pep-3151/Lib/test/test_dis.py
   python/branches/pep-3151/Lib/test/test_doctest.py
   python/branches/pep-3151/Lib/test/test_epoll.py
   python/branches/pep-3151/Lib/test/test_exceptions.py
   python/branches/pep-3151/Lib/test/test_file.py
   python/branches/pep-3151/Lib/test/test_fileio.py
   python/branches/pep-3151/Lib/test/test_float.py
   python/branches/pep-3151/Lib/test/test_fork1.py
   python/branches/pep-3151/Lib/test/test_fractions.py
   python/branches/pep-3151/Lib/test/test_frozen.py
   python/branches/pep-3151/Lib/test/test_functools.py
   python/branches/pep-3151/Lib/test/test_gc.py
   python/branches/pep-3151/Lib/test/test_gdb.py
   python/branches/pep-3151/Lib/test/test_genexps.py
   python/branches/pep-3151/Lib/test/test_getargs2.py
   python/branches/pep-3151/Lib/test/test_getopt.py
   python/branches/pep-3151/Lib/test/test_glob.py
   python/branches/pep-3151/Lib/test/test_grp.py
   python/branches/pep-3151/Lib/test/test_gzip.py
   python/branches/pep-3151/Lib/test/test_hashlib.py
   python/branches/pep-3151/Lib/test/test_htmlparser.py
   python/branches/pep-3151/Lib/test/test_http_cookiejar.py
   python/branches/pep-3151/Lib/test/test_http_cookies.py
   python/branches/pep-3151/Lib/test/test_httplib.py
   python/branches/pep-3151/Lib/test/test_httpservers.py
   python/branches/pep-3151/Lib/test/test_imaplib.py
   python/branches/pep-3151/Lib/test/test_imp.py
   python/branches/pep-3151/Lib/test/test_import.py
   python/branches/pep-3151/Lib/test/test_inspect.py
   python/branches/pep-3151/Lib/test/test_int.py
   python/branches/pep-3151/Lib/test/test_io.py
   python/branches/pep-3151/Lib/test/test_ioctl.py
   python/branches/pep-3151/Lib/test/test_isinstance.py
   python/branches/pep-3151/Lib/test/test_itertools.py
   python/branches/pep-3151/Lib/test/test_json.py
   python/branches/pep-3151/Lib/test/test_keywordonlyarg.py
   python/branches/pep-3151/Lib/test/test_kqueue.py
   python/branches/pep-3151/Lib/test/test_linecache.py
   python/branches/pep-3151/Lib/test/test_listcomps.py
   python/branches/pep-3151/Lib/test/test_logging.py
   python/branches/pep-3151/Lib/test/test_long.py
   python/branches/pep-3151/Lib/test/test_mailbox.py
   python/branches/pep-3151/Lib/test/test_marshal.py
   python/branches/pep-3151/Lib/test/test_math.py
   python/branches/pep-3151/Lib/test/test_memoryio.py
   python/branches/pep-3151/Lib/test/test_memoryview.py
   python/branches/pep-3151/Lib/test/test_metaclass.py
   python/branches/pep-3151/Lib/test/test_minidom.py
   python/branches/pep-3151/Lib/test/test_mmap.py
   python/branches/pep-3151/Lib/test/test_multiprocessing.py
   python/branches/pep-3151/Lib/test/test_netrc.py
   python/branches/pep-3151/Lib/test/test_nntplib.py
   python/branches/pep-3151/Lib/test/test_normalization.py
   python/branches/pep-3151/Lib/test/test_ntpath.py
   python/branches/pep-3151/Lib/test/test_opcodes.py
   python/branches/pep-3151/Lib/test/test_operator.py
   python/branches/pep-3151/Lib/test/test_optparse.py
   python/branches/pep-3151/Lib/test/test_os.py
   python/branches/pep-3151/Lib/test/test_parser.py
   python/branches/pep-3151/Lib/test/test_pdb.py
   python/branches/pep-3151/Lib/test/test_pep247.py
   python/branches/pep-3151/Lib/test/test_pep263.py
   python/branches/pep-3151/Lib/test/test_pep3120.py
   python/branches/pep-3151/Lib/test/test_pep3131.py
   python/branches/pep-3151/Lib/test/test_pickle.py
   python/branches/pep-3151/Lib/test/test_pickletools.py
   python/branches/pep-3151/Lib/test/test_platform.py
   python/branches/pep-3151/Lib/test/test_poplib.py
   python/branches/pep-3151/Lib/test/test_posix.py
   python/branches/pep-3151/Lib/test/test_posixpath.py
   python/branches/pep-3151/Lib/test/test_pow.py
   python/branches/pep-3151/Lib/test/test_pty.py
   python/branches/pep-3151/Lib/test/test_pyclbr.py
   python/branches/pep-3151/Lib/test/test_pydoc.py
   python/branches/pep-3151/Lib/test/test_pyexpat.py
   python/branches/pep-3151/Lib/test/test_queue.py
   python/branches/pep-3151/Lib/test/test_random.py
   python/branches/pep-3151/Lib/test/test_range.py
   python/branches/pep-3151/Lib/test/test_reprlib.py
   python/branches/pep-3151/Lib/test/test_resource.py
   python/branches/pep-3151/Lib/test/test_richcmp.py
   python/branches/pep-3151/Lib/test/test_runpy.py
   python/branches/pep-3151/Lib/test/test_sax.py
   python/branches/pep-3151/Lib/test/test_scope.py
   python/branches/pep-3151/Lib/test/test_shelve.py
   python/branches/pep-3151/Lib/test/test_shutil.py
   python/branches/pep-3151/Lib/test/test_signal.py
   python/branches/pep-3151/Lib/test/test_site.py
   python/branches/pep-3151/Lib/test/test_slice.py
   python/branches/pep-3151/Lib/test/test_smtpd.py
   python/branches/pep-3151/Lib/test/test_smtplib.py
   python/branches/pep-3151/Lib/test/test_socket.py
   python/branches/pep-3151/Lib/test/test_socketserver.py
   python/branches/pep-3151/Lib/test/test_ssl.py
   python/branches/pep-3151/Lib/test/test_strlit.py
   python/branches/pep-3151/Lib/test/test_struct.py
   python/branches/pep-3151/Lib/test/test_structmembers.py
   python/branches/pep-3151/Lib/test/test_subprocess.py
   python/branches/pep-3151/Lib/test/test_sys.py
   python/branches/pep-3151/Lib/test/test_sys_settrace.py
   python/branches/pep-3151/Lib/test/test_sysconfig.py
   python/branches/pep-3151/Lib/test/test_syslog.py
   python/branches/pep-3151/Lib/test/test_tarfile.py
   python/branches/pep-3151/Lib/test/test_telnetlib.py
   python/branches/pep-3151/Lib/test/test_tempfile.py
   python/branches/pep-3151/Lib/test/test_textwrap.py
   python/branches/pep-3151/Lib/test/test_threadedtempfile.py
   python/branches/pep-3151/Lib/test/test_threading.py
   python/branches/pep-3151/Lib/test/test_threadsignals.py
   python/branches/pep-3151/Lib/test/test_time.py
   python/branches/pep-3151/Lib/test/test_timeout.py
   python/branches/pep-3151/Lib/test/test_tokenize.py
   python/branches/pep-3151/Lib/test/test_trace.py
   python/branches/pep-3151/Lib/test/test_traceback.py
   python/branches/pep-3151/Lib/test/test_ttk_guionly.py
   python/branches/pep-3151/Lib/test/test_tuple.py
   python/branches/pep-3151/Lib/test/test_types.py
   python/branches/pep-3151/Lib/test/test_ucn.py
   python/branches/pep-3151/Lib/test/test_unicode.py
   python/branches/pep-3151/Lib/test/test_unicodedata.py
   python/branches/pep-3151/Lib/test/test_unittest.py
   python/branches/pep-3151/Lib/test/test_urllib.py
   python/branches/pep-3151/Lib/test/test_urllib2.py
   python/branches/pep-3151/Lib/test/test_urllibnet.py
   python/branches/pep-3151/Lib/test/test_urlparse.py
   python/branches/pep-3151/Lib/test/test_uuid.py
   python/branches/pep-3151/Lib/test/test_warnings.py
   python/branches/pep-3151/Lib/test/test_weakset.py
   python/branches/pep-3151/Lib/test/test_winreg.py
   python/branches/pep-3151/Lib/test/test_winsound.py
   python/branches/pep-3151/Lib/test/test_with.py
   python/branches/pep-3151/Lib/test/test_wsgiref.py
   python/branches/pep-3151/Lib/test/test_xml_etree.py
   python/branches/pep-3151/Lib/test/test_xml_etree_c.py
   python/branches/pep-3151/Lib/test/test_xmlrpc.py
   python/branches/pep-3151/Lib/test/test_xmlrpc_net.py
   python/branches/pep-3151/Lib/test/test_zipfile.py
   python/branches/pep-3151/Lib/test/test_zipimport.py
   python/branches/pep-3151/Lib/test/test_zipimport_support.py
   python/branches/pep-3151/Lib/test/test_zlib.py
   python/branches/pep-3151/Lib/test/win_console_handler.py
   python/branches/pep-3151/Lib/threading.py
   python/branches/pep-3151/Lib/tkinter/__init__.py
   python/branches/pep-3151/Lib/tkinter/scrolledtext.py
   python/branches/pep-3151/Lib/tkinter/test/test_tkinter/test_loadtk.py
   python/branches/pep-3151/Lib/tkinter/test/test_ttk/test_widgets.py
   python/branches/pep-3151/Lib/tkinter/tix.py
   python/branches/pep-3151/Lib/token.py
   python/branches/pep-3151/Lib/tokenize.py
   python/branches/pep-3151/Lib/trace.py
   python/branches/pep-3151/Lib/turtle.py
   python/branches/pep-3151/Lib/turtledemo/about_turtledemo.txt
   python/branches/pep-3151/Lib/turtledemo/demohelp.txt
   python/branches/pep-3151/Lib/unittest/case.py
   python/branches/pep-3151/Lib/unittest/loader.py
   python/branches/pep-3151/Lib/unittest/main.py
   python/branches/pep-3151/Lib/unittest/runner.py
   python/branches/pep-3151/Lib/unittest/suite.py
   python/branches/pep-3151/Lib/unittest/test/test_assertions.py
   python/branches/pep-3151/Lib/unittest/test/test_break.py
   python/branches/pep-3151/Lib/unittest/test/test_case.py
   python/branches/pep-3151/Lib/unittest/test/test_discovery.py
   python/branches/pep-3151/Lib/unittest/test/test_functiontestcase.py
   python/branches/pep-3151/Lib/unittest/test/test_loader.py
   python/branches/pep-3151/Lib/unittest/test/test_program.py
   python/branches/pep-3151/Lib/unittest/test/test_runner.py
   python/branches/pep-3151/Lib/unittest/test/test_setups.py
   python/branches/pep-3151/Lib/unittest/test/test_suite.py
   python/branches/pep-3151/Lib/unittest/util.py
   python/branches/pep-3151/Lib/urllib/parse.py
   python/branches/pep-3151/Lib/urllib/request.py
   python/branches/pep-3151/Lib/wave.py
   python/branches/pep-3151/Lib/weakref.py
   python/branches/pep-3151/Lib/webbrowser.py
   python/branches/pep-3151/Lib/wsgiref/handlers.py
   python/branches/pep-3151/Lib/wsgiref/util.py
   python/branches/pep-3151/Lib/xml/etree/ElementTree.py
   python/branches/pep-3151/Lib/xmlrpc/client.py
   python/branches/pep-3151/Lib/zipfile.py
   python/branches/pep-3151/Mac/BuildScript/README.txt
   python/branches/pep-3151/Mac/BuildScript/build-installer.py
   python/branches/pep-3151/Mac/BuildScript/resources/ReadMe.txt
   python/branches/pep-3151/Mac/BuildScript/resources/Welcome.rtf
   python/branches/pep-3151/Mac/BuildScript/scripts/postflight.documentation
   python/branches/pep-3151/Mac/IDLE/IDLE.app/Contents/Info.plist
   python/branches/pep-3151/Mac/Makefile.in
   python/branches/pep-3151/Mac/PythonLauncher/Info.plist.in
   python/branches/pep-3151/Mac/README
   python/branches/pep-3151/Mac/Resources/app/Info.plist.in
   python/branches/pep-3151/Mac/Resources/framework/Info.plist.in
   python/branches/pep-3151/Makefile.pre.in
   python/branches/pep-3151/Misc/ACKS
   python/branches/pep-3151/Misc/NEWS
   python/branches/pep-3151/Misc/README
   python/branches/pep-3151/Misc/SpecialBuilds.txt
   python/branches/pep-3151/Misc/indent.pro
   python/branches/pep-3151/Misc/python-wing4.wpr
   python/branches/pep-3151/Misc/python.man
   python/branches/pep-3151/Misc/python.pc.in
   python/branches/pep-3151/Modules/Setup.dist
   python/branches/pep-3151/Modules/_collectionsmodule.c
   python/branches/pep-3151/Modules/_ctypes/_ctypes.c
   python/branches/pep-3151/Modules/_ctypes/_ctypes_test.c
   python/branches/pep-3151/Modules/_ctypes/cfield.c
   python/branches/pep-3151/Modules/_ctypes/libffi_msvc/ffi.c
   python/branches/pep-3151/Modules/_datetimemodule.c
   python/branches/pep-3151/Modules/_elementtree.c
   python/branches/pep-3151/Modules/_functoolsmodule.c
   python/branches/pep-3151/Modules/_gdbmmodule.c
   python/branches/pep-3151/Modules/_io/bufferedio.c
   python/branches/pep-3151/Modules/_io/bytesio.c
   python/branches/pep-3151/Modules/_io/fileio.c
   python/branches/pep-3151/Modules/_io/textio.c
   python/branches/pep-3151/Modules/_json.c
   python/branches/pep-3151/Modules/_lsprof.c
   python/branches/pep-3151/Modules/_multiprocessing/multiprocessing.h
   python/branches/pep-3151/Modules/_pickle.c
   python/branches/pep-3151/Modules/_posixsubprocess.c
   python/branches/pep-3151/Modules/_sqlite/connection.c
   python/branches/pep-3151/Modules/_sqlite/cursor.c
   python/branches/pep-3151/Modules/_sqlite/module.c
   python/branches/pep-3151/Modules/_sqlite/statement.c
   python/branches/pep-3151/Modules/_ssl.c
   python/branches/pep-3151/Modules/_struct.c
   python/branches/pep-3151/Modules/_testcapimodule.c
   python/branches/pep-3151/Modules/_threadmodule.c
   python/branches/pep-3151/Modules/_tkinter.c
   python/branches/pep-3151/Modules/arraymodule.c
   python/branches/pep-3151/Modules/atexitmodule.c
   python/branches/pep-3151/Modules/audioop.c
   python/branches/pep-3151/Modules/cjkcodecs/_codecs_iso2022.c
   python/branches/pep-3151/Modules/cjkcodecs/multibytecodec.c
   python/branches/pep-3151/Modules/gcmodule.c
   python/branches/pep-3151/Modules/getpath.c
   python/branches/pep-3151/Modules/grpmodule.c
   python/branches/pep-3151/Modules/itertoolsmodule.c
   python/branches/pep-3151/Modules/ld_so_aix.in
   python/branches/pep-3151/Modules/main.c
   python/branches/pep-3151/Modules/md5module.c
   python/branches/pep-3151/Modules/mmapmodule.c
   python/branches/pep-3151/Modules/parsermodule.c
   python/branches/pep-3151/Modules/posixmodule.c
   python/branches/pep-3151/Modules/pwdmodule.c
   python/branches/pep-3151/Modules/pyexpat.c
   python/branches/pep-3151/Modules/readline.c
   python/branches/pep-3151/Modules/resource.c
   python/branches/pep-3151/Modules/selectmodule.c
   python/branches/pep-3151/Modules/sha1module.c
   python/branches/pep-3151/Modules/sha256module.c
   python/branches/pep-3151/Modules/sha512module.c
   python/branches/pep-3151/Modules/signalmodule.c
   python/branches/pep-3151/Modules/socketmodule.c
   python/branches/pep-3151/Modules/socketmodule.h
   python/branches/pep-3151/Modules/spwdmodule.c
   python/branches/pep-3151/Modules/symtablemodule.c
   python/branches/pep-3151/Modules/syslogmodule.c
   python/branches/pep-3151/Modules/termios.c
   python/branches/pep-3151/Modules/timemodule.c
   python/branches/pep-3151/Modules/unicodedata.c
   python/branches/pep-3151/Modules/zipimport.c
   python/branches/pep-3151/Modules/zlibmodule.c
   python/branches/pep-3151/Objects/abstract.c
   python/branches/pep-3151/Objects/bytearrayobject.c
   python/branches/pep-3151/Objects/bytesobject.c
   python/branches/pep-3151/Objects/codeobject.c
   python/branches/pep-3151/Objects/complexobject.c
   python/branches/pep-3151/Objects/descrobject.c
   python/branches/pep-3151/Objects/dictobject.c
   python/branches/pep-3151/Objects/fileobject.c
   python/branches/pep-3151/Objects/floatobject.c
   python/branches/pep-3151/Objects/funcobject.c
   python/branches/pep-3151/Objects/genobject.c
   python/branches/pep-3151/Objects/listobject.c
   python/branches/pep-3151/Objects/longobject.c
   python/branches/pep-3151/Objects/memoryobject.c
   python/branches/pep-3151/Objects/moduleobject.c
   python/branches/pep-3151/Objects/object.c
   python/branches/pep-3151/Objects/obmalloc.c
   python/branches/pep-3151/Objects/rangeobject.c
   python/branches/pep-3151/Objects/setobject.c
   python/branches/pep-3151/Objects/sliceobject.c
   python/branches/pep-3151/Objects/stringlib/formatter.h
   python/branches/pep-3151/Objects/stringlib/string_format.h
   python/branches/pep-3151/Objects/structseq.c
   python/branches/pep-3151/Objects/tupleobject.c
   python/branches/pep-3151/Objects/typeobject.c
   python/branches/pep-3151/Objects/unicodectype.c
   python/branches/pep-3151/Objects/unicodeobject.c
   python/branches/pep-3151/Objects/weakrefobject.c
   python/branches/pep-3151/PC/   (props changed)
   python/branches/pep-3151/PC/VC6/pythoncore.dsp
   python/branches/pep-3151/PC/VC6/readme.txt
   python/branches/pep-3151/PC/VS7.1/build_ssl.bat   (contents, props changed)
   python/branches/pep-3151/PC/VS7.1/pythoncore.vcproj
   python/branches/pep-3151/PC/VS7.1/readme.txt
   python/branches/pep-3151/PC/VS8.0/build.bat   (contents, props changed)
   python/branches/pep-3151/PC/VS8.0/build_env.bat   (contents, props changed)
   python/branches/pep-3151/PC/VS8.0/build_pgo.bat   (contents, props changed)
   python/branches/pep-3151/PC/VS8.0/build_ssl.bat   (contents, props changed)
   python/branches/pep-3151/PC/VS8.0/env.bat   (contents, props changed)
   python/branches/pep-3151/PC/VS8.0/idle.bat   (contents, props changed)
   python/branches/pep-3151/PC/VS8.0/kill_python.c
   python/branches/pep-3151/PC/VS8.0/pyproject.vsprops
   python/branches/pep-3151/PC/VS8.0/rt.bat   (contents, props changed)
   python/branches/pep-3151/PC/bdist_wininst/wininst.dsp   (contents, props changed)
   python/branches/pep-3151/PC/bdist_wininst/wininst.dsw   (contents, props changed)
   python/branches/pep-3151/PC/example_nt/example.vcproj
   python/branches/pep-3151/PC/getpathp.c
   python/branches/pep-3151/PC/import_nt.c
   python/branches/pep-3151/PC/os2emx/Makefile
   python/branches/pep-3151/PC/os2emx/README.os2emx
   python/branches/pep-3151/PC/pyconfig.h
   python/branches/pep-3151/PC/python_nt.rc
   python/branches/pep-3151/PCbuild/build_ssl.bat
   python/branches/pep-3151/PCbuild/build_tkinter.py
   python/branches/pep-3151/PCbuild/kill_python.c
   python/branches/pep-3151/PCbuild/make_buildinfo.c
   python/branches/pep-3151/PCbuild/pcbuild.sln
   python/branches/pep-3151/PCbuild/pyproject.vsprops
   python/branches/pep-3151/PCbuild/pythoncore.vcproj
   python/branches/pep-3151/PCbuild/readme.txt
   python/branches/pep-3151/Parser/asdl_c.py
   python/branches/pep-3151/Parser/parsetok.c
   python/branches/pep-3151/Parser/pgenmain.c
   python/branches/pep-3151/Parser/printgrammar.c
   python/branches/pep-3151/Parser/tokenizer.c
   python/branches/pep-3151/Python/Python-ast.c
   python/branches/pep-3151/Python/_warnings.c
   python/branches/pep-3151/Python/ast.c
   python/branches/pep-3151/Python/bltinmodule.c
   python/branches/pep-3151/Python/ceval.c
   python/branches/pep-3151/Python/ceval_gil.h
   python/branches/pep-3151/Python/compile.c
   python/branches/pep-3151/Python/dtoa.c
   python/branches/pep-3151/Python/dynload_aix.c
   python/branches/pep-3151/Python/dynload_dl.c
   python/branches/pep-3151/Python/dynload_hpux.c
   python/branches/pep-3151/Python/dynload_next.c
   python/branches/pep-3151/Python/dynload_os2.c
   python/branches/pep-3151/Python/dynload_shlib.c
   python/branches/pep-3151/Python/dynload_win.c
   python/branches/pep-3151/Python/errors.c
   python/branches/pep-3151/Python/future.c
   python/branches/pep-3151/Python/getargs.c
   python/branches/pep-3151/Python/getcopyright.c
   python/branches/pep-3151/Python/import.c
   python/branches/pep-3151/Python/importdl.c
   python/branches/pep-3151/Python/peephole.c
   python/branches/pep-3151/Python/pyarena.c
   python/branches/pep-3151/Python/pystrtod.c
   python/branches/pep-3151/Python/pythonrun.c
   python/branches/pep-3151/Python/sysmodule.c
   python/branches/pep-3151/Python/thread_nt.h
   python/branches/pep-3151/Python/thread_pthread.h
   python/branches/pep-3151/Python/traceback.c
   python/branches/pep-3151/README
   python/branches/pep-3151/Tools/README
   python/branches/pep-3151/Tools/buildbot/build-amd64.bat   (contents, props changed)
   python/branches/pep-3151/Tools/buildbot/build.bat   (contents, props changed)
   python/branches/pep-3151/Tools/buildbot/buildmsi.bat   (contents, props changed)
   python/branches/pep-3151/Tools/buildbot/clean-amd64.bat   (contents, props changed)
   python/branches/pep-3151/Tools/buildbot/clean.bat   (contents, props changed)
   python/branches/pep-3151/Tools/buildbot/external-amd64.bat   (contents, props changed)
   python/branches/pep-3151/Tools/buildbot/external-common.bat   (contents, props changed)
   python/branches/pep-3151/Tools/buildbot/external.bat   (contents, props changed)
   python/branches/pep-3151/Tools/buildbot/test-amd64.bat   (contents, props changed)
   python/branches/pep-3151/Tools/buildbot/test.bat   (contents, props changed)
   python/branches/pep-3151/Tools/ccbench/ccbench.py
   python/branches/pep-3151/Tools/msi/msi.py
   python/branches/pep-3151/Tools/msi/uuids.py
   python/branches/pep-3151/Tools/scripts/README
   python/branches/pep-3151/Tools/scripts/find_recursionlimit.py
   python/branches/pep-3151/Tools/scripts/patchcheck.py
   python/branches/pep-3151/Tools/scripts/untabify.py
   python/branches/pep-3151/Tools/unicode/gencodec.py
   python/branches/pep-3151/Tools/unicode/genwincodecs.bat   (contents, props changed)
   python/branches/pep-3151/Tools/unicode/makeunicodedata.py
   python/branches/pep-3151/configure
   python/branches/pep-3151/configure.in
   python/branches/pep-3151/pyconfig.h.in
   python/branches/pep-3151/setup.py

Modified: python/branches/pep-3151/.gitignore
==============================================================================
--- python/branches/pep-3151/.gitignore	(original)
+++ python/branches/pep-3151/.gitignore	Sat Feb 26 08:16:32 2011
@@ -1,8 +1,17 @@
+*.cover
+*.o
+*.orig
+*.pyc
+*.pyd
+*.pyo
+*.rej
+*~
 Doc/build/
 Doc/tools/docutils/
 Doc/tools/jinja2/
 Doc/tools/pygments/
 Doc/tools/sphinx/
+Lib/lib2to3/*.pickle
 Makefile
 Makefile.pre
 Misc/python.pc
@@ -10,17 +19,26 @@
 Modules/Setup.config
 Modules/Setup.local
 Modules/config.c
+Modules/ld_so_aix
+PCbuild/*.bsc
+PCbuild/*.dll
+PCbuild/*.exe
+PCbuild/*.exp
+PCbuild/*.lib
+PCbuild/*.ncb
+PCbuild/*.o
+PCbuild/*.pdb
+PCbuild/Win32-temp-*
 Parser/pgen
 Parser/pgen.stamp
+__pycache__
+autom4te.cache
 build/
 config.log
 config.status
-libpython3.2.a
+libpython*.a
 pybuilddir.txt
 pyconfig.h
 python
 python-gdb.py
 tags
-Lib/lib2to3/Grammar3.2.0.alpha.2.pickle
-Lib/lib2to3/PatternGrammar3.2.0.alpha.2.pickle
-autom4te.cache

Modified: python/branches/pep-3151/.hgeol
==============================================================================
--- python/branches/pep-3151/.hgeol	(original)
+++ python/branches/pep-3151/.hgeol	Sat Feb 26 08:16:32 2011
@@ -1,16 +1,13 @@
 [patterns]
-** = native
 
-**.bat  = CRLF
-**.def  = CRLF
-**.dsp  = CRLF
-**.dsw  = CRLF
-**.mak  = CRLF
-**.mk   = CRLF
-**.rc   = CRLF
-**.sln  = CRLF
-**.vcproj  = CRLF
-**.vsprops = CRLF
+# Non human-editable files are binary
+
+**.dsp  = BIN
+**.dsw  = BIN
+**.mk   = BIN
+**.sln  = BIN
+**.vcproj  = BIN
+**.vsprops = BIN
 
 **.aif  = BIN
 **.au   = BIN
@@ -31,6 +28,12 @@
 
 Lib/email/test/data/msg_26.txt = BIN
 Lib/test/sndhdrdata/sndhdr.* = BIN
+Lib/test/decimaltestdata/*.decTest = BIN
+
+# All other files (which presumably are human-editable) are "native".
+# This must be the last rule!
+
+** = native
 
 [repository]
-native = LF
\ No newline at end of file
+native = LF

Modified: python/branches/pep-3151/.hgignore
==============================================================================
--- python/branches/pep-3151/.hgignore	(original)
+++ python/branches/pep-3151/.hgignore	Sat Feb 26 08:16:32 2011
@@ -34,10 +34,12 @@
 Parser/pgen.stamp$
 ^core
 ^python-gdb.py
+^python.exe-gdb.py
 ^pybuilddir.txt
 
 syntax: glob
 libpython*.a
+*.swp
 *.o
 *.pyc
 *.pyo

Modified: python/branches/pep-3151/Doc/ACKS.txt
==============================================================================
--- python/branches/pep-3151/Doc/ACKS.txt	(original)
+++ python/branches/pep-3151/Doc/ACKS.txt	Sat Feb 26 08:16:32 2011
@@ -47,6 +47,7 @@
    * L. Peter Deutsch
    * Robert Donohue
    * Fred L. Drake, Jr.
+   * Jacques Ducasse
    * Josip Dzolonga
    * Jeff Epler
    * Michael Ernst
@@ -111,6 +112,7 @@
    * Andrew M. Kuchling
    * Dave Kuhlman
    * Erno Kuusela
+   * Ross Lagerwall
    * Thomas Lamb
    * Detlef Lannert
    * Piers Lauder
@@ -128,6 +130,7 @@
    * Andrew MacIntyre
    * Vladimir Marangozov
    * Vincent Marchetti
+   * Westley Martínez
    * Laura Matson
    * Daniel May
    * Rebecca McCreary
@@ -138,6 +141,7 @@
    * Ross Moore
    * Sjoerd Mullender
    * Dale Nagata
+   * Michal Nowikowski 
    * Ng Pheng Siong
    * Koray Oner
    * Tomas Oppelstrup
@@ -178,6 +182,7 @@
    * Joakim Sernbrant
    * Justin Sheehy
    * Charlie Shepherd
+   * SilentGhost
    * Michael Simcich
    * Ionel Simionescu
    * Michael Sloan

Modified: python/branches/pep-3151/Doc/Makefile
==============================================================================
--- python/branches/pep-3151/Doc/Makefile	(original)
+++ python/branches/pep-3151/Doc/Makefile	Sat Feb 26 08:16:32 2011
@@ -26,6 +26,7 @@
 	@echo "  htmlhelp   to make HTML files and a HTML help project"
 	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
 	@echo "  text       to make plain text files"
+	@echo "  epub       to make EPUB files"
 	@echo "  changes    to make an overview over all changed/added/deprecated items"
 	@echo "  linkcheck  to check all external links for integrity"
 	@echo "  coverage   to check documentation coverage for library and C API"
@@ -40,7 +41,7 @@
 checkout:
 	@if [ ! -d tools/sphinx ]; then \
 	  echo "Checking out Sphinx..."; \
-	  svn checkout $(SVNROOT)/external/Sphinx-1.0.4/sphinx tools/sphinx; \
+	  svn checkout $(SVNROOT)/external/Sphinx-1.0.7/sphinx tools/sphinx; \
 	fi
 	@if [ ! -d tools/docutils ]; then \
 	  echo "Checking out Docutils..."; \
@@ -81,6 +82,10 @@
 text: build
 	@echo "Build finished; the text files are in build/text."
 
+epub: BUILDER = epub
+epub: build
+	@echo "Build finished; the epub files are in build/epub."
+
 changes: BUILDER = changes
 changes: build
 	@echo "The overview file is in build/changes."
@@ -158,6 +163,17 @@
 	cp build/latex/docs-pdf.zip dist/python-$(DISTVERSION)-docs-pdf-letter.zip
 	cp build/latex/docs-pdf.tar.bz2 dist/python-$(DISTVERSION)-docs-pdf-letter.tar.bz2
 
+	# archive the epub build
+	rm -rf build/epub
+	make epub
+	mkdir -p dist/python-$(DISTVERSION)-docs-epub
+	cp -pPR build/epub/*.epub dist/python-$(DISTVERSION)-docs-epub/
+	tar -C dist -cf dist/python-$(DISTVERSION)-docs-epub.tar python-$(DISTVERSION)-docs-epub
+	bzip2 -9 -k dist/python-$(DISTVERSION)-docs-epub.tar
+	(cd dist; zip -q -r -9 python-$(DISTVERSION)-docs-epub.zip python-$(DISTVERSION)-docs-epub)
+	rm -r dist/python-$(DISTVERSION)-docs-epub
+	rm dist/python-$(DISTVERSION)-docs-epub.tar
+
 check:
 	$(PYTHON) tools/rstlint.py -i tools
 

Modified: python/branches/pep-3151/Doc/README.txt
==============================================================================
--- python/branches/pep-3151/Doc/README.txt	(original)
+++ python/branches/pep-3151/Doc/README.txt	Sat Feb 26 08:16:32 2011
@@ -54,6 +54,9 @@
 
  * "text", which builds a plain text file for each source file.
 
+ * "epub", which builds an EPUB document, suitable to be viewed on e-book
+   readers.
+
  * "linkcheck", which checks all external references to see whether they are
    broken, redirected or malformed, and outputs this information to stdout as
    well as a plain-text (.txt) file.
@@ -78,7 +81,7 @@
 
 You'll need to install the Sphinx package, either by checking it out via ::
 
-   svn co http://svn.python.org/projects/external/Sphinx-1.0.4/sphinx tools/sphinx
+   svn co http://svn.python.org/projects/external/Sphinx-1.0.7/sphinx tools/sphinx
 
 or by installing it from PyPI.
 
@@ -132,7 +135,7 @@
 as long as you don't change or remove the copyright notice:
 
 ----------------------------------------------------------------------
-Copyright (c) 2000-2010 Python Software Foundation.
+Copyright (c) 2000-2011 Python Software Foundation.
 All rights reserved.
 
 Copyright (c) 2000 BeOpen.com.

Modified: python/branches/pep-3151/Doc/c-api/arg.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/arg.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/arg.rst	Sat Feb 26 08:16:32 2011
@@ -30,9 +30,10 @@
 Strings and buffers
 -------------------
 
-These formats do not expect you to provide raw storage for the returned string
-or bytes.  Also, you won't have to release any memory yourself, except with
-the ``es``, ``es#``, ``et`` and ``et#`` formats.
+These formats allow to access an object as a contiguous chunk of memory.
+You don't have to provide raw storage for the returned unicode or bytes
+area.  Also, you won't have to release any memory yourself, except with the
+``es``, ``es#``, ``et`` and ``et#`` formats.
 
 However, when a :c:type:`Py_buffer` structure gets filled, the underlying
 buffer is locked so that the caller can subsequently use the buffer even

Modified: python/branches/pep-3151/Doc/c-api/buffer.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/buffer.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/buffer.rst	Sat Feb 26 08:16:32 2011
@@ -12,16 +12,32 @@
 .. index::
    single: buffer interface
 
-Python objects implemented in C can export a "buffer interface."  These
-functions can be used by an object to expose its data in a raw, byte-oriented
-format. Clients of the object can use the buffer interface to access the
-object data directly, without needing to copy it first.
-
-Examples of objects that support the buffer interface are :class:`bytes`,
-:class:`bytearray` and :class:`array.array`. The bytes and bytearray objects
-exposes their bytes contents in the buffer interface's byte-oriented form.
-An :class:`array.array` can also expose its contents, but it should be noted
-that array elements may be multi-byte values.
+Certain objects available in Python wrap access to an underlying memory
+array or *buffer*.  Such objects include the built-in :class:`bytes` and
+:class:`bytearray`, and some extension types like :class:`array.array`.
+Third-party libraries may define their own types for special purposes, such
+as image processing or numeric analysis.
+
+While each of these types have their own semantics, they share the common
+characteristic of being backed by a possibly large memory buffer.  It is
+then desireable, in some situations, to access that buffer directly and
+without intermediate copying.
+
+Python provides such a facility at the C level in the form of the *buffer
+protocol*.  This protocol has two sides:
+
+.. index:: single: PyBufferProcs
+
+- on the producer side, a type can export a "buffer interface" which allows
+  objects of that type to expose information about their underlying buffer.
+  This interface is described in the section :ref:`buffer-structs`;
+
+- on the consumer side, several means are available to obtain a pointer to
+  the raw underlying data of an object (for example a method parameter).
+
+Simple objects such as :class:`bytes` and :class:`bytearray` expose their
+underlying buffer in byte-oriented form.  Other forms are possible; for example,
+the elements exposed by a :class:`array.array` can be multi-byte values.
 
 An example consumer of the buffer interface is the :meth:`~io.BufferedIOBase.write`
 method of file objects: any object that can export a series of bytes through
@@ -44,12 +60,6 @@
 resource leaks.
 
 
-.. index:: single: PyBufferProcs
-
-How the buffer interface is exposed by a type object is described in the
-section :ref:`buffer-structs`, under the description for :c:type:`PyBufferProcs`.
-
-
 The buffer structure
 ====================
 

Modified: python/branches/pep-3151/Doc/c-api/code.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/code.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/code.rst	Sat Feb 26 08:16:32 2011
@@ -47,4 +47,4 @@
 
    Return a new empty code object with the specified filename,
    function name, and first line number.  It is illegal to
-   :keyword:`exec` or :func:`eval` the resulting code object.
+   :func:`exec` or :func:`eval` the resulting code object.

Modified: python/branches/pep-3151/Doc/c-api/exceptions.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/exceptions.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/exceptions.rst	Sat Feb 26 08:16:32 2011
@@ -145,79 +145,11 @@
 
 .. c:function:: PyObject* PyErr_Format(PyObject *exception, const char *format, ...)
 
-   This function sets the error indicator and returns *NULL*. *exception* should be
-   a Python exception (class, not an instance). *format* should be an ASCII-encoded string,
-   containing format codes, similar to :c:func:`printf`. The ``width.precision``
-   before a format code is parsed, but the width part is ignored.
-
-   .. % This should be exactly the same as the table in PyString_FromFormat.
-   .. % One should just refer to the other.
-   .. % The descriptions for %zd and %zu are wrong, but the truth is complicated
-   .. % because not all compilers support the %z width modifier -- we fake it
-   .. % when necessary via interpolating PY_FORMAT_SIZE_T.
-   .. % Similar comments apply to the %ll width modifier and
-   .. % PY_FORMAT_LONG_LONG.
-
-   +-------------------+---------------+--------------------------------+
-   | Format Characters | Type          | Comment                        |
-   +===================+===============+================================+
-   | :attr:`%%`        | *n/a*         | The literal % character.       |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%c`        | int           | A single character,            |
-   |                   |               | represented as an C int.       |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%d`        | int           | Exactly equivalent to          |
-   |                   |               | ``printf("%d")``.              |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%u`        | unsigned int  | Exactly equivalent to          |
-   |                   |               | ``printf("%u")``.              |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%ld`       | long          | Exactly equivalent to          |
-   |                   |               | ``printf("%ld")``.             |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%lu`       | unsigned long | Exactly equivalent to          |
-   |                   |               | ``printf("%lu")``.             |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%lld`      | long long     | Exactly equivalent to          |
-   |                   |               | ``printf("%lld")``.            |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%llu`      | unsigned      | Exactly equivalent to          |
-   |                   | long long     | ``printf("%llu")``.            |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%zd`       | Py_ssize_t    | Exactly equivalent to          |
-   |                   |               | ``printf("%zd")``.             |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%zu`       | size_t        | Exactly equivalent to          |
-   |                   |               | ``printf("%zu")``.             |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%i`        | int           | Exactly equivalent to          |
-   |                   |               | ``printf("%i")``.              |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%x`        | int           | Exactly equivalent to          |
-   |                   |               | ``printf("%x")``.              |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%s`        | char\*        | A null-terminated C character  |
-   |                   |               | array.                         |
-   +-------------------+---------------+--------------------------------+
-   | :attr:`%p`        | void\*        | The hex representation of a C  |
-   |                   |               | pointer. Mostly equivalent to  |
-   |                   |               | ``printf("%p")`` except that   |
-   |                   |               | it is guaranteed to start with |
-   |                   |               | the literal ``0x`` regardless  |
-   |                   |               | of what the platform's         |
-   |                   |               | ``printf`` yields.             |
-   +-------------------+---------------+--------------------------------+
-
-   An unrecognized format character causes all the rest of the format string to be
-   copied as-is to the result string, and any extra arguments discarded.
-
-   .. note::
-
-      The `"%lld"` and `"%llu"` format specifiers are only available
-      when :const:`HAVE_LONG_LONG` is defined.
-
-   .. versionchanged:: 3.2
-      Support for `"%lld"` and `"%llu"` added.
+   This function sets the error indicator and returns *NULL*.  *exception*
+   should be a Python exception class.  The *format* and subsequent
+   parameters help format the error message; they have the same meaning and
+   values as in :c:func:`PyUnicode_FromFormat`. *format* is an ASCII-encoded
+   string.
 
 
 .. c:function:: void PyErr_SetNone(PyObject *type)
@@ -287,7 +219,9 @@
 
    Similar to :c:func:`PyErr_SetFromWindowsErr`, with the additional behavior that
    if *filename* is not *NULL*, it is passed to the constructor of
-   :exc:`WindowsError` as a third parameter. Availability: Windows.
+   :exc:`WindowsError` as a third parameter.  *filename* is decoded from the
+   filesystem encoding (:func:`sys.getfilesystemencoding`).  Availability:
+   Windows.
 
 
 .. c:function:: PyObject* PyErr_SetExcFromWindowsErrWithFilename(PyObject *type, int ierr, char *filename)
@@ -301,7 +235,8 @@
    Set file, line, and offset information for the current exception.  If the
    current exception is not a :exc:`SyntaxError`, then it sets additional
    attributes, which make the exception printing subsystem think the exception
-   is a :exc:`SyntaxError`.
+   is a :exc:`SyntaxError`. *filename* is decoded from the filesystem encoding
+   (:func:`sys.getfilesystemencoding`).
 
 .. versionadded:: 3.2
 
@@ -323,7 +258,7 @@
 .. c:function:: int PyErr_WarnEx(PyObject *category, char *message, int stack_level)
 
    Issue a warning message.  The *category* argument is a warning category (see
-   below) or *NULL*; the *message* argument is a message string.  *stack_level* is a
+   below) or *NULL*; the *message* argument is an UTF-8 encoded string.  *stack_level* is a
    positive number giving a number of stack frames; the warning will be issued from
    the  currently executing line of code in that stack frame.  A *stack_level* of 1
    is the function calling :c:func:`PyErr_WarnEx`, 2 is  the function above that,
@@ -363,13 +298,16 @@
    is a straightforward wrapper around the Python function
    :func:`warnings.warn_explicit`, see there for more information.  The *module*
    and *registry* arguments may be set to *NULL* to get the default effect
-   described there.
+   described there. *message* and *module* are UTF-8 encoded strings,
+   *filename* is decoded from the filesystem encoding
+   (:func:`sys.getfilesystemencoding`).
 
 
 .. c:function:: int PyErr_WarnFormat(PyObject *category, Py_ssize_t stack_level, const char *format, ...)
 
    Function similar to :c:func:`PyErr_WarnEx`, but use
-   :c:func:`PyUnicode_FromFormatV` to format the warning message.
+   :c:func:`PyUnicode_FromFormat` to format the warning message.  *format* is
+   an ASCII-encoded string.
 
    .. versionadded:: 3.2
 
@@ -496,6 +434,85 @@
    This steals a reference to *ctx*.
 
 
+.. _unicodeexceptions:
+
+Unicode Exception Objects
+=========================
+
+The following functions are used to create and modify Unicode exceptions from C.
+
+.. c:function:: PyObject* PyUnicodeDecodeError_Create(const char *encoding, const char *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
+
+   Create a :class:`UnicodeDecodeError` object with the attributes *encoding*,
+   *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
+   UTF-8 encoded strings.
+
+.. c:function:: PyObject* PyUnicodeEncodeError_Create(const char *encoding, const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
+
+   Create a :class:`UnicodeEncodeError` object with the attributes *encoding*,
+   *object*, *length*, *start*, *end* and *reason*. *encoding* and *reason* are
+   UTF-8 encoded strings.
+
+.. c:function:: PyObject* PyUnicodeTranslateError_Create(const Py_UNICODE *object, Py_ssize_t length, Py_ssize_t start, Py_ssize_t end, const char *reason)
+
+   Create a :class:`UnicodeTranslateError` object with the attributes *object*,
+   *length*, *start*, *end* and *reason*. *reason* is an UTF-8 encoded string.
+
+.. c:function:: PyObject* PyUnicodeDecodeError_GetEncoding(PyObject *exc)
+                PyObject* PyUnicodeEncodeError_GetEncoding(PyObject *exc)
+
+   Return the *encoding* attribute of the given exception object.
+
+.. c:function:: PyObject* PyUnicodeDecodeError_GetObject(PyObject *exc)
+                PyObject* PyUnicodeEncodeError_GetObject(PyObject *exc)
+                PyObject* PyUnicodeTranslateError_GetObject(PyObject *exc)
+
+   Return the *object* attribute of the given exception object.
+
+.. c:function:: int PyUnicodeDecodeError_GetStart(PyObject *exc, Py_ssize_t *start)
+                int PyUnicodeEncodeError_GetStart(PyObject *exc, Py_ssize_t *start)
+                int PyUnicodeTranslateError_GetStart(PyObject *exc, Py_ssize_t *start)
+
+   Get the *start* attribute of the given exception object and place it into
+   *\*start*.  *start* must not be *NULL*.  Return ``0`` on success, ``-1`` on
+   failure.
+
+.. c:function:: int PyUnicodeDecodeError_SetStart(PyObject *exc, Py_ssize_t start)
+                int PyUnicodeEncodeError_SetStart(PyObject *exc, Py_ssize_t start)
+                int PyUnicodeTranslateError_SetStart(PyObject *exc, Py_ssize_t start)
+
+   Set the *start* attribute of the given exception object to *start*.  Return
+   ``0`` on success, ``-1`` on failure.
+
+.. c:function:: int PyUnicodeDecodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
+                int PyUnicodeEncodeError_GetEnd(PyObject *exc, Py_ssize_t *end)
+                int PyUnicodeTranslateError_GetEnd(PyObject *exc, Py_ssize_t *end)
+
+   Get the *end* attribute of the given exception object and place it into
+   *\*end*.  *end* must not be *NULL*.  Return ``0`` on success, ``-1`` on
+   failure.
+
+.. c:function:: int PyUnicodeDecodeError_SetEnd(PyObject *exc, Py_ssize_t end)
+                int PyUnicodeEncodeError_SetEnd(PyObject *exc, Py_ssize_t end)
+                int PyUnicodeTranslateError_SetEnd(PyObject *exc, Py_ssize_t end)
+
+   Set the *end* attribute of the given exception object to *end*.  Return ``0``
+   on success, ``-1`` on failure.
+
+.. c:function:: PyObject* PyUnicodeDecodeError_GetReason(PyObject *exc)
+                PyObject* PyUnicodeEncodeError_GetReason(PyObject *exc)
+                PyObject* PyUnicodeTranslateError_GetReason(PyObject *exc)
+
+   Return the *reason* attribute of the given exception object.
+
+.. c:function:: int PyUnicodeDecodeError_SetReason(PyObject *exc, const char *reason)
+                int PyUnicodeEncodeError_SetReason(PyObject *exc, const char *reason)
+                int PyUnicodeTranslateError_SetReason(PyObject *exc, const char *reason)
+
+   Set the *reason* attribute of the given exception object to *reason*.  Return
+   ``0`` on success, ``-1`` on failure.
+
+
 Recursion Control
 =================
 
@@ -525,6 +542,35 @@
    Ends a :c:func:`Py_EnterRecursiveCall`.  Must be called once for each
    *successful* invocation of :c:func:`Py_EnterRecursiveCall`.
 
+Properly implementing :attr:`tp_repr` for container types requires
+special recursion handling.  In addition to protecting the stack,
+:attr:`tp_repr` also needs to track objects to prevent cycles.  The
+following two functions facilitate this functionality.  Effectively,
+these are the C equivalent to :func:`reprlib.recursive_repr`.
+
+.. c:function:: int Py_ReprEnter(PyObject *object)
+
+   Called at the beginning of the :attr:`tp_repr` implementation to
+   detect cycles.
+
+   If the object has already been processed, the function returns a
+   positive integer.  In that case the :attr:`tp_repr` implementation
+   should return a string object indicating a cycle.  As examples,
+   :class:`dict` objects return ``{...}`` and :class:`list` objects
+   return ``[...]``.
+
+   The function will return a negative integer if the recursion limit
+   is reached.  In that case the :attr:`tp_repr` implementation should
+   typically return ``NULL``.
+
+   Otherwise, the function returns zero and the :attr:`tp_repr`
+   implementation can continue normally.
+
+.. c:function:: void Py_ReprLeave(PyObject *object)
+
+   Ends a :c:func:`Py_ReprEnter`.  Must be called once for each
+   invocation of :c:func:`Py_ReprEnter` that returns zero.
+
 
 .. _standardexceptions:
 

Modified: python/branches/pep-3151/Doc/c-api/import.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/import.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/import.rst	Sat Feb 26 08:16:32 2011
@@ -142,6 +142,7 @@
    attribute of the module object is set to *cpathname* if it is
    non-``NULL``.  Of the three functions, this is the preferred one to use.
 
+   .. versionadded:: 3.2
 
 .. c:function:: long PyImport_GetMagicNumber()
 
@@ -155,6 +156,8 @@
    Return the magic tag string for :pep:`3147` format Python bytecode file
    names.
 
+   .. versionadded:: 3.2
+
 .. c:function:: PyObject* PyImport_GetModuleDict()
 
    Return the dictionary used for the module administration (a.k.a.

Modified: python/branches/pep-3151/Doc/c-api/init.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/init.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/init.rst	Sat Feb 26 08:16:32 2011
@@ -8,13 +8,15 @@
 *****************************************
 
 
+Initializing and finalizing the interpreter
+===========================================
+
+
 .. c:function:: void Py_Initialize()
 
    .. index::
       single: Py_SetProgramName()
       single: PyEval_InitThreads()
-      single: PyEval_ReleaseLock()
-      single: PyEval_AcquireLock()
       single: modules (in module sys)
       single: path (in module sys)
       module: builtins
@@ -28,8 +30,7 @@
    Initialize the Python interpreter.  In an application embedding  Python, this
    should be called before using any other Python/C API functions; with the
    exception of :c:func:`Py_SetProgramName`, :c:func:`Py_SetPath`,
-   :c:func:`PyEval_InitThreads`, :c:func:`PyEval_ReleaseLock`, and
-   :c:func:`PyEval_AcquireLock`. This initializes
+   and :c:func:`PyEval_InitThreads`. This initializes
    the table of loaded modules (``sys.modules``), and creates the fundamental
    modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`.  It also initializes
    the module search path (``sys.path``). It does not set ``sys.argv``; use
@@ -82,85 +83,8 @@
    :c:func:`Py_Finalize` more than once.
 
 
-.. c:function:: PyThreadState* Py_NewInterpreter()
-
-   .. index::
-      module: builtins
-      module: __main__
-      module: sys
-      single: stdout (in module sys)
-      single: stderr (in module sys)
-      single: stdin (in module sys)
-
-   Create a new sub-interpreter.  This is an (almost) totally separate environment
-   for the execution of Python code.  In particular, the new interpreter has
-   separate, independent versions of all imported modules, including the
-   fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`.  The
-   table of loaded modules (``sys.modules``) and the module search path
-   (``sys.path``) are also separate.  The new environment has no ``sys.argv``
-   variable.  It has new standard I/O stream file objects ``sys.stdin``,
-   ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
-   :c:type:`FILE` structures in the C library).
-
-   The return value points to the first thread state created in the new
-   sub-interpreter.  This thread state is made in the current thread state.
-   Note that no actual thread is created; see the discussion of thread states
-   below.  If creation of the new interpreter is unsuccessful, *NULL* is
-   returned; no exception is set since the exception state is stored in the
-   current thread state and there may not be a current thread state.  (Like all
-   other Python/C API functions, the global interpreter lock must be held before
-   calling this function and is still held when it returns; however, unlike most
-   other Python/C API functions, there needn't be a current thread state on
-   entry.)
-
-   .. index::
-      single: Py_Finalize()
-      single: Py_Initialize()
-
-   Extension modules are shared between (sub-)interpreters as follows: the first
-   time a particular extension is imported, it is initialized normally, and a
-   (shallow) copy of its module's dictionary is squirreled away.  When the same
-   extension is imported by another (sub-)interpreter, a new module is initialized
-   and filled with the contents of this copy; the extension's ``init`` function is
-   not called.  Note that this is different from what happens when an extension is
-   imported after the interpreter has been completely re-initialized by calling
-   :c:func:`Py_Finalize` and :c:func:`Py_Initialize`; in that case, the extension's
-   ``initmodule`` function *is* called again.
-
-   .. index:: single: close() (in module os)
-
-   **Bugs and caveats:** Because sub-interpreters (and the main interpreter) are
-   part of the same process, the insulation between them isn't perfect --- for
-   example, using low-level file operations like  :func:`os.close` they can
-   (accidentally or maliciously) affect each other's open files.  Because of the
-   way extensions are shared between (sub-)interpreters, some extensions may not
-   work properly; this is especially likely when the extension makes use of
-   (static) global variables, or when the extension manipulates its module's
-   dictionary after its initialization.  It is possible to insert objects created
-   in one sub-interpreter into a namespace of another sub-interpreter; this should
-   be done with great care to avoid sharing user-defined functions, methods,
-   instances or classes between sub-interpreters, since import operations executed
-   by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
-   modules.  (XXX This is a hard-to-fix bug that will be addressed in a future
-   release.)
-
-   Also note that the use of this functionality is incompatible with extension
-   modules such as PyObjC and ctypes that use the :c:func:`PyGILState_\*` APIs (and
-   this is inherent in the way the :c:func:`PyGILState_\*` functions work).  Simple
-   things may work, but confusing behavior will always be near.
-
-
-.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
-
-   .. index:: single: Py_Finalize()
-
-   Destroy the (sub-)interpreter represented by the given thread state. The given
-   thread state must be the current thread state.  See the discussion of thread
-   states below.  When the call returns, the current thread state is *NULL*.  All
-   thread states associated with this interpreter are destroyed.  (The global
-   interpreter lock must be held before calling this function and is still held
-   when it returns.)  :c:func:`Py_Finalize` will destroy all sub-interpreters that
-   haven't been explicitly destroyed at that point.
+Process-wide parameters
+=======================
 
 
 .. c:function:: void Py_SetProgramName(wchar_t *name)
@@ -412,8 +336,9 @@
 .. c:function:: void Py_SetPythonHome(wchar_t *home)
 
    Set the default "home" directory, that is, the location of the standard
-   Python libraries.  The libraries are searched in
-   :file:`{home}/lib/python{version}` and :file:`{home}/lib/python{version}`.
+   Python libraries.  See :envvar:`PYTHONHOME` for the meaning of the
+   argument string.
+
    The argument should point to a zero-terminated character string in static
    storage whose contents will not change for the duration of the program's
    execution.  No code in the Python interpreter will change the contents of
@@ -438,48 +363,47 @@
    single: lock, interpreter
 
 The Python interpreter is not fully thread-safe.  In order to support
-multi-threaded Python programs, there's a global lock, called the :dfn:`global
-interpreter lock` or :dfn:`GIL`, that must be held by the current thread before
+multi-threaded Python programs, there's a global lock, called the :term:`global
+interpreter lock` or :term:`GIL`, that must be held by the current thread before
 it can safely access Python objects. Without the lock, even the simplest
 operations could cause problems in a multi-threaded program: for example, when
 two threads simultaneously increment the reference count of the same object, the
 reference count could end up being incremented only once instead of twice.
 
-.. index:: single: setcheckinterval() (in module sys)
+.. index:: single: setswitchinterval() (in module sys)
 
-Therefore, the rule exists that only the thread that has acquired the global
-interpreter lock may operate on Python objects or call Python/C API functions.
-In order to support multi-threaded Python programs, the interpreter regularly
-releases and reacquires the lock --- by default, every 100 bytecode instructions
-(this can be changed with  :func:`sys.setcheckinterval`).  The lock is also
-released and reacquired around potentially blocking I/O operations like reading
-or writing a file, so that other threads can run while the thread that requests
-the I/O is waiting for the I/O operation to complete.
+Therefore, the rule exists that only the thread that has acquired the
+:term:`GIL` may operate on Python objects or call Python/C API functions.
+In order to emulate concurrency of execution, the interpreter regularly
+tries to switch threads (see :func:`sys.setswitchinterval`).  The lock is also
+released around potentially blocking I/O operations like reading or writing
+a file, so that other Python threads can run in the meantime.
 
 .. index::
    single: PyThreadState
    single: PyThreadState
 
-The Python interpreter needs to keep some bookkeeping information separate per
-thread --- for this it uses a data structure called :c:type:`PyThreadState`.
-There's one global variable, however: the pointer to the current
-:c:type:`PyThreadState` structure.  Before the addition of :dfn:`thread-local
-storage` (:dfn:`TLS`) the current thread state had to be manipulated
-explicitly.
+The Python interpreter keeps some thread-specific bookkeeping information
+inside a data structure called :c:type:`PyThreadState`.  There's also one
+global variable pointing to the current :c:type:`PyThreadState`: it can
+be retrieved using :c:func:`PyThreadState_Get`.
 
-This is easy enough in most cases.  Most code manipulating the global
-interpreter lock has the following simple structure::
+Releasing the GIL from extension code
+-------------------------------------
+
+Most extension code manipulating the :term:`GIL` has the following simple
+structure::
 
    Save the thread state in a local variable.
    Release the global interpreter lock.
-   ...Do some blocking I/O operation...
+   ... Do some blocking I/O operation ...
    Reacquire the global interpreter lock.
    Restore the thread state from the local variable.
 
 This is so common that a pair of macros exists to simplify it::
 
    Py_BEGIN_ALLOW_THREADS
-   ...Do some blocking I/O operation...
+   ... Do some blocking I/O operation ...
    Py_END_ALLOW_THREADS
 
 .. index::
@@ -488,9 +412,8 @@
 
 The :c:macro:`Py_BEGIN_ALLOW_THREADS` macro opens a new block and declares a
 hidden local variable; the :c:macro:`Py_END_ALLOW_THREADS` macro closes the
-block.  Another advantage of using these two macros is that when Python is
-compiled without thread support, they are defined empty, thus saving the thread
-state and GIL manipulations.
+block.  These two macros are still available when Python is compiled without
+thread support (they simply have an empty expansion).
 
 When thread support is enabled, the block above expands to the following code::
 
@@ -500,65 +423,60 @@
    ...Do some blocking I/O operation...
    PyEval_RestoreThread(_save);
 
-Using even lower level primitives, we can get roughly the same effect as
-follows::
-
-   PyThreadState *_save;
-
-   _save = PyThreadState_Swap(NULL);
-   PyEval_ReleaseLock();
-   ...Do some blocking I/O operation...
-   PyEval_AcquireLock();
-   PyThreadState_Swap(_save);
-
 .. index::
    single: PyEval_RestoreThread()
-   single: errno
    single: PyEval_SaveThread()
-   single: PyEval_ReleaseLock()
-   single: PyEval_AcquireLock()
 
-There are some subtle differences; in particular, :c:func:`PyEval_RestoreThread`
-saves and restores the value of the  global variable :c:data:`errno`, since the
-lock manipulation does not guarantee that :c:data:`errno` is left alone.  Also,
-when thread support is disabled, :c:func:`PyEval_SaveThread` and
-:c:func:`PyEval_RestoreThread` don't manipulate the GIL; in this case,
-:c:func:`PyEval_ReleaseLock` and :c:func:`PyEval_AcquireLock` are not available.
-This is done so that dynamically loaded extensions compiled with thread support
-enabled can be loaded by an interpreter that was compiled with disabled thread
-support.
-
-The global interpreter lock is used to protect the pointer to the current thread
-state.  When releasing the lock and saving the thread state, the current thread
-state pointer must be retrieved before the lock is released (since another
-thread could immediately acquire the lock and store its own thread state in the
-global variable). Conversely, when acquiring the lock and restoring the thread
-state, the lock must be acquired before storing the thread state pointer.
-
-It is important to note that when threads are created from C, they don't have
-the global interpreter lock, nor is there a thread state data structure for
-them.  Such threads must bootstrap themselves into existence, by first
-creating a thread state data structure, then acquiring the lock, and finally
-storing their thread state pointer, before they can start using the Python/C
-API.  When they are done, they should reset the thread state pointer, release
-the lock, and finally free their thread state data structure.
-
-Threads can take advantage of the :c:func:`PyGILState_\*` functions to do all of
-the above automatically.  The typical idiom for calling into Python from a C
-thread is now::
+Here is how these functions work: the global interpreter lock is used to protect the pointer to the
+current thread state.  When releasing the lock and saving the thread state,
+the current thread state pointer must be retrieved before the lock is released
+(since another thread could immediately acquire the lock and store its own thread
+state in the global variable). Conversely, when acquiring the lock and restoring
+the thread state, the lock must be acquired before storing the thread state
+pointer.
+
+.. note::
+   Calling system I/O functions is the most common use case for releasing
+   the GIL, but it can also be useful before calling long-running computations
+   which don't need access to Python objects, such as compression or
+   cryptographic functions operating over memory buffers.  For example, the
+   standard :mod:`zlib` and :mod:`hashlib` modules release the GIL when
+   compressing or hashing data.
+
+Non-Python created threads
+--------------------------
+
+When threads are created using the dedicated Python APIs (such as the
+:mod:`threading` module), a thread state is automatically associated to them
+and the code showed above is therefore correct.  However, when threads are
+created from C (for example by a third-party library with its own thread
+management), they don't hold the GIL, nor is there a thread state structure
+for them.
+
+If you need to call Python code from these threads (often this will be part
+of a callback API provided by the aforementioned third-party library),
+you must first register these threads with the interpreter by
+creating a thread state data structure, then acquiring the GIL, and finally
+storing their thread state pointer, before you can start using the Python/C
+API.  When you are done, you should reset the thread state pointer, release
+the GIL, and finally free the thread state data structure.
+
+The :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` functions do
+all of the above automatically.  The typical idiom for calling into Python
+from a C thread is::
 
    PyGILState_STATE gstate;
    gstate = PyGILState_Ensure();
 
-   /* Perform Python actions here.  */
+   /* Perform Python actions here. */
    result = CallSomeFunction();
-   /* evaluate result */
+   /* evaluate result or handle exception */
 
    /* Release the thread. No Python API allowed beyond this point. */
    PyGILState_Release(gstate);
 
 Note that the :c:func:`PyGILState_\*` functions assume there is only one global
-interpreter (created automatically by :c:func:`Py_Initialize`).  Python still
+interpreter (created automatically by :c:func:`Py_Initialize`).  Python
 supports the creation of additional interpreters (using
 :c:func:`Py_NewInterpreter`), but mixing multiple interpreters and the
 :c:func:`PyGILState_\*` API is unsupported.
@@ -580,6 +498,13 @@
 :c:func:`PyOS_AfterFork` tries to reset the necessary locks, but is not
 always able to.
 
+
+High-level API
+--------------
+
+These are the most commonly used types and functions when writing C extension
+code, or when embedding the Python interpreter:
+
 .. c:type:: PyInterpreterState
 
    This data structure represents the state shared by a number of cooperating
@@ -603,16 +528,15 @@
 .. c:function:: void PyEval_InitThreads()
 
    .. index::
-      single: PyEval_ReleaseLock()
+      single: PyEval_AcquireThread()
       single: PyEval_ReleaseThread()
       single: PyEval_SaveThread()
       single: PyEval_RestoreThread()
 
    Initialize and acquire the global interpreter lock.  It should be called in the
    main thread before creating a second thread or engaging in any other thread
-   operations such as :c:func:`PyEval_ReleaseLock` or
-   ``PyEval_ReleaseThread(tstate)``. It is not needed before calling
-   :c:func:`PyEval_SaveThread` or :c:func:`PyEval_RestoreThread`.
+   operations such as ``PyEval_ReleaseThread(tstate)``. It is not needed before
+   calling :c:func:`PyEval_SaveThread` or :c:func:`PyEval_RestoreThread`.
 
    .. index:: single: Py_Initialize()
 
@@ -621,21 +545,22 @@
 
    .. index:: module: _thread
 
-   When only the main thread exists, no GIL operations are needed. This is a
-   common situation (most Python programs do not use threads), and the lock
-   operations slow the interpreter down a bit. Therefore, the lock is not
-   created initially.  This situation is equivalent to having acquired the lock:
-   when there is only a single thread, all object accesses are safe.  Therefore,
-   when this function initializes the global interpreter lock, it also acquires
-   it.  Before the Python :mod:`_thread` module creates a new thread, knowing
-   that either it has the lock or the lock hasn't been created yet, it calls
-   :c:func:`PyEval_InitThreads`.  When this call returns, it is guaranteed that
-   the lock has been created and that the calling thread has acquired it.
+   .. note::
+      When only the main thread exists, no GIL operations are needed. This is a
+      common situation (most Python programs do not use threads), and the lock
+      operations slow the interpreter down a bit. Therefore, the lock is not
+      created initially.  This situation is equivalent to having acquired the lock:
+      when there is only a single thread, all object accesses are safe.  Therefore,
+      when this function initializes the global interpreter lock, it also acquires
+      it.  Before the Python :mod:`_thread` module creates a new thread, knowing
+      that either it has the lock or the lock hasn't been created yet, it calls
+      :c:func:`PyEval_InitThreads`.  When this call returns, it is guaranteed that
+      the lock has been created and that the calling thread has acquired it.
 
-   It is **not** safe to call this function when it is unknown which thread (if
-   any) currently has the global interpreter lock.
+      It is **not** safe to call this function when it is unknown which thread (if
+      any) currently has the global interpreter lock.
 
-   This function is not available when thread support is disabled at compile time.
+      This function is not available when thread support is disabled at compile time.
 
 
 .. c:function:: int PyEval_ThreadsInitialized()
@@ -646,37 +571,6 @@
    not available when thread support is disabled at compile time.
 
 
-.. c:function:: void PyEval_AcquireLock()
-
-   Acquire the global interpreter lock.  The lock must have been created earlier.
-   If this thread already has the lock, a deadlock ensues.  This function is not
-   available when thread support is disabled at compile time.
-
-
-.. c:function:: void PyEval_ReleaseLock()
-
-   Release the global interpreter lock.  The lock must have been created earlier.
-   This function is not available when thread support is disabled at compile time.
-
-
-.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)
-
-   Acquire the global interpreter lock and set the current thread state to
-   *tstate*, which should not be *NULL*.  The lock must have been created earlier.
-   If this thread already has the lock, deadlock ensues.  This function is not
-   available when thread support is disabled at compile time.
-
-
-.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)
-
-   Reset the current thread state to *NULL* and release the global interpreter
-   lock.  The lock must have been created earlier and must be held by the current
-   thread.  The *tstate* argument, which must not be *NULL*, is only used to check
-   that it represents the current thread state --- if it isn't, a fatal error is
-   reported. This function is not available when thread support is disabled at
-   compile time.
-
-
 .. c:function:: PyThreadState* PyEval_SaveThread()
 
    Release the global interpreter lock (if it has been created and thread
@@ -695,6 +589,20 @@
    when thread support is disabled at compile time.)
 
 
+.. c:function:: PyThreadState* PyThreadState_Get()
+
+   Return the current thread state.  The global interpreter lock must be held.
+   When the current thread state is *NULL*, this issues a fatal error (so that
+   the caller needn't check for *NULL*).
+
+
+.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
+
+   Swap the current thread state with the thread state given by the argument
+   *tstate*, which may be *NULL*.  The global interpreter lock must be held
+   and is not released.
+
+
 .. c:function:: void PyEval_ReInitThreads()
 
    This function is called from :c:func:`PyOS_AfterFork` to ensure that newly
@@ -702,6 +610,43 @@
    are not running in the child process.
 
 
+The following functions use thread-local storage, and are not compatible
+with sub-interpreters:
+
+.. c:function:: PyGILState_STATE PyGILState_Ensure()
+
+   Ensure that the current thread is ready to call the Python C API regardless
+   of the current state of Python, or of the global interpreter lock. This may
+   be called as many times as desired by a thread as long as each call is
+   matched with a call to :c:func:`PyGILState_Release`. In general, other
+   thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
+   :c:func:`PyGILState_Release` calls as long as the thread state is restored to
+   its previous state before the Release().  For example, normal usage of the
+   :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
+   acceptable.
+
+   The return value is an opaque "handle" to the thread state when
+   :c:func:`PyGILState_Ensure` was called, and must be passed to
+   :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
+   though recursive calls are allowed, these handles *cannot* be shared - each
+   unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
+   to :c:func:`PyGILState_Release`.
+
+   When the function returns, the current thread will hold the GIL and be able
+   to call arbitrary Python code.  Failure is a fatal error.
+
+
+.. c:function:: void PyGILState_Release(PyGILState_STATE)
+
+   Release any resources previously acquired.  After this call, Python's state will
+   be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
+   (but generally this state will be unknown to the caller, hence the use of the
+   GILState API).
+
+   Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
+   :c:func:`PyGILState_Release` on the same thread.
+
+
 The following macros are normally used without a trailing semicolon; look for
 example usage in the Python source distribution.
 
@@ -735,6 +680,10 @@
    :c:macro:`Py_BEGIN_ALLOW_THREADS` without the opening brace and variable
    declaration.  It is a no-op when thread support is disabled at compile time.
 
+
+Low-level API
+-------------
+
 All of the following functions are only available when thread support is enabled
 at compile time, and must be called only when the global interpreter lock has
 been created.
@@ -780,19 +729,6 @@
    :c:func:`PyThreadState_Clear`.
 
 
-.. c:function:: PyThreadState* PyThreadState_Get()
-
-   Return the current thread state.  The global interpreter lock must be held.
-   When the current thread state is *NULL*, this issues a fatal error (so that
-   the caller needn't check for *NULL*).
-
-
-.. c:function:: PyThreadState* PyThreadState_Swap(PyThreadState *tstate)
-
-   Swap the current thread state with the thread state given by the argument
-   *tstate*, which may be *NULL*.  The global interpreter lock must be held.
-
-
 .. c:function:: PyObject* PyThreadState_GetDict()
 
    Return a dictionary in which extensions can store thread-specific state
@@ -813,39 +749,148 @@
    exception (if any) for the thread is cleared. This raises no exceptions.
 
 
-.. c:function:: PyGILState_STATE PyGILState_Ensure()
+.. c:function:: void PyEval_AcquireThread(PyThreadState *tstate)
 
-   Ensure that the current thread is ready to call the Python C API regardless
-   of the current state of Python, or of the global interpreter lock. This may
-   be called as many times as desired by a thread as long as each call is
-   matched with a call to :c:func:`PyGILState_Release`. In general, other
-   thread-related APIs may be used between :c:func:`PyGILState_Ensure` and
-   :c:func:`PyGILState_Release` calls as long as the thread state is restored to
-   its previous state before the Release().  For example, normal usage of the
-   :c:macro:`Py_BEGIN_ALLOW_THREADS` and :c:macro:`Py_END_ALLOW_THREADS` macros is
-   acceptable.
+   Acquire the global interpreter lock and set the current thread state to
+   *tstate*, which should not be *NULL*.  The lock must have been created earlier.
+   If this thread already has the lock, deadlock ensues.
 
-   The return value is an opaque "handle" to the thread state when
-   :c:func:`PyGILState_Ensure` was called, and must be passed to
-   :c:func:`PyGILState_Release` to ensure Python is left in the same state. Even
-   though recursive calls are allowed, these handles *cannot* be shared - each
-   unique call to :c:func:`PyGILState_Ensure` must save the handle for its call
-   to :c:func:`PyGILState_Release`.
+   :c:func:`PyEval_RestoreThread` is a higher-level function which is always
+   available (even when thread support isn't enabled or when threads have
+   not been initialized).
 
-   When the function returns, the current thread will hold the GIL. Failure is a
-   fatal error.
 
+.. c:function:: void PyEval_ReleaseThread(PyThreadState *tstate)
 
-.. c:function:: void PyGILState_Release(PyGILState_STATE)
+   Reset the current thread state to *NULL* and release the global interpreter
+   lock.  The lock must have been created earlier and must be held by the current
+   thread.  The *tstate* argument, which must not be *NULL*, is only used to check
+   that it represents the current thread state --- if it isn't, a fatal error is
+   reported.
 
-   Release any resources previously acquired.  After this call, Python's state will
-   be the same as it was prior to the corresponding :c:func:`PyGILState_Ensure` call
-   (but generally this state will be unknown to the caller, hence the use of the
-   GILState API.)
+   :c:func:`PyEval_SaveThread` is a higher-level function which is always
+   available (even when thread support isn't enabled or when threads have
+   not been initialized).
 
-   Every call to :c:func:`PyGILState_Ensure` must be matched by a call to
-   :c:func:`PyGILState_Release` on the same thread.
 
+.. c:function:: void PyEval_AcquireLock()
+
+   Acquire the global interpreter lock.  The lock must have been created earlier.
+   If this thread already has the lock, a deadlock ensues.
+
+   .. deprecated:: 3.2
+      This function does not update the current thread state.  Please use
+      :c:func:`PyEval_RestoreThread` or :c:func:`PyEval_AcquireThread`
+      instead.
+
+
+.. c:function:: void PyEval_ReleaseLock()
+
+   Release the global interpreter lock.  The lock must have been created earlier.
+
+   .. deprecated:: 3.2
+      This function does not update the current thread state.  Please use
+      :c:func:`PyEval_SaveThread` or :c:func:`PyEval_ReleaseThread`
+      instead.
+
+
+Sub-interpreter support
+=======================
+
+While in most uses, you will only embed a single Python interpreter, there
+are cases where you need to create several independent interpreters in the
+same process and perhaps even in the same thread.  Sub-interpreters allow
+you to do that.  You can switch between sub-interpreters using the
+:c:func:`PyThreadState_Swap` function.  You can create and destroy them
+using the following functions:
+
+
+.. c:function:: PyThreadState* Py_NewInterpreter()
+
+   .. index::
+      module: builtins
+      module: __main__
+      module: sys
+      single: stdout (in module sys)
+      single: stderr (in module sys)
+      single: stdin (in module sys)
+
+   Create a new sub-interpreter.  This is an (almost) totally separate environment
+   for the execution of Python code.  In particular, the new interpreter has
+   separate, independent versions of all imported modules, including the
+   fundamental modules :mod:`builtins`, :mod:`__main__` and :mod:`sys`.  The
+   table of loaded modules (``sys.modules``) and the module search path
+   (``sys.path``) are also separate.  The new environment has no ``sys.argv``
+   variable.  It has new standard I/O stream file objects ``sys.stdin``,
+   ``sys.stdout`` and ``sys.stderr`` (however these refer to the same underlying
+   file descriptors).
+
+   The return value points to the first thread state created in the new
+   sub-interpreter.  This thread state is made in the current thread state.
+   Note that no actual thread is created; see the discussion of thread states
+   below.  If creation of the new interpreter is unsuccessful, *NULL* is
+   returned; no exception is set since the exception state is stored in the
+   current thread state and there may not be a current thread state.  (Like all
+   other Python/C API functions, the global interpreter lock must be held before
+   calling this function and is still held when it returns; however, unlike most
+   other Python/C API functions, there needn't be a current thread state on
+   entry.)
+
+   .. index::
+      single: Py_Finalize()
+      single: Py_Initialize()
+
+   Extension modules are shared between (sub-)interpreters as follows: the first
+   time a particular extension is imported, it is initialized normally, and a
+   (shallow) copy of its module's dictionary is squirreled away.  When the same
+   extension is imported by another (sub-)interpreter, a new module is initialized
+   and filled with the contents of this copy; the extension's ``init`` function is
+   not called.  Note that this is different from what happens when an extension is
+   imported after the interpreter has been completely re-initialized by calling
+   :c:func:`Py_Finalize` and :c:func:`Py_Initialize`; in that case, the extension's
+   ``initmodule`` function *is* called again.
+
+   .. index:: single: close() (in module os)
+
+
+.. c:function:: void Py_EndInterpreter(PyThreadState *tstate)
+
+   .. index:: single: Py_Finalize()
+
+   Destroy the (sub-)interpreter represented by the given thread state. The given
+   thread state must be the current thread state.  See the discussion of thread
+   states below.  When the call returns, the current thread state is *NULL*.  All
+   thread states associated with this interpreter are destroyed.  (The global
+   interpreter lock must be held before calling this function and is still held
+   when it returns.)  :c:func:`Py_Finalize` will destroy all sub-interpreters that
+   haven't been explicitly destroyed at that point.
+
+
+Bugs and caveats
+----------------
+
+Because sub-interpreters (and the main interpreter) are part of the same
+process, the insulation between them isn't perfect --- for example, using
+low-level file operations like  :func:`os.close` they can
+(accidentally or maliciously) affect each other's open files.  Because of the
+way extensions are shared between (sub-)interpreters, some extensions may not
+work properly; this is especially likely when the extension makes use of
+(static) global variables, or when the extension manipulates its module's
+dictionary after its initialization.  It is possible to insert objects created
+in one sub-interpreter into a namespace of another sub-interpreter; this should
+be done with great care to avoid sharing user-defined functions, methods,
+instances or classes between sub-interpreters, since import operations executed
+by such objects may affect the wrong (sub-)interpreter's dictionary of loaded
+modules.
+
+Also note that combining this functionality with :c:func:`PyGILState_\*` APIs
+is delicate, become these APIs assume a bijection between Python thread states
+and OS-level threads, an assumption broken by the presence of sub-interpreters.
+It is highly recommended that you don't switch sub-interpreters between a pair
+of matching :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release` calls.
+Furthermore, extensions (such as :mod:`ctypes`) using these APIs to allow calling
+of Python code from non-Python created threads will probably be broken when using
+sub-interpreters.
 
 
 Asynchronous Notifications

Modified: python/branches/pep-3151/Doc/c-api/intro.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/intro.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/intro.rst	Sat Feb 26 08:16:32 2011
@@ -41,8 +41,8 @@
    #include "Python.h"
 
 This implies inclusion of the following standard headers: ``<stdio.h>``,
-``<string.h>``, ``<errno.h>``, ``<limits.h>``, and ``<stdlib.h>`` (if
-available).
+``<string.h>``, ``<errno.h>``, ``<limits.h>``, ``<assert.h>`` and ``<stdlib.h>``
+(if available).
 
 .. note::
 

Modified: python/branches/pep-3151/Doc/c-api/list.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/list.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/list.rst	Sat Feb 26 08:16:32 2011
@@ -37,7 +37,7 @@
 
    .. note::
 
-      If *length* is greater than zero, the returned list object's items are
+      If *len* is greater than zero, the returned list object's items are
       set to ``NULL``.  Thus you cannot use abstract API functions such as
       :c:func:`PySequence_SetItem`  or expose the object to Python code before
       setting all items to a real object with :c:func:`PyList_SetItem`.
@@ -58,9 +58,9 @@
 
 .. c:function:: PyObject* PyList_GetItem(PyObject *list, Py_ssize_t index)
 
-   Return the object at position *pos* in the list pointed to by *p*.  The
+   Return the object at position *index* in the list pointed to by *list*.  The
    position must be positive, indexing from the end of the list is not
-   supported.  If *pos* is out of bounds, return *NULL* and set an
+   supported.  If *index* is out of bounds, return *NULL* and set an
    :exc:`IndexError` exception.
 
 

Modified: python/branches/pep-3151/Doc/c-api/module.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/module.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/module.rst	Sat Feb 26 08:16:32 2011
@@ -52,7 +52,7 @@
    manipulate a module's :attr:`__dict__`.
 
 
-.. c:function:: char* PyModule_GetName(PyObject *module)
+.. c:function:: PyObject* PyModule_GetNameObject(PyObject *module)
 
    .. index::
       single: __name__ (module attribute)
@@ -61,15 +61,13 @@
    Return *module*'s :attr:`__name__` value.  If the module does not provide one,
    or if it is not a string, :exc:`SystemError` is raised and *NULL* is returned.
 
+   .. versionadded:: 3.3
 
-.. c:function:: char* PyModule_GetFilename(PyObject *module)
 
-   Similar to :c:func:`PyModule_GetFilenameObject` but return the filename
-   encoded to 'utf-8'.
+.. c:function:: char* PyModule_GetName(PyObject *module)
 
-   .. deprecated:: 3.2
-      :c:func:`PyModule_GetFilename` raises :c:type:`UnicodeEncodeError` on
-      unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead.
+   Similar to :c:func:`PyModule_GetNameObject` but return the name encoded to
+   ``'utf-8'``.
 
 
 .. c:function:: PyObject* PyModule_GetFilenameObject(PyObject *module)
@@ -86,6 +84,16 @@
    .. versionadded:: 3.2
 
 
+.. c:function:: char* PyModule_GetFilename(PyObject *module)
+
+   Similar to :c:func:`PyModule_GetFilenameObject` but return the filename
+   encoded to 'utf-8'.
+
+   .. deprecated:: 3.2
+      :c:func:`PyModule_GetFilename` raises :c:type:`UnicodeEncodeError` on
+      unencodable filenames, use :c:func:`PyModule_GetFilenameObject` instead.
+
+
 .. c:function:: void* PyModule_GetState(PyObject *module)
 
    Return the "state" of the module, that is, a pointer to the block of memory

Modified: python/branches/pep-3151/Doc/c-api/object.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/object.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/object.rst	Sat Feb 26 08:16:32 2011
@@ -108,6 +108,9 @@
    Python expression ``o1 op o2``, where ``op`` is the operator corresponding to
    *opid*.
 
+.. note::
+   If *o1* and *o2* are the same object, :c:func:`PyObject_RichCompareBool`
+   will always return ``1`` for :const:`Py_EQ` and ``0`` for :const:`Py_NE`.
 
 .. c:function:: PyObject* PyObject_Repr(PyObject *o)
 

Modified: python/branches/pep-3151/Doc/c-api/slice.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/slice.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/slice.rst	Sat Feb 26 08:16:32 2011
@@ -26,7 +26,7 @@
    the new object could not be allocated.
 
 
-.. c:function:: int PySlice_GetIndices(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
+.. c:function:: int PySlice_GetIndices(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
 
    Retrieve the start, stop and step indices from the slice object *slice*,
    assuming a sequence of length *length*. Treats indices greater than
@@ -38,8 +38,12 @@
 
    You probably do not want to use this function.
 
+   .. versionchanged:: 3.2
+      The parameter type for the *slice* parameter was ``PySliceObject*``
+      before.
 
-.. c:function:: int PySlice_GetIndicesEx(PySliceObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength)
+
+.. c:function:: int PySlice_GetIndicesEx(PyObject *slice, Py_ssize_t length, Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength)
 
    Usable replacement for :c:func:`PySlice_GetIndices`.  Retrieve the start,
    stop, and step indices from the slice object *slice* assuming a sequence of
@@ -49,3 +53,6 @@
 
    Returns 0 on success and -1 on error with exception set.
 
+   .. versionchanged:: 3.2
+      The parameter type for the *slice* parameter was ``PySliceObject*``
+      before.

Modified: python/branches/pep-3151/Doc/c-api/type.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/type.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/type.rst	Sat Feb 26 08:16:32 2011
@@ -35,6 +35,14 @@
 
    Clear the internal lookup cache. Return the current version tag.
 
+.. c:function:: long PyType_GetFlags(PyTypeObject* type)
+
+   Return the :attr:`tp_flags` member of *type*. This function is primarily
+   meant for use with `Py_LIMITED_API`; the individual flag bits are
+   guaranteed to be stable across Python releases, but access to
+   :attr:`tp_flags` itself is not part of the limited API.
+
+   .. versionadded:: 3.2
 
 .. c:function:: void PyType_Modified(PyTypeObject *type)
 

Modified: python/branches/pep-3151/Doc/c-api/typeobj.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/typeobj.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/typeobj.rst	Sat Feb 26 08:16:32 2011
@@ -705,7 +705,9 @@
    This field is not inherited by subtypes (computed attributes are inherited
    through a different mechanism).
 
-   Docs for PyGetSetDef (XXX belong elsewhere)::
+   .. XXX belongs elsewhere
+
+   Docs for PyGetSetDef::
 
       typedef PyObject *(*getter)(PyObject *, void *);
       typedef int (*setter)(PyObject *, PyObject *, void *);
@@ -752,7 +754,7 @@
 
       PyObject * tp_descr_get(PyObject *self, PyObject *obj, PyObject *type);
 
-   XXX explain.
+   .. XXX explain.
 
    This field is inherited by subtypes.
 
@@ -767,7 +769,7 @@
 
    This field is inherited by subtypes.
 
-   XXX explain.
+   .. XXX explain.
 
 
 .. c:member:: long PyTypeObject.tp_dictoffset
@@ -1193,7 +1195,7 @@
 .. sectionauthor:: Benjamin Peterson
 
 
-The buffer interface exports a model where an object can expose its internal
+The :ref:`buffer interface <bufferobjects>` exports a model where an object can expose its internal
 data.
 
 If an object does not export the buffer interface, then its :attr:`tp_as_buffer`

Modified: python/branches/pep-3151/Doc/c-api/unicode.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/unicode.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/unicode.rst	Sat Feb 26 08:16:32 2011
@@ -328,6 +328,13 @@
    Identical to :c:func:`PyUnicode_FromFormat` except that it takes exactly two
    arguments.
 
+.. c:function:: PyObject* PyUnicode_TransformDecimalToASCII(Py_UNICODE *s, Py_ssize_t size)
+
+   Create a Unicode object by replacing all decimal digits in
+   :c:type:`Py_UNICODE` buffer of the given size by ASCII digits 0--9
+   according to their decimal value.  Return *NULL* if an exception
+   occurs.
+
 
 .. c:function:: Py_UNICODE* PyUnicode_AsUnicode(PyObject *unicode)
 
@@ -1056,7 +1063,9 @@
 .. c:function:: int PyUnicode_CompareWithASCIIString(PyObject *uni, char *string)
 
    Compare a unicode object, *uni*, with *string* and return -1, 0, 1 for less
-   than, equal, and greater than, respectively.
+   than, equal, and greater than, respectively. It is best to pass only
+   ASCII-encoded strings, but the function interprets the input string as
+   ISO-8859-1 if it contains non-ASCII characters".
 
 
 .. c:function:: int PyUnicode_RichCompare(PyObject *left,  PyObject *right,  int op)

Modified: python/branches/pep-3151/Doc/c-api/utilities.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/utilities.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/utilities.rst	Sat Feb 26 08:16:32 2011
@@ -18,3 +18,4 @@
    arg.rst
    conversion.rst
    reflection.rst
+   codec.rst

Modified: python/branches/pep-3151/Doc/c-api/veryhigh.rst
==============================================================================
--- python/branches/pep-3151/Doc/c-api/veryhigh.rst	(original)
+++ python/branches/pep-3151/Doc/c-api/veryhigh.rst	Sat Feb 26 08:16:32 2011
@@ -66,8 +66,9 @@
    If *fp* refers to a file associated with an interactive device (console or
    terminal input or Unix pseudo-terminal), return the value of
    :c:func:`PyRun_InteractiveLoop`, otherwise return the result of
-   :c:func:`PyRun_SimpleFile`.  If *filename* is *NULL*, this function uses
-   ``"???"`` as the filename.
+   :c:func:`PyRun_SimpleFile`.  *filename* is decoded from the filesystem
+   encoding (:func:`sys.getfilesystemencoding`).  If *filename* is *NULL*, this
+   function uses ``"???"`` as the filename.
 
 
 .. c:function:: int PyRun_SimpleString(const char *command)
@@ -110,9 +111,10 @@
 .. c:function:: int PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags)
 
    Similar to :c:func:`PyRun_SimpleStringFlags`, but the Python source code is read
-   from *fp* instead of an in-memory string. *filename* should be the name of the
-   file.  If *closeit* is true, the file is closed before PyRun_SimpleFileExFlags
-   returns.
+   from *fp* instead of an in-memory string. *filename* should be the name of
+   the file, it is decoded from the filesystem encoding
+   (:func:`sys.getfilesystemencoding`).  If *closeit* is true, the file is
+   closed before PyRun_SimpleFileExFlags returns.
 
 
 .. c:function:: int PyRun_InteractiveOne(FILE *fp, const char *filename)
@@ -125,7 +127,10 @@
 
    Read and execute a single statement from a file associated with an
    interactive device according to the *flags* argument.  The user will be
-   prompted using ``sys.ps1`` and ``sys.ps2``.  Returns ``0`` when the input was
+   prompted using ``sys.ps1`` and ``sys.ps2``.  *filename* is decoded from the
+   filesystem encoding (:func:`sys.getfilesystemencoding`).
+
+   Returns ``0`` when the input was
    executed successfully, ``-1`` if there was an exception, or an error code
    from the :file:`errcode.h` include file distributed as part of Python if
    there was a parse error.  (Note that :file:`errcode.h` is not included by
@@ -142,7 +147,8 @@
 
    Read and execute statements from a file associated with an interactive device
    until EOF is reached.  The user will be prompted using ``sys.ps1`` and
-   ``sys.ps2``.  Returns ``0`` at EOF.
+   ``sys.ps2``.  *filename* is decoded from the filesystem encoding
+   (:func:`sys.getfilesystemencoding`).  Returns ``0`` at EOF.
 
 
 .. c:function:: struct _node* PyParser_SimpleParseString(const char *str, int start)
@@ -164,7 +170,8 @@
    Parse Python source code from *str* using the start token *start* according to
    the *flags* argument.  The result can be used to create a code object which can
    be evaluated efficiently. This is useful if a code fragment must be evaluated
-   many times.
+   many times. *filename* is decoded from the filesystem encoding
+   (:func:`sys.getfilesystemencoding`).
 
 
 .. c:function:: struct _node* PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
@@ -217,7 +224,8 @@
 .. c:function:: PyObject* PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags)
 
    Similar to :c:func:`PyRun_StringFlags`, but the Python source code is read from
-   *fp* instead of an in-memory string. *filename* should be the name of the file.
+   *fp* instead of an in-memory string. *filename* should be the name of the file,
+   it is decoded from the filesystem encoding (:func:`sys.getfilesystemencoding`).
    If *closeit* is true, the file is closed before :c:func:`PyRun_FileExFlags`
    returns.
 
@@ -230,23 +238,38 @@
 
 .. c:function:: PyObject* Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags)
 
+   This is a simplified interface to :c:func:`Py_CompileStringExFlags` below, with
+   *optimize* set to ``-1``.
+
+
+.. c:function:: PyObject* Py_CompileStringExFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags, int optimize)
+
    Parse and compile the Python source code in *str*, returning the resulting code
    object.  The start token is given by *start*; this can be used to constrain the
    code which can be compiled and should be :const:`Py_eval_input`,
    :const:`Py_file_input`, or :const:`Py_single_input`.  The filename specified by
    *filename* is used to construct the code object and may appear in tracebacks or
-   :exc:`SyntaxError` exception messages.  This returns *NULL* if the code cannot
-   be parsed or compiled.
+   :exc:`SyntaxError` exception messages, it is decoded from the filesystem
+   encoding (:func:`sys.getfilesystemencoding`).  This returns *NULL* if the
+   code cannot be parsed or compiled.
+
+   The integer *optimize* specifies the optimization level of the compiler; a
+   value of ``-1`` selects the optimization level of the interpreter as given by
+   :option:`-O` options.  Explicit levels are ``0`` (no optimization;
+   ``__debug__`` is true), ``1`` (asserts are removed, ``__debug__`` is false)
+   or ``2`` (docstrings are removed too).
+
+   .. versionadded:: 3.2
 
 
-.. c:function:: PyObject* PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
+.. c:function:: PyObject* PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
 
    This is a simplified interface to :c:func:`PyEval_EvalCodeEx`, with just
    the code object, and the dictionaries of global and local variables.
    The other arguments are set to *NULL*.
 
 
-.. c:function:: PyObject* PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals, PyObject **args, int argcount, PyObject **kws, int kwcount, PyObject **defs, int defcount, PyObject *closure)
+.. c:function:: PyObject* PyEval_EvalCodeEx(PyObject *co, PyObject *globals, PyObject *locals, PyObject **args, int argcount, PyObject **kws, int kwcount, PyObject **defs, int defcount, PyObject *closure)
 
    Evaluate a precompiled code object, given a particular environment for its
    evaluation.  This environment consists of dictionaries of global and local

Modified: python/branches/pep-3151/Doc/conf.py
==============================================================================
--- python/branches/pep-3151/Doc/conf.py	(original)
+++ python/branches/pep-3151/Doc/conf.py	Sat Feb 26 08:16:32 2011
@@ -131,6 +131,8 @@
      'Python Tutorial', _stdauthor, 'manual'),
     ('using/index', 'using.tex',
      'Python Setup and Usage', _stdauthor, 'manual'),
+    ('faq/index', 'faq.tex',
+     'Python Frequently Asked Questions', _stdauthor, 'manual'),
     ('whatsnew/' + version, 'whatsnew.tex',
      'What\'s New in Python', 'A. M. Kuchling', 'howto'),
 ]

Modified: python/branches/pep-3151/Doc/copyright.rst
==============================================================================
--- python/branches/pep-3151/Doc/copyright.rst	(original)
+++ python/branches/pep-3151/Doc/copyright.rst	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,7 @@
 
 Python and this documentation is:
 
-Copyright © 2001-2010 Python Software Foundation. All rights reserved.
+Copyright © 2001-2011 Python Software Foundation. All rights reserved.
 
 Copyright © 2000 BeOpen.com. All rights reserved.
 

Modified: python/branches/pep-3151/Doc/distutils/apiref.rst
==============================================================================
--- python/branches/pep-3151/Doc/distutils/apiref.rst	(original)
+++ python/branches/pep-3151/Doc/distutils/apiref.rst	Sat Feb 26 08:16:32 2011
@@ -888,7 +888,7 @@
 .. function:: make_zipfile(base_name, base_dir[, verbose=0, dry_run=0])
 
    Create a zip file from all files in and under *base_dir*.  The output zip file
-   will be named *base_dir* + :file:`.zip`.  Uses either the  :mod:`zipfile` Python
+   will be named *base_name* + :file:`.zip`.  Uses either the  :mod:`zipfile` Python
    module (if available) or the InfoZIP :file:`zip`  utility (if installed and
    found on the default search path).  If neither  tool is available, raises
    :exc:`DistutilsExecError`.   Returns the name of the output zip file.

Modified: python/branches/pep-3151/Doc/distutils/uploading.rst
==============================================================================
--- python/branches/pep-3151/Doc/distutils/uploading.rst	(original)
+++ python/branches/pep-3151/Doc/distutils/uploading.rst	Sat Feb 26 08:16:32 2011
@@ -57,8 +57,11 @@
 
     from distutils.core import setup
 
+    with open('README.txt') as file:
+        long_description = file.read()
+
     setup(name='Distutils',
-          long_description=open('README.txt'))
+          long_description=long_description)
 
 In that case, :file:`README.txt` is a regular reStructuredText text file located
 in the root of the package besides :file:`setup.py`.

Modified: python/branches/pep-3151/Doc/documenting/markup.rst
==============================================================================
--- python/branches/pep-3151/Doc/documenting/markup.rst	(original)
+++ python/branches/pep-3151/Doc/documenting/markup.rst	Sat Feb 26 08:16:32 2011
@@ -565,10 +565,6 @@
    If you don't need the "variable part" indication, use the standard
    ````code```` instead.
 
-.. describe:: var
-
-   A Python or C variable or parameter name.
-
 
 The following roles generate external links:
 
@@ -614,6 +610,8 @@
 
 The ``:ref:`` invocation is replaced with the section title.
 
+Alternatively, you can reference any label (not just section titles)
+if you provide the link text ``:ref:`link text <reference-label>```.
 
 Paragraph-level markup
 ----------------------

Modified: python/branches/pep-3151/Doc/documenting/style.rst
==============================================================================
--- python/branches/pep-3151/Doc/documenting/style.rst	(original)
+++ python/branches/pep-3151/Doc/documenting/style.rst	Sat Feb 26 08:16:32 2011
@@ -1,14 +1,18 @@
 .. highlightlang:: rest
 
-Style Guide
+Style guide
 ===========
 
 The Python documentation should follow the `Apple Publications Style Guide`_
 wherever possible. This particular style guide was selected mostly because it
 seems reasonable and is easy to get online.
 
-Topics which are not covered in Apple's style guide will be discussed in
-this document.
+Topics which are either not covered in Apple's style guide or treated
+differently in Python documentation will be discussed in this
+document.
+
+Use of whitespace
+-----------------
 
 All reST files use an indentation of 3 spaces.  The maximum line length is 80
 characters for normal text, but tables, deeply indented code samples and long
@@ -21,6 +25,9 @@
 ignores the second space, it is customarily put in by some users, for example
 to aid Emacs' auto-fill mode.
 
+Footnotes
+---------
+
 Footnotes are generally discouraged, though they may be used when they are the
 best way to present specific information. When a footnote reference is added at
 the end of the sentence, it should follow the sentence-ending punctuation. The
@@ -34,6 +41,36 @@
 
 Footnotes may appear in the middle of sentences where appropriate.
 
+Capitalization
+--------------
+
+.. sidebar:: Sentence case
+
+   Sentence case is a set of capitalization rules used in English
+   sentences: the first word is always capitalized and other words are
+   only capitalized if there is a specific rule requiring it.
+
+Apple style guide recommends the use of title case in section titles.
+However, rules for which words should be capitalized in title case
+vary greaty between publications.
+
+In Python documentation, use of sentence case in section titles is
+preferable, but consistency within a unit is more important than
+following this rule.  If you add a section to the chapter where most
+sections are in title case you can either convert all titles to
+sentence case or use the dominant style in the new section title.
+
+Sentences that start with a word for which specific rules require
+starting it with a lower case letter should be avoided in titles and
+elsewhere.
+
+.. note::
+
+   Sections that describe a library module often have titles in the
+   form of "modulename --- Short description of the module."  In this
+   case, the description should be capitalized as a stand-alone
+   sentence.
+
 Many special names are used in the Python documentation, including the names of
 operating systems, programming languages, standards bodies, and the like. Most
 of these entities are not assigned any special markup, but the preferred
@@ -44,26 +81,32 @@
 be used to ensure consistency throughout the documentation:
 
 CPU
-    For "central processing unit." Many style guides say this should be spelled
-    out on the first use (and if you must use it, do so!). For the Python
-    documentation, this abbreviation should be avoided since there's no
-    reasonable way to predict which occurrence will be the first seen by the
-    reader. It is better to use the word "processor" instead.
+   For "central processing unit." Many style guides say this should be
+   spelled out on the first use (and if you must use it, do so!). For
+   the Python documentation, this abbreviation should be avoided since
+   there's no reasonable way to predict which occurrence will be the
+   first seen by the reader. It is better to use the word "processor"
+   instead.
 
 POSIX
-    The name assigned to a particular group of standards. This is always
-    uppercase.
+   The name assigned to a particular group of standards. This is always
+   uppercase.
 
 Python
-    The name of our favorite programming language is always capitalized.
+   The name of our favorite programming language is always capitalized.
+
+reST
+   For "reStructuredText," an easy to read, plaintext markup syntax
+   used to produce Python documentation.  When spelled out, it is
+   always one word and both forms start with a lower case 'r'.
 
 Unicode
-    The name of a character set and matching encoding. This is always written
-    capitalized.
+   The name of a character coding system. This is always written
+   capitalized.
 
 Unix
-    The name of the operating system developed at AT&T Bell Labs in the early
-    1970s.
+   The name of the operating system developed at AT&T Bell Labs in the early
+   1970s.
 
 
 .. _Apple Publications Style Guide: http://developer.apple.com/mac/library/documentation/UserExperience/Conceptual/APStyleGuide/APSG_2009.pdf

Modified: python/branches/pep-3151/Doc/extending/embedding.rst
==============================================================================
--- python/branches/pep-3151/Doc/extending/embedding.rst	(original)
+++ python/branches/pep-3151/Doc/extending/embedding.rst	Sat Feb 26 08:16:32 2011
@@ -35,9 +35,6 @@
 to :c:func:`PyRun_SimpleFile`.  You can also call the lower-level operations
 described in the previous chapters to construct and use Python objects.
 
-A simple demo of embedding Python can be found in the directory
-:file:`Demo/embed/` of the source distribution.
-
 
 .. seealso::
 
@@ -209,7 +206,7 @@
    {
        if(!PyArg_ParseTuple(args, ":numargs"))
            return NULL;
-       return Py_BuildValue("i", numargs);
+       return PyLong_FromLong(numargs);
    }
 
    static PyMethodDef EmbMethods[] = {

Modified: python/branches/pep-3151/Doc/extending/extending.rst
==============================================================================
--- python/branches/pep-3151/Doc/extending/extending.rst	(original)
+++ python/branches/pep-3151/Doc/extending/extending.rst	Sat Feb 26 08:16:32 2011
@@ -81,7 +81,7 @@
        if (!PyArg_ParseTuple(args, "s", &command))
            return NULL;
        sts = system(command);
-       return Py_BuildValue("i", sts);
+       return PyLong_FromLong(sts);
    }
 
 There is a straightforward translation from the argument list in Python (for
@@ -274,12 +274,9 @@
    sts = system(command);
 
 Our :func:`spam.system` function must return the value of :c:data:`sts` as a
-Python object.  This is done using the function :c:func:`Py_BuildValue`, which is
-something like the inverse of :c:func:`PyArg_ParseTuple`: it takes a format
-string and an arbitrary number of C values, and returns a new Python object.
-More info on :c:func:`Py_BuildValue` is given later. ::
+Python object.  This is done using the function :c:func:`PyLong_FromLong`. ::
 
-   return Py_BuildValue("i", sts);
+   return PyLong_FromLong(sts);
 
 In this case, it will return an integer object.  (Yes, even integers are objects
 on the heap in Python!)
@@ -1195,7 +1192,7 @@
        if (!PyArg_ParseTuple(args, "s", &command))
            return NULL;
        sts = PySpam_System(command);
-       return Py_BuildValue("i", sts);
+       return PyLong_FromLong(sts);
    }
 
 In the beginning of the module, right after the line ::

Modified: python/branches/pep-3151/Doc/extending/windows.rst
==============================================================================
--- python/branches/pep-3151/Doc/extending/windows.rst	(original)
+++ python/branches/pep-3151/Doc/extending/windows.rst	Sat Feb 26 08:16:32 2011
@@ -110,7 +110,7 @@
    Now your options are:
 
 #. Copy :file:`example.sln` and :file:`example.vcproj`, rename them to
-      :file:`spam.\*`, and edit them by hand, or
+   :file:`spam.\*`, and edit them by hand, or
 
 #. Create a brand new project; instructions are below.
 
@@ -179,8 +179,8 @@
 
 and add the following to the module initialization function::
 
-   MyObject_Type.ob_type = &PyType_Type;
-
+   if (PyType_Ready(&MyObject_Type) < 0)
+        return NULL;
 
 
 .. _dynamic-linking:

Modified: python/branches/pep-3151/Doc/faq/design.rst
==============================================================================
--- python/branches/pep-3151/Doc/faq/design.rst	(original)
+++ python/branches/pep-3151/Doc/faq/design.rst	Sat Feb 26 08:16:32 2011
@@ -418,11 +418,9 @@
 .. XXX check which of these projects are still alive
 
 There are also several programs which make it easier to intermingle Python and C
-code in various ways to increase performance.  See, for example, `Psyco
-<http://psyco.sourceforge.net/>`_, `Pyrex
-<http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_, `PyInline
-<http://pyinline.sourceforge.net/>`_, `Py2Cmod
-<http://sourceforge.net/projects/py2cmod/>`_, and `Weave
+code in various ways to increase performance.  See, for example, `Cython
+<http://cython.org/>`_, `Pyrex
+<http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_ and `Weave
 <http://www.scipy.org/Weave>`_.
 
 

Modified: python/branches/pep-3151/Doc/faq/extending.rst
==============================================================================
--- python/branches/pep-3151/Doc/faq/extending.rst	(original)
+++ python/branches/pep-3151/Doc/faq/extending.rst	Sat Feb 26 08:16:32 2011
@@ -45,10 +45,11 @@
 very little effort, as long as you're running on a machine with an
 x86-compatible processor.
 
-`Pyrex <http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_ is a compiler
-that accepts a slightly modified form of Python and generates the corresponding
-C code.  Pyrex makes it possible to write an extension without having to learn
-Python's C API.
+`Cython <http://cython.org>`_ and its relative `Pyrex
+<http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_ are compilers
+that accept a slightly modified form of Python and generate the corresponding
+C code.  Cython and Pyrex make it possible to write an extension without having
+to learn Python's C API.
 
 If you need to interface to some C or C++ library for which no Python extension
 currently exists, you can try wrapping the library's data types and functions
@@ -379,7 +380,7 @@
            if (ps1  == prompt ||                  /* ">>> " or */
                '\n' == code[i + j - 1])           /* "... " and double '\n' */
            {                                               /* so execute it */
-             dum = PyEval_EvalCode ((PyCodeObject *)src, glb, loc);
+             dum = PyEval_EvalCode (src, glb, loc);
              Py_XDECREF (dum);
              Py_XDECREF (src);
              free (code);

Modified: python/branches/pep-3151/Doc/faq/gui.rst
==============================================================================
--- python/branches/pep-3151/Doc/faq/gui.rst	(original)
+++ python/branches/pep-3151/Doc/faq/gui.rst	Sat Feb 26 08:16:32 2011
@@ -15,7 +15,9 @@
 What platform-independent GUI toolkits exist for Python?
 ========================================================
 
-Depending on what platform(s) you are aiming at, there are several.
+Depending on what platform(s) you are aiming at, there are several.  Some
+of them haven't been ported to Python 3 yet.  At least `Tkinter`_ and `Qt`_
+are known to be Python 3-compatible.
 
 .. XXX check links
 
@@ -23,10 +25,12 @@
 -------
 
 Standard builds of Python include an object-oriented interface to the Tcl/Tk
-widget set, called Tkinter.  This is probably the easiest to install and use.
-For more info about Tk, including pointers to the source, see the Tcl/Tk home
-page at http://www.tcl.tk.  Tcl/Tk is fully portable to the MacOS, Windows, and
-Unix platforms.
+widget set, called :ref:`tkinter <Tkinter>`.  This is probably the easiest to
+install (since it comes included with most
+`binary distributions <http://www.python.org/download/>`_ of Python) and use.
+For more info about Tk, including pointers to the source, see the
+`Tcl/Tk home page <http://www.tcl.tk>`_.  Tcl/Tk is fully portable to the
+MacOS, Windows, and Unix platforms.
 
 wxWidgets
 ---------
@@ -51,13 +55,15 @@
 Qt
 ---
 
-There are bindings available for the Qt toolkit (`PyQt
-<http://www.riverbankcomputing.co.uk/software/pyqt/>`_) and for KDE (`PyKDE <http://www.riverbankcomputing.co.uk/software/pykde/intro>`__).  If
-you're writing open source software, you don't need to pay for PyQt, but if you
-want to write proprietary applications, you must buy a PyQt license from
-`Riverbank Computing <http://www.riverbankcomputing.co.uk>`_ and (up to Qt 4.4;
-Qt 4.5 upwards is licensed under the LGPL license) a Qt license from `Trolltech
-<http://www.trolltech.com>`_.
+There are bindings available for the Qt toolkit (using either `PyQt
+<http://www.riverbankcomputing.co.uk/software/pyqt/>`_ or `PySide
+<http://www.pyside.org/>`_) and for KDE (`PyKDE <http://www.riverbankcomputing.co.uk/software/pykde/intro>`__).
+PyQt is currently more mature than PySide, but you must buy a PyQt license from
+`Riverbank Computing <http://www.riverbankcomputing.co.uk/software/pyqt/license>`_
+if you want to write proprietary applications.  PySide is free for all applications.
+
+Qt 4.5 upwards is licensed under the LGPL license; also, commercial licenses
+are available from `Nokia <http://qt.nokia.com/>`_.
 
 Gtk+
 ----

Modified: python/branches/pep-3151/Doc/faq/installed.rst
==============================================================================
--- python/branches/pep-3151/Doc/faq/installed.rst	(original)
+++ python/branches/pep-3151/Doc/faq/installed.rst	Sat Feb 26 08:16:32 2011
@@ -24,14 +24,14 @@
   it; you'll have to figure out who's been using the machine and might have
   installed it.
 * A third-party application installed on the machine might have been written in
-  Python and included a Python installation.  For a home computer, the most
-  common such application is `PySol <http://pysolfc.sourceforge.net/>`_, a
-  solitaire game that includes over 1000 different games and variations.
+  Python and included a Python installation.  There are many such applications,
+  from GUI programs to network servers and administrative scripts.
 * Some Windows machines also have Python installed.  At this writing we're aware
   of computers from Hewlett-Packard and Compaq that include Python.  Apparently
   some of HP/Compaq's administrative tools are written in Python.
-* All Apple computers running Mac OS X have Python installed; it's included in
-  the base installation.
+* Many Unix-compatible operating systems, such as Mac OS X and some Linux
+  distributions, have Python installed by default; it's included in the base
+  installation.
 
 
 Can I delete Python?

Modified: python/branches/pep-3151/Doc/faq/library.rst
==============================================================================
--- python/branches/pep-3151/Doc/faq/library.rst	(original)
+++ python/branches/pep-3151/Doc/faq/library.rst	Sat Feb 26 08:16:32 2011
@@ -285,11 +285,15 @@
 How do I parcel out work among a bunch of worker threads?
 ---------------------------------------------------------
 
-Use the :mod:`queue` module to create a queue containing a list of jobs.  The
-:class:`~queue.Queue` class maintains a list of objects with ``.put(obj)`` to
-add an item to the queue and ``.get()`` to return an item.  The class will take
-care of the locking necessary to ensure that each job is handed out exactly
-once.
+The easiest way is to use the new :mod:`concurrent.futures` module,
+especially the :mod:`~concurrent.futures.ThreadPoolExecutor` class.
+
+Or, if you want fine control over the dispatching algorithm, you can write
+your own logic manually.  Use the :mod:`queue` module to create a queue
+containing a list of jobs.  The :class:`~queue.Queue` class maintains a
+list of objects with ``.put(obj)`` to add an item to the queue and ``.get()``
+to return an item.  The class will take care of the locking necessary to
+ensure that each job is handed out exactly once.
 
 Here's a trivial example::
 
@@ -352,7 +356,7 @@
 What kinds of global value mutation are thread-safe?
 ----------------------------------------------------
 
-A global interpreter lock (GIL) is used internally to ensure that only one
+A :term:`global interpreter lock` (GIL) is used internally to ensure that only one
 thread runs in the Python VM at a time.  In general, Python offers to switch
 among threads only between bytecode instructions; how frequently it switches can
 be set via :func:`sys.setswitchinterval`.  Each bytecode instruction and
@@ -395,32 +399,34 @@
 Can't we get rid of the Global Interpreter Lock?
 ------------------------------------------------
 
-.. XXX mention multiprocessing
 .. XXX link to dbeazley's talk about GIL?
 
-The Global Interpreter Lock (GIL) is often seen as a hindrance to Python's
+The :term:`global interpreter lock` (GIL) is often seen as a hindrance to Python's
 deployment on high-end multiprocessor server machines, because a multi-threaded
 Python program effectively only uses one CPU, due to the insistence that
 (almost) all Python code can only run while the GIL is held.
 
 Back in the days of Python 1.5, Greg Stein actually implemented a comprehensive
 patch set (the "free threading" patches) that removed the GIL and replaced it
-with fine-grained locking.  Unfortunately, even on Windows (where locks are very
-efficient) this ran ordinary Python code about twice as slow as the interpreter
-using the GIL.  On Linux the performance loss was even worse because pthread
-locks aren't as efficient.
-
-Since then, the idea of getting rid of the GIL has occasionally come up but
-nobody has found a way to deal with the expected slowdown, and users who don't
-use threads would not be happy if their code ran at half at the speed.  Greg's
-free threading patch set has not been kept up-to-date for later Python versions.
+with fine-grained locking.  Adam Olsen recently did a similar experiment
+in his `python-safethread <http://code.google.com/p/python-safethread/>`_
+project.  Unfortunately, both experiments exhibited a sharp drop in single-thread
+performance (at least 30% slower), due to the amount of fine-grained locking
+necessary to compensate for the removal of the GIL.
 
 This doesn't mean that you can't make good use of Python on multi-CPU machines!
 You just have to be creative with dividing the work up between multiple
-*processes* rather than multiple *threads*.  Judicious use of C extensions will
-also help; if you use a C extension to perform a time-consuming task, the
-extension can release the GIL while the thread of execution is in the C code and
-allow other threads to get some work done.
+*processes* rather than multiple *threads*.  The
+:class:`~concurrent.futures.ProcessPoolExecutor` class in the new
+:mod:`concurrent.futures` module provides an easy way of doing so; the
+:mod:`multiprocessing` module provides a lower-level API in case you want
+more control over dispatching of tasks.
+
+Judicious use of C extensions will also help; if you use a C extension to
+perform a time-consuming task, the extension can release the GIL while the
+thread of execution is in the C code and allow other threads to get some work
+done.  Some standard library modules such as :mod:`zlib` and :mod:`hashlib`
+already do this.
 
 It has been suggested that the GIL should be a per-interpreter-state lock rather
 than truly global; interpreters then wouldn't be able to share objects.
@@ -751,7 +757,8 @@
 How do I avoid blocking in the connect() method of a socket?
 ------------------------------------------------------------
 
-The select module is commonly used to help with asynchronous I/O on sockets.
+The :mod:`select` module is commonly used to help with asynchronous I/O on
+sockets.
 
 To prevent the TCP connect from blocking, you can set the socket to non-blocking
 mode.  Then when you do the ``connect()``, you will either connect immediately
@@ -765,6 +772,12 @@
 -- ``0`` or ``errno.EISCONN`` indicate that you're connected -- or you can pass this
 socket to select to check if it's writable.
 
+.. note::
+   The :mod:`asyncore` module presents a framework-like approach to the problem
+   of writing non-blocking networking code.
+   The third-party `Twisted <http://twistedmatrix.com/>`_ library is
+   a popular and feature-rich alternative.
+
 
 Databases
 =========

Modified: python/branches/pep-3151/Doc/faq/programming.rst
==============================================================================
--- python/branches/pep-3151/Doc/faq/programming.rst	(original)
+++ python/branches/pep-3151/Doc/faq/programming.rst	Sat Feb 26 08:16:32 2011
@@ -127,9 +127,9 @@
 
 .. XXX seems to have overlap with other questions!
 
-`Pyrex <http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_ can compile a
-slightly modified version of Python code into a C extension, and can be used on
-many different platforms.
+`Cython <http://cython.org>`_ and `Pyrex <http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/>`_
+can compile a slightly modified version of Python code into a C extension, and
+can be used on many different platforms.
 
 `Psyco <http://psyco.sourceforge.net>`_ is a just-in-time compiler that
 translates Python code into x86 assembly language.  If you can use it, Psyco can

Modified: python/branches/pep-3151/Doc/glossary.rst
==============================================================================
--- python/branches/pep-3151/Doc/glossary.rst	(original)
+++ python/branches/pep-3151/Doc/glossary.rst	Sat Feb 26 08:16:32 2011
@@ -27,7 +27,7 @@
       :ref:`2to3-reference`.
 
    abstract base class
-      Abstract Base Classes (abbreviated ABCs) complement :term:`duck-typing` by
+      :ref:`abstract-base-classes` complement :term:`duck-typing` by
       providing a way to define interfaces when other techniques like
       :func:`hasattr` would be clumsy. Python comes with many built-in ABCs for
       data structures (in the :mod:`collections` module), numbers (in the
@@ -102,9 +102,10 @@
       See :pep:`343`.
 
    CPython
-      The canonical implementation of the Python programming language.  The
-      term "CPython" is used in contexts when necessary to distinguish this
-      implementation from others such as Jython or IronPython.
+      The canonical implementation of the Python programming language, as
+      distributed on `python.org <http://python.org>`_.  The term "CPython"
+      is used when necessary to distinguish this implementation from others
+      such as Jython or IronPython.
 
    decorator
       A function returning another function, usually applied as a function
@@ -181,22 +182,22 @@
       not expressions.
 
    extension module
-      A module written in C or C++, using Python's C API to interact with the core and
-      with user code.
+      A module written in C or C++, using Python's C API to interact with the
+      core and with user code.
 
    file object
       An object exposing a file-oriented API (with methods such as
-      :meth:`read()` or :meth:`write()`) to an underlying resource.
-      Depending on the way it was created, a file object can mediate access
-      to a real on-disk file or to another other type of storage or
-      communication device (for example standard input/output, in-memory
-      buffers, sockets, pipes, etc.).  File objects are also called
-      :dfn:`file-like objects` or :dfn:`streams`.
-
-      There are actually three categories of file objects: raw binary
-      files, buffered binary files and text files.  Their interfaces are
-      defined in the :mod:`io` module.  The canonical way to create a
-      file object is by using the :func:`open` function.
+      :meth:`read()` or :meth:`write()`) to an underlying resource.  Depending
+      on the way it was created, a file object can mediate access to a real
+      on-disk file or to another other type of storage or communication device
+      (for example standard input/output, in-memory buffers, sockets, pipes,
+      etc.).  File objects are also called :dfn:`file-like objects` or
+      :dfn:`streams`.
+
+      There are actually three categories of file objects: raw binary files,
+      buffered binary files and text files.  Their interfaces are defined in the
+      :mod:`io` module.  The canonical way to create a file object is by using
+      the :func:`open` function.
 
    file-like object
       A synonym for :term:`file object`.
@@ -263,16 +264,25 @@
       See :term:`global interpreter lock`.
 
    global interpreter lock
-      The lock used by Python threads to assure that only one thread
-      executes in the :term:`CPython` :term:`virtual machine` at a time.
-      This simplifies the CPython implementation by assuring that no two
-      processes can access the same memory at the same time.  Locking the
-      entire interpreter makes it easier for the interpreter to be
-      multi-threaded, at the expense of much of the parallelism afforded by
-      multi-processor machines.  Efforts have been made in the past to
-      create a "free-threaded" interpreter (one which locks shared data at a
-      much finer granularity), but so far none have been successful because
-      performance suffered in the common single-processor case.
+      The mechanism used by the :term:`CPython` interpreter to assure that
+      only one thread executes Python :term:`bytecode` at a time.
+      This simplifies the CPython implementation by making the object model
+      (including critical built-in types such as :class:`dict`) implicitly
+      safe against concurrent access.  Locking the entire interpreter
+      makes it easier for the interpreter to be multi-threaded, at the
+      expense of much of the parallelism afforded by multi-processor
+      machines.
+
+      However, some extension modules, either standard or third-party,
+      are designed so as to release the GIL when doing computationally-intensive
+      tasks such as compression or hashing.  Also, the GIL is always released
+      when doing I/O.
+
+      Past efforts to create a "free-threaded" interpreter (one which locks
+      shared data at a much finer granularity) have not been successful
+      because performance suffered in the common single-processor case. It
+      is believed that overcoming this performance issue would make the
+      implementation much more complicated and therefore costlier to maintain.
 
    hashable
       An object is *hashable* if it has a hash value which never changes during
@@ -322,7 +332,7 @@
       slowly.  See also :term:`interactive`.
 
    iterable
-      A container object capable of returning its members one at a
+      An object capable of returning its members one at a
       time. Examples of iterables include all sequence types (such as
       :class:`list`, :class:`str`, and :class:`tuple`) and some non-sequence
       types like :class:`dict` and :class:`file` and objects of any classes you
@@ -339,12 +349,12 @@
 
    iterator
       An object representing a stream of data.  Repeated calls to the iterator's
-      :meth:`__next__` (or passing it to the built-in function :func:`next`)
-      method return successive items in the stream.  When no more data are
-      available a :exc:`StopIteration` exception is raised instead.  At this
+      :meth:`__next__` method (or passing it to the built-in function
+      :func:`next`) return successive items in the stream.  When no more data
+      are available a :exc:`StopIteration` exception is raised instead.  At this
       point, the iterator object is exhausted and any further calls to its
-      :meth:`next` method just raise :exc:`StopIteration` again.  Iterators are
-      required to have an :meth:`__iter__` method that returns the iterator
+      :meth:`__next__` method just raise :exc:`StopIteration` again.  Iterators
+      are required to have an :meth:`__iter__` method that returns the iterator
       object itself so every iterator is also iterable and may be used in most
       places where other iterables are accepted.  One notable exception is code
       which attempts multiple iteration passes.  A container object (such as a
@@ -392,6 +402,12 @@
       the :term:`EAFP` approach and is characterized by the presence of many
       :keyword:`if` statements.
 
+      In a multi-threaded environment, the LBYL approach can risk introducing a
+      race condition between "the looking" and "the leaping".  For example, the
+      code, ``if key in mapping: return mapping[key]`` can fail if another
+      thread removes *key* from *mapping* after the test, but before the lookup.
+      This issue can be solved with locks or by using the EAFP approach.
+
    list
       A built-in Python :term:`sequence`.  Despite its name it is more akin
       to an array in other languages than to a linked list since access to
@@ -412,9 +428,11 @@
       :class:`importlib.abc.Loader` for an :term:`abstract base class`.
 
    mapping
-      A container object (such as :class:`dict`) which supports arbitrary key
-      lookups using the special method :meth:`__getitem__`.  Mappings also
-      support :meth:`__len__`, :meth:`__iter__`, and :meth:`__contains__`.
+      A container object that supports arbitrary key lookups and implements the
+      methods specified in the :class:`Mapping` or :class:`MutableMapping`
+      :ref:`abstract base classes <abstract-base-classes>`. Examples include
+      :class:`dict`, :class:`collections.defaultdict`,
+      :class:`collections.OrderedDict` and :class:`collections.Counter`.
 
    metaclass
       The class of a class.  Class definitions create a class name, a class
@@ -435,6 +453,14 @@
       its first :term:`argument` (which is usually called ``self``).
       See :term:`function` and :term:`nested scope`.
 
+   method resolution order
+      Method Resolution Order is the order in which base classes are searched
+      for a member during lookup. See `The Python 2.3 Method Resolution Order
+      <http://www.python.org/download/releases/2.3/mro/>`_.
+
+   MRO
+      See :term:`method resolution order`.
+
    mutable
       Mutable objects can change their value but keep their :func:`id`.  See
       also :term:`immutable`.

Modified: python/branches/pep-3151/Doc/howto/index.rst
==============================================================================
--- python/branches/pep-3151/Doc/howto/index.rst	(original)
+++ python/branches/pep-3151/Doc/howto/index.rst	Sat Feb 26 08:16:32 2011
@@ -14,11 +14,14 @@
    :maxdepth: 1
 
    advocacy.rst
+   pyporting.rst
    cporting.rst
    curses.rst
    descriptor.rst
    doanddont.rst
    functional.rst
+   logging.rst
+   logging-cookbook.rst
    regex.rst
    sockets.rst
    sorting.rst

Modified: python/branches/pep-3151/Doc/howto/regex.rst
==============================================================================
--- python/branches/pep-3151/Doc/howto/regex.rst	(original)
+++ python/branches/pep-3151/Doc/howto/regex.rst	Sat Feb 26 08:16:32 2011
@@ -5,7 +5,6 @@
 ****************************
 
 :Author: A.M. Kuchling <amk at amk.ca>
-:Release: 0.05
 
 .. TODO:
    Document lookbehind assertions
@@ -24,11 +23,6 @@
 Introduction
 ============
 
-The :mod:`re` module was added in Python 1.5, and provides Perl-style regular
-expression patterns.  Earlier versions of Python came with the :mod:`regex`
-module, which provided Emacs-style patterns.  The :mod:`regex` module was
-removed completely in Python 2.5.
-
 Regular expressions (called REs, or regexes, or regex patterns) are essentially
 a tiny, highly specialized programming language embedded inside Python and made
 available through the :mod:`re` module. Using this little language, you specify
@@ -113,7 +107,10 @@
 Some of the special sequences beginning with ``'\'`` represent predefined sets
 of characters that are often useful, such as the set of digits, the set of
 letters, or the set of anything that isn't whitespace.  The following predefined
-special sequences are available:
+special sequences are a subset of those available. The equivalent classes are
+for bytes patterns. For a complete list of sequences and expanded class
+definitions for Unicode string patterns, see the last part of
+:ref:`Regular Expression Syntax <re-syntax>`.
 
 ``\d``
    Matches any decimal digit; this is equivalent to the class ``[0-9]``.
@@ -264,7 +261,7 @@
    >>> import re
    >>> p = re.compile('ab*')
    >>> p
-   <_sre.SRE_Pattern object at 80b4150>
+   <_sre.SRE_Pattern object at 0x...>
 
 :func:`re.compile` also accepts an optional *flags* argument, used to enable
 various special features and syntax variations.  We'll go over the available
@@ -362,8 +359,8 @@
 and more.
 
 You can learn about this by interactively experimenting with the :mod:`re`
-module.  If you have Tkinter available, you may also want to look at
-:file:`Tools/scripts/redemo.py`, a demonstration program included with the
+module.  If you have :mod:`tkinter` available, you may also want to look at
+:file:`Tools/demo/redemo.py`, a demonstration program included with the
 Python distribution.  It allows you to enter REs and strings, and displays
 whether the RE matches or fails. :file:`redemo.py` can be quite useful when
 trying to debug a complicated RE.  Phil Schwartz's `Kodos
@@ -373,11 +370,10 @@
 This HOWTO uses the standard Python interpreter for its examples. First, run the
 Python interpreter, import the :mod:`re` module, and compile a RE::
 
-   Python 2.2.2 (#1, Feb 10 2003, 12:57:01)
    >>> import re
    >>> p = re.compile('[a-z]+')
    >>> p
-   <_sre.SRE_Pattern object at 80c3c28>
+   <_sre.SRE_Pattern object at 0x...>
 
 Now, you can try matching various strings against the RE ``[a-z]+``.  An empty
 string shouldn't match at all, since ``+`` means 'one or more repetitions'.
@@ -395,7 +391,7 @@
 
    >>> m = p.match('tempo')
    >>> m
-   <_sre.SRE_Match object at 80c4f68>
+   <_sre.SRE_Match object at 0x...>
 
 Now you can query the :class:`MatchObject` for information about the matching
 string.   :class:`MatchObject` instances also have several methods and
@@ -434,7 +430,7 @@
    >>> print(p.match('::: message'))
    None
    >>> m = p.search('::: message') ; print(m)
-   <re.MatchObject instance at 80c9650>
+   <_sre.SRE_Match object at 0x...>
    >>> m.group()
    'message'
    >>> m.span()
@@ -459,11 +455,11 @@
 
 :meth:`findall` has to create the entire list before it can be returned as the
 result.  The :meth:`finditer` method returns a sequence of :class:`MatchObject`
-instances as an :term:`iterator`. [#]_ ::
+instances as an :term:`iterator`::
 
    >>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
    >>> iterator
-   <callable-iterator object at 0x401833ac>
+   <callable_iterator object at 0x...>
    >>> for match in iterator:
    ...     print(match.span())
    ...
@@ -485,7 +481,7 @@
    >>> print(re.match(r'From\s+', 'Fromage amk'))
    None
    >>> re.match(r'From\s+', 'From amk Thu May 14 19:12:10 1998')
-   <re.MatchObject instance at 80c5978>
+   <_sre.SRE_Match object at 0x...>
 
 Under the hood, these functions simply create a pattern object for you
 and call the appropriate method on it.  They also store the compiled object in a
@@ -687,7 +683,7 @@
    line, the RE to use is ``^From``. ::
 
       >>> print(re.search('^From', 'From Here to Eternity'))
-      <re.MatchObject instance at 80c1520>
+      <_sre.SRE_Match object at 0x...>
       >>> print(re.search('^From', 'Reciting From Memory'))
       None
 
@@ -699,11 +695,11 @@
    or any location followed by a newline character.     ::
 
       >>> print(re.search('}$', '{block}'))
-      <re.MatchObject instance at 80adfa8>
+      <_sre.SRE_Match object at 0x...>
       >>> print(re.search('}$', '{block} '))
       None
       >>> print(re.search('}$', '{block}\n'))
-      <re.MatchObject instance at 80adfa8>
+      <_sre.SRE_Match object at 0x...>
 
    To match a literal ``'$'``, use ``\$`` or enclose it inside a character class,
    as in  ``[$]``.
@@ -728,7 +724,7 @@
 
       >>> p = re.compile(r'\bclass\b')
       >>> print(p.search('no class at all'))
-      <re.MatchObject instance at 80c8f28>
+      <_sre.SRE_Match object at 0x...>
       >>> print(p.search('the declassified algorithm'))
       None
       >>> print(p.search('one subclass is'))
@@ -746,7 +742,7 @@
       >>> print(p.search('no class at all'))
       None
       >>> print(p.search('\b' + 'class' + '\b')  )
-      <re.MatchObject instance at 80c3ee0>
+      <_sre.SRE_Match object at 0x...>
 
    Second, inside a character class, where there's no use for this assertion,
    ``\b`` represents the backspace character, for compatibility with Python's
@@ -1316,8 +1312,8 @@
 be *very* complicated.  Use an HTML or XML parser module for such tasks.)
 
 
-Not Using re.VERBOSE
---------------------
+Using re.VERBOSE
+----------------
 
 By now you've probably noticed that regular expressions are a very compact
 notation, but they're not terribly readable.  REs of moderate complexity can
@@ -1366,8 +1362,3 @@
 now-removed :mod:`regex` module, which won't help you much.)  Consider checking
 it out from your library.
 
-
-.. rubric:: Footnotes
-
-.. [#] Introduced in Python 2.2.2.
-

Modified: python/branches/pep-3151/Doc/howto/sorting.rst
==============================================================================
--- python/branches/pep-3151/Doc/howto/sorting.rst	(original)
+++ python/branches/pep-3151/Doc/howto/sorting.rst	Sat Feb 26 08:16:32 2011
@@ -8,8 +8,8 @@
 
 
 Python lists have a built-in :meth:`list.sort` method that modifies the list
-in-place and a :func:`sorted` built-in function that builds a new sorted list
-from an iterable.
+in-place.  There is also a :func:`sorted` built-in function that builds a new
+sorted list from an iterable.
 
 In this document, we explore the various techniques for sorting data using Python.
 
@@ -23,7 +23,7 @@
     >>> sorted([5, 2, 3, 1, 4])
     [1, 2, 3, 4, 5]
 
-You can also use the :meth:`list.sort` method of a list. It modifies the list
+You can also use the :meth:`list.sort` method. It modifies the list
 in-place (and returns *None* to avoid confusion). Usually it's less convenient
 than :func:`sorted` - but if you don't need the original list, it's slightly
 more efficient.
@@ -87,9 +87,9 @@
 =========================
 
 The key-function patterns shown above are very common, so Python provides
-convenience functions to make accessor functions easier and faster. The operator
-module has :func:`operator.itemgetter`, :func:`operator.attrgetter`, and
-an :func:`operator.methodcaller` function.
+convenience functions to make accessor functions easier and faster. The
+:mod:`operator` module has :func:`~operator.itemgetter`,
+:func:`~operator.attrgetter`, and an :func:`~operator.methodcaller` function.
 
 Using those functions, the above examples become simpler and faster:
 
@@ -248,7 +248,7 @@
     [5, 4, 3, 2, 1]
 
 In Python 3.2, the :func:`functools.cmp_to_key` function was added to the
-functools module in the standard library.
+:mod:`functools` module in the standard library.
 
 Odd and Ends
 ============
@@ -256,7 +256,7 @@
 * For locale aware sorting, use :func:`locale.strxfrm` for a key function or
   :func:`locale.strcoll` for a comparison function.
 
-* The *reverse* parameter still maintains sort stability (i.e. records with
+* The *reverse* parameter still maintains sort stability (so that records with
   equal keys retain the original order). Interestingly, that effect can be
   simulated without the parameter by using the builtin :func:`reversed` function
   twice:

Modified: python/branches/pep-3151/Doc/howto/unicode.rst
==============================================================================
--- python/branches/pep-3151/Doc/howto/unicode.rst	(original)
+++ python/branches/pep-3151/Doc/howto/unicode.rst	Sat Feb 26 08:16:32 2011
@@ -4,13 +4,11 @@
   Unicode HOWTO
 *****************
 
-:Release: 1.11
+:Release: 1.12
 
-This HOWTO discusses Python 2.x's support for Unicode, and explains
+This HOWTO discusses Python support for Unicode, and explains
 various problems that people commonly encounter when trying to work
-with Unicode.  (This HOWTO has not yet been updated to cover the 3.x
-versions of Python.)
-
+with Unicode.
 
 Introduction to Unicode
 =======================
@@ -44,14 +42,14 @@
 hold values ranging from 0 to 255.  ASCII codes only went up to 127, so some
 machines assigned values between 128 and 255 to accented characters.  Different
 machines had different codes, however, which led to problems exchanging files.
-Eventually various commonly used sets of values for the 128-255 range emerged.
+Eventually various commonly used sets of values for the 128--255 range emerged.
 Some were true standards, defined by the International Standards Organization,
 and some were **de facto** conventions that were invented by one company or
 another and managed to catch on.
 
 255 characters aren't very many.  For example, you can't fit both the accented
 characters used in Western Europe and the Cyrillic alphabet used for Russian
-into the 128-255 range because there are more than 127 such characters.
+into the 128--255 range because there are more than 127 such characters.
 
 You could write files using different codes (all your Russian files in a coding
 system called KOI8, all your French files in a different coding system called
@@ -64,8 +62,8 @@
 to represent many different characters from many different alphabets; an initial
 goal was to have Unicode contain the alphabets for every single human language.
 It turns out that even 16 bits isn't enough to meet that goal, and the modern
-Unicode specification uses a wider range of codes, 0-1,114,111 (0x10ffff in
-base-16).
+Unicode specification uses a wider range of codes, 0 through 1,114,111 (0x10ffff
+in base 16).
 
 There's a related ISO standard, ISO 10646.  Unicode and ISO 10646 were
 originally separate efforts, but the specifications were merged with the 1.1
@@ -90,7 +88,7 @@
 The Unicode standard describes how characters are represented by **code
 points**.  A code point is an integer value, usually denoted in base 16.  In the
 standard, a code point is written using the notation U+12ca to mean the
-character with value 0x12ca (4810 decimal).  The Unicode standard contains a lot
+character with value 0x12ca (4,810 decimal).  The Unicode standard contains a lot
 of tables listing characters and their corresponding code points::
 
    0061    'a'; LATIN SMALL LETTER A
@@ -117,10 +115,10 @@
 ---------
 
 To summarize the previous section: a Unicode string is a sequence of code
-points, which are numbers from 0 to 0x10ffff.  This sequence needs to be
-represented as a set of bytes (meaning, values from 0-255) in memory.  The rules
-for translating a Unicode string into a sequence of bytes are called an
-**encoding**.
+points, which are numbers from 0 through 0x10ffff (1,114,111 decimal).  This
+sequence needs to be represented as a set of bytes (meaning, values
+from 0 through 255) in memory.  The rules for translating a Unicode string
+into a sequence of bytes are called an **encoding**.
 
 The first encoding you might think of is an array of 32-bit integers.  In this
 representation, the string "Python" would look like this::
@@ -164,7 +162,7 @@
    case.)
 
 Latin-1, also known as ISO-8859-1, is a similar encoding.  Unicode code points
-0-255 are identical to the Latin-1 values, so converting to this encoding simply
+0--255 are identical to the Latin-1 values, so converting to this encoding simply
 requires converting code points to byte values; if a code point larger than 255
 is encountered, the string can't be encoded into Latin-1.
 
@@ -226,8 +224,8 @@
 <http://en.wikipedia.org/wiki/UTF-8>, for example.
 
 
-Python 2.x's Unicode Support
-============================
+Python's Unicode Support
+========================
 
 Now that you've learned the rudiments of Unicode, we can look at Python's
 Unicode features.
@@ -265,10 +263,13 @@
     UnicodeDecodeError: 'utf8' codec can't decode byte 0x80 in position 0:
                         unexpected code byte
     >>> b'\x80abc'.decode("utf-8", "replace")
-    '\ufffdabc'
+    '?abc'
     >>> b'\x80abc'.decode("utf-8", "ignore")
     'abc'
 
+(In this code example, the Unicode replacement character has been replaced by
+a question mark because it may not be displayed on some systems.)
+
 Encodings are specified as strings containing the encoding's name.  Python 3.2
 comes with roughly 100 different encodings; see the Python Library Reference at
 :ref:`standard-encodings` for a list.  Some encodings have multiple names; for
@@ -281,10 +282,10 @@
 built-in :func:`ord` function that takes a one-character Unicode string and
 returns the code point value::
 
-    >>> chr(40960)
-    '\ua000'
-    >>> ord('\ua000')
-    40960
+    >>> chr(57344)
+    '\ue000'
+    >>> ord('\ue000')
+    57344
 
 Converting to Bytes
 -------------------
@@ -326,7 +327,8 @@
 
 In Python source code, specific Unicode code points can be written using the
 ``\u`` escape sequence, which is followed by four hex digits giving the code
-point.  The ``\U`` escape sequence is similar, but expects 8 hex digits, not 4::
+point.  The ``\U`` escape sequence is similar, but expects eight hex digits,
+not four::
 
     >>> s = "a\xac\u1234\u20ac\U00008000"
               ^^^^ two-digit hex escape
@@ -465,18 +467,17 @@
 
 Reading Unicode from a file is therefore simple::
 
-    f = open('unicode.rst', encoding='utf-8')
-    for line in f:
-        print(repr(line))
+    with open('unicode.rst', encoding='utf-8') as f:
+        for line in f:
+            print(repr(line))
 
 It's also possible to open files in update mode, allowing both reading and
 writing::
 
-    f = open('test', encoding='utf-8', mode='w+')
-    f.write('\u4500 blah blah blah\n')
-    f.seek(0)
-    print(repr(f.readline()[:1]))
-    f.close()
+    with open('test', encoding='utf-8', mode='w+') as f:
+        f.write('\u4500 blah blah blah\n')
+        f.seek(0)
+        print(repr(f.readline()[:1]))
 
 The Unicode character U+FEFF is used as a byte-order mark (BOM), and is often
 written as the first character of a file in order to assist with autodetection
@@ -513,14 +514,13 @@
 automatically converted to the right encoding for you::
 
     filename = 'filename\u4500abc'
-    f = open(filename, 'w')
-    f.write('blah\n')
-    f.close()
+    with open(filename, 'w') as f:
+        f.write('blah\n')
 
 Functions in the :mod:`os` module such as :func:`os.stat` will also accept Unicode
 filenames.
 
-:func:`os.listdir`, which returns filenames, raises an issue: should it return
+Function :func:`os.listdir`, which returns filenames, raises an issue: should it return
 the Unicode version of filenames, or should it return byte strings containing
 the encoded versions?  :func:`os.listdir` will do both, depending on whether you
 provided the directory path as a byte string or a Unicode string.  If you pass a
@@ -569,14 +569,6 @@
 two different kinds of strings.  There is no automatic encoding or decoding if
 you do e.g. ``str + bytes``, a :exc:`TypeError` is raised for this expression.
 
-It's easy to miss such problems if you only test your software with data that
-doesn't contain any accents; everything will seem to work, but there's actually
-a bug in your program waiting for the first user who attempts to use characters
-> 127.  A second tip, therefore, is:
-
-    Include characters > 127 and, even better, characters > 255 in your test
-    data.
-
 When using data coming from a web browser or some other untrusted source, a
 common technique is to check for illegal characters in a string before using the
 string in a generated command line or storing it in a database.  If you're doing
@@ -594,8 +586,8 @@
         if '/' in filename:
             raise ValueError("'/' not allowed in filenames")
         unicode_name = filename.decode(encoding)
-        f = open(unicode_name, 'r')
-        # ... return contents of file ...
+        with open(unicode_name, 'r') as f:
+            # ... return contents of file ...
 
 However, if an attacker could specify the ``'base64'`` encoding, they could pass
 ``'L2V0Yy9wYXNzd2Q='``, which is the base-64 encoded form of the string
@@ -610,27 +602,30 @@
 Applications in Python" are available at
 <http://downloads.egenix.com/python/LSM2005-Developing-Unicode-aware-applications-in-Python.pdf>
 and discuss questions of character encodings as well as how to internationalize
-and localize an application.
+and localize an application.  These slides cover Python 2.x only.
 
 
-Revision History and Acknowledgements
-=====================================
+Acknowledgements
+================
 
 Thanks to the following people who have noted errors or offered suggestions on
 this article: Nicholas Bastin, Marius Gedminas, Kent Johnson, Ken Krugler,
 Marc-André Lemburg, Martin von Löwis, Chad Whitacre.
 
-Version 1.0: posted August 5 2005.
+.. comment
+   Revision History
+
+   Version 1.0: posted August 5 2005.
 
-Version 1.01: posted August 7 2005.  Corrects factual and markup errors; adds
-several links.
+   Version 1.01: posted August 7 2005.  Corrects factual and markup errors; adds
+   several links.
 
-Version 1.02: posted August 16 2005.  Corrects factual errors.
+   Version 1.02: posted August 16 2005.  Corrects factual errors.
 
-Version 1.1: Feb-Nov 2008.  Updates the document with respect to Python 3 changes.
+   Version 1.1: Feb-Nov 2008.  Updates the document with respect to Python 3 changes.
 
-Version 1.11: posted June 20 2010.  Notes that Python 3.x is not covered,
-and that the HOWTO only covers 2.x.
+   Version 1.11: posted June 20 2010.  Notes that Python 3.x is not covered,
+   and that the HOWTO only covers 2.x.
 
 .. comment Describe Python 3.x support (new section? new document?)
 .. comment Additional topic: building Python w/ UCS2 or UCS4 support

Modified: python/branches/pep-3151/Doc/howto/webservers.rst
==============================================================================
--- python/branches/pep-3151/Doc/howto/webservers.rst	(original)
+++ python/branches/pep-3151/Doc/howto/webservers.rst	Sat Feb 26 08:16:32 2011
@@ -526,7 +526,7 @@
 
 .. seealso::
 
-   There are many template engines competing for attention, becuase it is
+   There are many template engines competing for attention, because it is
    pretty easy to create them in Python.  The page `Templating
    <http://wiki.python.org/moin/Templating>`_ in the wiki lists a big,
    ever-growing number of these.  The three listed above are considered "second

Modified: python/branches/pep-3151/Doc/includes/email-mime.py
==============================================================================
--- python/branches/pep-3151/Doc/includes/email-mime.py	(original)
+++ python/branches/pep-3151/Doc/includes/email-mime.py	Sat Feb 26 08:16:32 2011
@@ -27,5 +27,5 @@
 
 # Send the email via our own SMTP server.
 s = smtplib.SMTP()
-s.sendmail(msg)
+s.send_message(msg)
 s.quit()

Modified: python/branches/pep-3151/Doc/includes/mp_newtype.py
==============================================================================
--- python/branches/pep-3151/Doc/includes/mp_newtype.py	(original)
+++ python/branches/pep-3151/Doc/includes/mp_newtype.py	Sat Feb 26 08:16:32 2011
@@ -12,7 +12,7 @@
 
 ##
 
-class Foo(object):
+class Foo:
     def f(self):
         print('you called Foo.f()')
     def g(self):

Modified: python/branches/pep-3151/Doc/includes/sqlite3/adapter_point_1.py
==============================================================================
--- python/branches/pep-3151/Doc/includes/sqlite3/adapter_point_1.py	(original)
+++ python/branches/pep-3151/Doc/includes/sqlite3/adapter_point_1.py	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
 import sqlite3
 
-class Point(object):
+class Point:
     def __init__(self, x, y):
         self.x, self.y = x, y
 

Modified: python/branches/pep-3151/Doc/includes/sqlite3/adapter_point_2.py
==============================================================================
--- python/branches/pep-3151/Doc/includes/sqlite3/adapter_point_2.py	(original)
+++ python/branches/pep-3151/Doc/includes/sqlite3/adapter_point_2.py	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
 import sqlite3
 
-class Point(object):
+class Point:
     def __init__(self, x, y):
         self.x, self.y = x, y
 

Modified: python/branches/pep-3151/Doc/includes/sqlite3/converter_point.py
==============================================================================
--- python/branches/pep-3151/Doc/includes/sqlite3/converter_point.py	(original)
+++ python/branches/pep-3151/Doc/includes/sqlite3/converter_point.py	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
 import sqlite3
 
-class Point(object):
+class Point:
     def __init__(self, x, y):
         self.x, self.y = x, y
 

Modified: python/branches/pep-3151/Doc/includes/tzinfo-examples.py
==============================================================================
--- python/branches/pep-3151/Doc/includes/tzinfo-examples.py	(original)
+++ python/branches/pep-3151/Doc/includes/tzinfo-examples.py	Sat Feb 26 08:16:32 2011
@@ -71,7 +71,7 @@
     def _isdst(self, dt):
         tt = (dt.year, dt.month, dt.day,
               dt.hour, dt.minute, dt.second,
-              dt.weekday(), 0, -1)
+              dt.weekday(), 0, 0)
         stamp = _time.mktime(tt)
         tt = _time.localtime(stamp)
         return tt.tm_isdst > 0

Modified: python/branches/pep-3151/Doc/install/index.rst
==============================================================================
--- python/branches/pep-3151/Doc/install/index.rst	(original)
+++ python/branches/pep-3151/Doc/install/index.rst	Sat Feb 26 08:16:32 2011
@@ -929,15 +929,34 @@
 GNU C / Cygwin / MinGW
 ^^^^^^^^^^^^^^^^^^^^^^
 
-These instructions only apply if you're using a version of Python prior  to
-2.4.1 with a MinGW prior to 3.0.0 (with binutils-2.13.90-20030111-1).
-
 This section describes the necessary steps to use Distutils with the GNU C/C++
 compilers in their Cygwin and MinGW distributions. [#]_ For a Python interpreter
 that was built with Cygwin, everything should work without any of these
 following steps.
 
-These compilers require some special libraries. This task is more complex than
+Not all extensions can be built with MinGW or Cygwin, but many can.  Extensions
+most likely to not work are those that use C++ or depend on Microsoft Visual C
+extensions.
+
+To let Distutils compile your extension with Cygwin you have to type::
+
+   python setup.py build --compiler=cygwin
+
+and for Cygwin in no-cygwin mode [#]_ or for MinGW type::
+
+   python setup.py build --compiler=mingw32
+
+If you want to use any of these options/compilers as default, you should
+consider writing it in your personal or system-wide configuration file for
+Distutils (see section :ref:`inst-config-files`.)
+
+Older Versions of Python and MinGW
+""""""""""""""""""""""""""""""""""
+The following instructions only apply if you're using a version of Python
+inferior to 2.4.1 with a MinGW inferior to 3.0.0 (with
+binutils-2.13.90-20030111-1).
+
+These compilers require some special libraries.  This task is more complex than
 for Borland's C++, because there is no program to convert the library.  First
 you have to create a list of symbols which the Python DLL exports. (You can find
 a good program for this task at
@@ -967,18 +986,6 @@
 them too. The converted files have to reside in the same directories as the
 normal libraries do.
 
-To let Distutils compile your extension with Cygwin you now have to type ::
-
-   python setup.py build --compiler=cygwin
-
-and for Cygwin in no-cygwin mode [#]_ or for MinGW type::
-
-   python setup.py build --compiler=mingw32
-
-If you want to use any of these options/compilers as default, you should
-consider to write it in your personal or system-wide configuration file for
-Distutils (see section :ref:`inst-config-files`.)
-
 
 .. seealso::
 

Modified: python/branches/pep-3151/Doc/library/2to3.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/2to3.rst	(original)
+++ python/branches/pep-3151/Doc/library/2to3.rst	Sat Feb 26 08:16:32 2011
@@ -141,7 +141,7 @@
 
 .. 2to3fixer:: exec
 
-   Converts the :keyword:`exec` statement to the :func:`exec` function.
+   Converts the ``exec`` statement to the :func:`exec` function.
 
 .. 2to3fixer:: execfile
 
@@ -293,7 +293,7 @@
 
 .. 2to3fixer:: print
 
-   Converts the :keyword:`print` statement to the :func:`print` function.
+   Converts the ``print`` statement to the :func:`print` function.
 
 .. 2to3fixer:: raise
 

Modified: python/branches/pep-3151/Doc/library/__future__.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/__future__.rst	(original)
+++ python/branches/pep-3151/Doc/library/__future__.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: __future__
    :synopsis: Future statement definitions
 
+**Source code:** :source:`Lib/__future__.py`
+
+--------------
 
 :mod:`__future__` is a real module, and serves three purposes:
 

Modified: python/branches/pep-3151/Doc/library/_dummy_thread.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/_dummy_thread.rst	(original)
+++ python/branches/pep-3151/Doc/library/_dummy_thread.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: _dummy_thread
    :synopsis: Drop-in replacement for the _thread module.
 
+**Source code:** :source:`Lib/_dummy_thread.py`
+
+--------------
 
 This module provides a duplicate interface to the :mod:`_thread` module.  It is
 meant to be imported when the :mod:`_thread` module is not provided on a

Modified: python/branches/pep-3151/Doc/library/_thread.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/_thread.rst	(original)
+++ python/branches/pep-3151/Doc/library/_thread.rst	Sat Feb 26 08:16:32 2011
@@ -137,6 +137,10 @@
    .. versionchanged:: 3.2
       The *timeout* parameter is new.
 
+   .. versionchanged:: 3.2
+      Lock acquires can now be interrupted by signals on POSIX.
+
+
 .. method:: lock.release()
 
    Releases the lock.  The lock must have been acquired earlier, but not

Modified: python/branches/pep-3151/Doc/library/abc.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/abc.rst	(original)
+++ python/branches/pep-3151/Doc/library/abc.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,10 @@
 .. sectionauthor:: Georg Brandl
 .. much of the content adapted from docstrings
 
+**Source code:** :source:`Lib/abc.py`
+
+--------------
+
 This module provides the infrastructure for defining an :term:`abstract base
 class` (ABCs) in Python, as outlined in :pep:`3119`; see the PEP for why this
 was added to Python. (See also :pep:`3141` and the :mod:`numbers` module
@@ -51,6 +55,9 @@
         assert issubclass(tuple, MyABC)
         assert isinstance((), MyABC)
 
+      .. versionchanged:: 3.3
+         Returns the registered subclass, to allow usage as a class decorator.
+
    You can also override this method in an abstract base class:
 
    .. method:: __subclasshook__(subclass)

Modified: python/branches/pep-3151/Doc/library/aifc.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/aifc.rst	(original)
+++ python/branches/pep-3151/Doc/library/aifc.rst	Sat Feb 26 08:16:32 2011
@@ -10,6 +10,10 @@
    single: AIFF
    single: AIFF-C
 
+**Source code:** :source:`Lib/aifc.py`
+
+--------------
+
 This module provides support for reading and writing AIFF and AIFF-C files.
 AIFF is Audio Interchange File Format, a format for storing digital audio
 samples in a file.  AIFF-C is a newer version of the format that includes the

Modified: python/branches/pep-3151/Doc/library/allos.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/allos.rst	(original)
+++ python/branches/pep-3151/Doc/library/allos.rst	Sat Feb 26 08:16:32 2011
@@ -19,6 +19,8 @@
    optparse.rst
    getopt.rst
    logging.rst
+   logging.config.rst
+   logging.handlers.rst
    getpass.rst
    curses.rst
    curses.ascii.rst

Modified: python/branches/pep-3151/Doc/library/argparse.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/argparse.rst	(original)
+++ python/branches/pep-3151/Doc/library/argparse.rst	Sat Feb 26 08:16:32 2011
@@ -4,9 +4,13 @@
 .. module:: argparse
    :synopsis: Command-line option and argument parsing library.
 .. moduleauthor:: Steven Bethard <steven.bethard at gmail.com>
-.. versionadded:: 3.2
 .. sectionauthor:: Steven Bethard <steven.bethard at gmail.com>
 
+**Source code:** :source:`Lib/argparse.py`
+
+.. versionadded:: 3.2
+
+--------------
 
 The :mod:`argparse` module makes it easy to write user friendly command line
 interfaces. The program defines what arguments it requires, and :mod:`argparse`
@@ -120,7 +124,9 @@
 ArgumentParser objects
 ----------------------
 
-.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], [argument_default], [parents], [prefix_chars], [conflict_handler], [formatter_class])
+.. class:: ArgumentParser([description], [epilog], [prog], [usage], [add_help], \
+                          [argument_default], [parents], [prefix_chars], \
+                          [conflict_handler], [formatter_class])
 
    Create a new :class:`ArgumentParser` object.  Each parameter has its own more
    detailed description below, but in short they are:
@@ -563,7 +569,9 @@
 The add_argument() method
 -------------------------
 
-.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], [const], [default], [type], [choices], [required], [help], [metavar], [dest])
+.. method:: ArgumentParser.add_argument(name or flags..., [action], [nargs], \
+                           [const], [default], [type], [choices], [required], \
+                           [help], [metavar], [dest])
 
    Define how a single command line argument should be parsed.  Each parameter
    has its own more detailed description below, but in short they are:
@@ -777,9 +785,11 @@
      >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
      ...                     default=sys.stdout)
      >>> parser.parse_args(['input.txt', 'output.txt'])
-     Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>, outfile=<open file 'output.txt', mode 'w' at 0x...>)
+     Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
+               outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
      >>> parser.parse_args([])
-     Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>, outfile=<open file '<stdout>', mode 'w' at 0x...>)
+     Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
+               outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
 
 * ``'*'``.  All command-line args present are gathered into a list.  Note that
   it generally doesn't make much sense to have more than one positional argument
@@ -875,26 +885,26 @@
 
 By default, ArgumentParser objects read command-line args in as simple strings.
 However, quite often the command-line string should instead be interpreted as
-another type, like a :class:`float`, :class:`int` or :class:`file`.  The
-``type`` keyword argument of :meth:`add_argument` allows any necessary
-type-checking and type-conversions to be performed.  Many common built-in types
-can be used directly as the value of the ``type`` argument::
+another type, like a :class:`float` or :class:`int`.  The ``type`` keyword
+argument of :meth:`add_argument` allows any necessary type-checking and
+type-conversions to be performed.  Common built-in types and functions can be
+used directly as the value of the ``type`` argument::
 
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('foo', type=int)
-   >>> parser.add_argument('bar', type=file)
+   >>> parser.add_argument('bar', type=open)
    >>> parser.parse_args('2 temp.txt'.split())
-   Namespace(bar=<open file 'temp.txt', mode 'r' at 0x...>, foo=2)
+   Namespace(bar=<_io.TextIOWrapper name='temp.txt' encoding='UTF-8'>, foo=2)
 
 To ease the use of various types of files, the argparse module provides the
 factory FileType which takes the ``mode=`` and ``bufsize=`` arguments of the
-``file`` object.  For example, ``FileType('w')`` can be used to create a
+:func:`open` function.  For example, ``FileType('w')`` can be used to create a
 writable file::
 
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('bar', type=argparse.FileType('w'))
    >>> parser.parse_args(['out.txt'])
-   Namespace(bar=<open file 'out.txt', mode 'w' at 0x...>)
+   Namespace(bar=<_io.TextIOWrapper name='out.txt' encoding='UTF-8'>)
 
 ``type=`` can take any callable that takes a single string argument and returns
 the type-converted value::
@@ -1312,7 +1322,7 @@
 that is normally used.  This can be achieved by specifying the ``namespace=``
 keyword argument::
 
-   >>> class C(object):
+   >>> class C:
    ...     pass
    ...
    >>> c = C()
@@ -1428,6 +1438,16 @@
 
        {foo,bar}   additional help
 
+   Furthermore, ``add_parser`` supports an additional ``aliases`` argument,
+   which allows multiple strings to refer to the same subparser. This example,
+   like ``svn``, aliases ``co`` as a shorthand for ``checkout``::
+
+     >>> parser = argparse.ArgumentParser()
+     >>> subparsers = parser.add_subparsers()
+     >>> checkout = subparsers.add_parser('checkout', aliases=['co'])
+     >>> checkout.add_argument('foo')
+     >>> parser.parse_args(['co', 'bar'])
+     Namespace(foo='bar')
 
    One particularly effective way of handling sub-commands is to combine the use
    of the :meth:`add_subparsers` method with calls to :meth:`set_defaults` so
@@ -1466,7 +1486,7 @@
      >>> args.func(args)
      ((XYZYX))
 
-   This way, you can let :meth:`parse_args` does the job of calling the
+   This way, you can let :meth:`parse_args` do the job of calling the
    appropriate function after argument parsing is complete.  Associating
    functions with actions like this is typically the easiest way to handle the
    different actions for each of your subparsers.  However, if it is necessary
@@ -1496,7 +1516,7 @@
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--output', type=argparse.FileType('wb', 0))
    >>> parser.parse_args(['--output', 'out'])
-   Namespace(output=<open file 'out', mode 'wb' at 0x...>)
+   Namespace(output=<_io.BufferedWriter name='out'>)
 
    FileType objects understand the pseudo-argument ``'-'`` and automatically
    convert this into ``sys.stdin`` for readable :class:`FileType` objects and
@@ -1505,7 +1525,7 @@
    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('infile', type=argparse.FileType('r'))
    >>> parser.parse_args(['-'])
-   Namespace(infile=<open file '<stdin>', mode 'r' at 0x...>)
+   Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>)
 
 
 Argument groups
@@ -1648,14 +1668,14 @@
 .. method:: ArgumentParser.print_usage(file=None)
 
    Print a brief description of how the :class:`ArgumentParser` should be
-   invoked on the command line.  If *file* is ``None``, :data:`sys.stderr` is
+   invoked on the command line.  If *file* is ``None``, :data:`sys.stdout` is
    assumed.
 
 .. method:: ArgumentParser.print_help(file=None)
 
    Print a help message, including the program usage and information about the
    arguments registered with the :class:`ArgumentParser`.  If *file* is
-   ``None``, :data:`sys.stderr` is assumed.
+   ``None``, :data:`sys.stdout` is assumed.
 
 There are also variants of these methods that simply return a string instead of
 printing it:
@@ -1729,6 +1749,7 @@
    This method prints a usage message including the *message* to the
    standard output and terminates the program with a status code of 2.
 
+.. _upgrading-optparse-code:
 
 Upgrading optparse code
 -----------------------
@@ -1742,11 +1763,12 @@
 
 A partial upgrade path from optparse to argparse:
 
-* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument` calls.
+* Replace all ``add_option()`` calls with :meth:`ArgumentParser.add_argument`
+  calls.
 
 * Replace ``options, args = parser.parse_args()`` with ``args =
-  parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument` calls for the
-  positional arguments.
+  parser.parse_args()`` and add additional :meth:`ArgumentParser.add_argument`
+  calls for the positional arguments.
 
 * Replace callback actions and the ``callback_*`` keyword arguments with
   ``type`` or ``action`` arguments.

Modified: python/branches/pep-3151/Doc/library/array.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/array.rst	(original)
+++ python/branches/pep-3151/Doc/library/array.rst	Sat Feb 26 08:16:32 2011
@@ -65,10 +65,6 @@
    passed to the :meth:`extend` method.
 
 
-.. data:: ArrayType
-
-   Obsolete alias for :class:`array`.
-
 .. data:: typecodes
 
    A string with all available type codes.

Modified: python/branches/pep-3151/Doc/library/ast.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/ast.rst	(original)
+++ python/branches/pep-3151/Doc/library/ast.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,9 @@
 .. sectionauthor:: Martin v. Löwis <martin at v.loewis.de>
 .. sectionauthor:: Georg Brandl <georg at python.org>
 
+**Source code:** :source:`Lib/ast.py`
+
+--------------
 
 The :mod:`ast` module helps Python applications to process trees of the Python
 abstract syntax grammar.  The abstract syntax itself might change with each
@@ -107,9 +110,9 @@
 Apart from the node classes, :mod:`ast` module defines these utility functions
 and classes for traversing abstract syntax trees:
 
-.. function:: parse(expr, filename='<unknown>', mode='exec')
+.. function:: parse(source, filename='<unknown>', mode='exec')
 
-   Parse an expression into an AST node.  Equivalent to ``compile(expr,
+   Parse the source into an AST node.  Equivalent to ``compile(source,
    filename, mode, ast.PyCF_ONLY_AST)``.
 
 
@@ -170,9 +173,9 @@
 
 .. function:: walk(node)
 
-   Recursively yield all child nodes of *node*, in no specified order.  This is
-   useful if you only want to modify nodes in place and don't care about the
-   context.
+   Recursively yield all descendant nodes in the tree starting at *node*
+   (including *node* itself), in no specified order.  This is useful if you only
+   want to modify nodes in place and don't care about the context.
 
 
 .. class:: NodeVisitor()

Modified: python/branches/pep-3151/Doc/library/asynchat.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/asynchat.rst	(original)
+++ python/branches/pep-3151/Doc/library/asynchat.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Sam Rushing <rushing at nightmare.com>
 .. sectionauthor:: Steve Holden <sholden at holdenweb.com>
 
+**Source code:** :source:`Lib/asynchat.py`
+
+--------------
 
 This module builds on the :mod:`asyncore` infrastructure, simplifying
 asynchronous clients and servers and making it easier to handle protocols

Modified: python/branches/pep-3151/Doc/library/asyncore.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/asyncore.rst	(original)
+++ python/branches/pep-3151/Doc/library/asyncore.rst	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,9 @@
 .. sectionauthor:: Steve Holden <sholden at holdenweb.com>
 .. heavily adapted from original documentation by Sam Rushing
 
+**Source code:** :source:`Lib/asyncore.py`
+
+--------------
 
 This module provides the basic infrastructure for writing asynchronous  socket
 service clients and servers.
@@ -181,12 +184,14 @@
    Most of these are nearly identical to their socket partners.
 
 
-   .. method:: create_socket(family, type)
+   .. method:: create_socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
 
       This is identical to the creation of a normal socket, and will use the
       same options for creation.  Refer to the :mod:`socket` documentation for
       information on creating sockets.
 
+  .. versionchanged:: 3.3 family and type arguments can be omitted.
+
 
    .. method:: connect(address)
 
@@ -277,7 +282,7 @@
 
        def __init__(self, host, path):
            asyncore.dispatcher.__init__(self)
-           self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+           self.create_socket()
            self.connect( (host, 80) )
            self.buffer = bytes('GET %s HTTP/1.0\r\n\r\n' % path, 'ascii')
 
@@ -306,7 +311,7 @@
 asyncore Example basic echo server
 ----------------------------------
 
-Here is abasic echo server that uses the :class:`dispatcher` class to accept
+Here is a basic echo server that uses the :class:`dispatcher` class to accept
 connections and dispatches the incoming connections to a handler::
 
     import asyncore
@@ -316,13 +321,14 @@
 
         def handle_read(self):
             data = self.recv(8192)
-            self.send(data)
+            if data:
+                self.send(data)
 
     class EchoServer(asyncore.dispatcher):
 
         def __init__(self, host, port):
             asyncore.dispatcher.__init__(self)
-            self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+            self.create_socket()
             self.set_reuse_addr()
             self.bind((host, port))
             self.listen(5)

Modified: python/branches/pep-3151/Doc/library/atexit.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/atexit.rst	(original)
+++ python/branches/pep-3151/Doc/library/atexit.rst	Sat Feb 26 08:16:32 2011
@@ -98,3 +98,4 @@
 
 This obviously only works with functions that don't take arguments.
 
+

Modified: python/branches/pep-3151/Doc/library/base64.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/base64.rst	(original)
+++ python/branches/pep-3151/Doc/library/base64.rst	Sat Feb 26 08:16:32 2011
@@ -37,7 +37,7 @@
    The encoded byte string is returned.
 
 
-.. function:: b64decode(s, altchars=None)
+.. function:: b64decode(s, altchars=None, validate=False)
 
    Decode a Base64 encoded byte string.
 
@@ -45,9 +45,13 @@
    at least length 2 (additional characters are ignored) which specifies the
    alternative alphabet used instead of the ``+`` and ``/`` characters.
 
-   The decoded byte string is returned.  A :exc:`TypeError` is raised if *s* were
-   incorrectly padded or if there are non-alphabet characters present in the
-   string.
+   The decoded string is returned.  A `binascii.Error` is raised if *s* is
+   incorrectly padded.
+
+   If *validate* is ``False`` (the default), non-base64-alphabet characters are
+   discarded prior to the padding check.  If *validate* is ``True``,
+   non-base64-alphabet characters in the input result in a
+   :exc:`binascii.Error`.
 
 
 .. function:: standard_b64encode(s)

Modified: python/branches/pep-3151/Doc/library/bdb.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/bdb.rst	(original)
+++ python/branches/pep-3151/Doc/library/bdb.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,10 @@
 .. module:: bdb
    :synopsis: Debugger framework.
 
+**Source code:** :source:`Lib/bdb.py`
+
+--------------
+
 The :mod:`bdb` module handles basic debugger functions, like setting breakpoints
 or managing execution via the debugger.
 
@@ -359,12 +363,10 @@
 .. function:: effective(file, line, frame)
 
    Determine if there is an effective (active) breakpoint at this line of code.
-   Return breakpoint number or 0 if none.
-
-   Called only if we know there is a breakpoint at this location.  Returns the
-   breakpoint that was triggered and a flag that indicates if it is ok to delete
-   a temporary breakpoint.
+   Return a tuple of the breakpoint and a boolean that indicates if it is ok
+   to delete a temporary breakpoint.  Return ``(None, None)`` if there is no
+   matching breakpoint.
 
 .. function:: set_trace()
 
-   Starts debugging with a :class:`Bdb` instance from caller's frame.
+   Start debugging with a :class:`Bdb` instance from caller's frame.

Modified: python/branches/pep-3151/Doc/library/bisect.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/bisect.rst	(original)
+++ python/branches/pep-3151/Doc/library/bisect.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,10 @@
 .. sectionauthor:: Raymond Hettinger <python at rcn.com>
 .. example based on the PyModules FAQ entry by Aaron Watters <arw at pythonpros.com>
 
+**Source code:** :source:`Lib/bisect.py`
+
+--------------
+
 This module provides support for maintaining a list in sorted order without
 having to sort the list after each insertion.  For long lists of items with
 expensive comparison operations, this can be an improvement over the more common

Modified: python/branches/pep-3151/Doc/library/builtins.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/builtins.rst	(original)
+++ python/branches/pep-3151/Doc/library/builtins.rst	Sat Feb 26 08:16:32 2011
@@ -32,9 +32,8 @@
 
        # ...
 
-As an implementation detail, most modules have the name ``__builtins__`` (note
-the ``'s'``) made available as part of their globals.  The value of
-``__builtins__`` is normally either this module or the value of this modules's
-:attr:`__dict__` attribute.  Since this is an implementation detail, it may not
-be used by alternate implementations of Python.
-
+As an implementation detail, most modules have the name ``__builtins__`` made
+available as part of their globals.  The value of ``__builtins__`` is normally
+either this module or the value of this modules's :attr:`__dict__` attribute.
+Since this is an implementation detail, it may not be used by alternate
+implementations of Python.

Modified: python/branches/pep-3151/Doc/library/calendar.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/calendar.rst	(original)
+++ python/branches/pep-3151/Doc/library/calendar.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
               of the Unix cal program.
 .. sectionauthor:: Drew Csillag <drew_csillag at geocities.com>
 
+**Source code:** :source:`Lib/calendar.py`
+
+--------------
 
 This module allows you to output calendars like the Unix :program:`cal` program,
 and provides additional useful functions related to the calendar. By default,
@@ -16,7 +19,7 @@
 functionality, see also the :mod:`datetime` and :mod:`time` modules.
 
 Most of these functions and classes rely on the :mod:`datetime` module which
-uses an idealized calendar, the current Gregorian calendar indefinitely extended
+uses an idealized calendar, the current Gregorian calendar extended
 in both directions.  This matches the definition of the "proleptic Gregorian"
 calendar in Dershowitz and Reingold's book "Calendrical Calculations", where
 it's the base calendar for all computations.
@@ -309,4 +312,3 @@
 
    Module :mod:`time`
       Low-level time related functions.
-

Modified: python/branches/pep-3151/Doc/library/cgi.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/cgi.rst	(original)
+++ python/branches/pep-3151/Doc/library/cgi.rst	Sat Feb 26 08:16:32 2011
@@ -13,6 +13,10 @@
    single: URL
    single: Common Gateway Interface
 
+**Source code:** :source:`Lib/cgi.py`
+
+--------------
+
 Support module for Common Gateway Interface (CGI) scripts.
 
 This module defines a number of utilities for use by CGI scripts written in

Modified: python/branches/pep-3151/Doc/library/cmd.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/cmd.rst	(original)
+++ python/branches/pep-3151/Doc/library/cmd.rst	Sat Feb 26 08:16:32 2011
@@ -5,13 +5,15 @@
    :synopsis: Build line-oriented command interpreters.
 .. sectionauthor:: Eric S. Raymond <esr at snark.thyrsus.com>
 
+**Source code:** :source:`Lib/cmd.py`
+
+--------------
 
 The :class:`Cmd` class provides a simple framework for writing line-oriented
 command interpreters.  These are often useful for test harnesses, administrative
 tools, and prototypes that will later be wrapped in a more sophisticated
 interface.
 
-
 .. class:: Cmd(completekey='tab', stdin=None, stdout=None)
 
    A :class:`Cmd` instance or subclass instance is a line-oriented interpreter

Modified: python/branches/pep-3151/Doc/library/codecs.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/codecs.rst	(original)
+++ python/branches/pep-3151/Doc/library/codecs.rst	Sat Feb 26 08:16:32 2011
@@ -788,7 +788,7 @@
 
 Strings are stored internally as sequences of codepoints (to be precise
 as :c:type:`Py_UNICODE` arrays). Depending on the way Python is compiled (either
-via :option:`--without-wide-unicode` or :option:`--with-wide-unicode`, with the
+via ``--without-wide-unicode`` or ``--with-wide-unicode``, with the
 former being the default) :c:type:`Py_UNICODE` is either a 16-bit or 32-bit data
 type. Once a string object is used outside of CPU and memory, CPU endianness
 and how these arrays are stored as bytes become an issue.  Transforming a
@@ -904,6 +904,15 @@
 case or use a hyphen instead of an underscore are also valid aliases; therefore,
 e.g. ``'utf-8'`` is a valid alias for the ``'utf_8'`` codec.
 
+.. impl-detail::
+
+   Some common encodings can bypass the codecs lookup machinery to
+   improve performance.  These optimization opportunities are only
+   recognized by CPython for a limited set of aliases: utf-8, utf8,
+   latin-1, latin1, iso-8859-1, mbcs (Windows only), ascii, utf-16,
+   and utf-32.  Using alternative spellings for these encodings may
+   result in slower execution.
+
 Many of the character sets support the same languages. They vary in individual
 characters (e.g. whether the EURO SIGN is supported or not), and in the
 assignment of characters to code positions. For the European languages in
@@ -1114,9 +1123,9 @@
 +-----------------+--------------------------------+--------------------------------+
 | utf_16          | U16, utf16                     | all languages                  |
 +-----------------+--------------------------------+--------------------------------+
-| utf_16_be       | UTF-16BE                       | all languages (BMP only)       |
+| utf_16_be       | UTF-16BE                       | all languages                  |
 +-----------------+--------------------------------+--------------------------------+
-| utf_16_le       | UTF-16LE                       | all languages (BMP only)       |
+| utf_16_le       | UTF-16LE                       | all languages                  |
 +-----------------+--------------------------------+--------------------------------+
 | utf_7           | U7, unicode-1-1-utf-7          | all languages                  |
 +-----------------+--------------------------------+--------------------------------+
@@ -1165,6 +1174,44 @@
 |                    |         | operand                   |
 +--------------------+---------+---------------------------+
 
+The following codecs provide bytes-to-bytes mappings.
+
++--------------------+---------------------------+---------------------------+
+| Codec              | Aliases                   | Purpose                   |
++====================+===========================+===========================+
+| base64_codec       | base64, base-64           | Convert operand to MIME   |
+|                    |                           | base64                    |
++--------------------+---------------------------+---------------------------+
+| bz2_codec          | bz2                       | Compress the operand      |
+|                    |                           | using bz2                 |
++--------------------+---------------------------+---------------------------+
+| hex_codec          | hex                       | Convert operand to        |
+|                    |                           | hexadecimal               |
+|                    |                           | representation, with two  |
+|                    |                           | digits per byte           |
++--------------------+---------------------------+---------------------------+
+| quopri_codec       | quopri, quoted-printable, | Convert operand to MIME   |
+|                    | quotedprintable           | quoted printable          |
++--------------------+---------------------------+---------------------------+
+| uu_codec           | uu                        | Convert the operand using |
+|                    |                           | uuencode                  |
++--------------------+---------------------------+---------------------------+
+| zlib_codec         | zip, zlib                 | Compress the operand      |
+|                    |                           | using gzip                |
++--------------------+---------------------------+---------------------------+
+
+The following codecs provide string-to-string mappings.
+
++--------------------+---------------------------+---------------------------+
+| Codec              | Aliases                   | Purpose                   |
++====================+===========================+===========================+
+| rot_13             | rot13                     | Returns the Caesar-cypher |
+|                    |                           | encryption of the operand |
++--------------------+---------------------------+---------------------------+
+
+.. versionadded:: 3.2
+   bytes-to-bytes and string-to-string codecs.
+
 
 :mod:`encodings.idna` --- Internationalized Domain Names in Applications
 ------------------------------------------------------------------------

Modified: python/branches/pep-3151/Doc/library/collections.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/collections.rst	(original)
+++ python/branches/pep-3151/Doc/library/collections.rst	Sat Feb 26 08:16:32 2011
@@ -12,6 +12,10 @@
    import itertools
    __name__ = '<doctest>'
 
+**Source code:** :source:`Lib/collections/__init__.py`
+
+--------------
+
 This module implements specialized container datatypes providing alternatives to
 Python's general purpose built-in containers, :class:`dict`, :class:`list`,
 :class:`set`, and :class:`tuple`.
@@ -19,6 +23,7 @@
 =====================   ====================================================================
 :func:`namedtuple`      factory function for creating tuple subclasses with named fields
 :class:`deque`          list-like container with fast appends and pops on either end
+:class:`ChainMap`       dict-like class for creating a single view of multiple mappings
 :class:`Counter`        dict subclass for counting hashable objects
 :class:`OrderedDict`    dict subclass that remembers the order entries were added
 :class:`defaultdict`    dict subclass that calls a factory function to supply missing values
@@ -27,10 +32,124 @@
 :class:`UserString`     wrapper around string objects for easier string subclassing
 =====================   ====================================================================
 
-In addition to the concrete container classes, the collections module provides
-ABCs (abstract base classes) that can be used to test whether a class provides a
-particular interface, for example, whether it is hashable or a mapping.
+.. versionchanged:: 3.3
+   Moved :ref:`abstract-base-classes` to the :mod:`collections.abc` module.
+   For backwards compatibility, they continue to be visible in this module
+   as well.
+
+
+:class:`ChainMap` objects
+-------------------------
 
+A :class:`ChainMap` class is provided for quickly linking a number of mappings
+so they can be treated as a single unit.  It is often much faster than creating
+a new dictionary and running multiple :meth:`~dict.update` calls.
+
+The class can be used to simulate nested scopes and is useful in templating.
+
+.. class:: ChainMap(*maps)
+
+   A :class:`ChainMap` groups multiple dicts or other mappings together to
+   create a single, updateable view.  If no *maps* are specified, a single empty
+   dictionary is provided so that a new chain always has at least one mapping.
+
+   The underlying mappings are stored in a list.  That list is public and can
+   accessed or updated using the *maps* attribute.  There is no other state.
+
+   Lookups search the underlying mappings successively until a key is found.  In
+   contrast, writes, updates, and deletions only operate on the first mapping.
+
+   A class:`ChainMap` incorporates the underlying mappings by reference.  So, if
+   one of the underlying mappings gets updated, those changes will be reflected
+   in class:`ChainMap`.
+
+   All of the usual dictionary methods are supported.  In addition, there is a
+   *maps* attribute, a method for creating new subcontexts, and a property for
+   accessing all but the first mapping:
+
+   .. attribute:: maps
+
+      A user updateable list of mappings.  The list is ordered from
+      first-searched to last-searched.  It is the only stored state and can
+      modified to change which mappings are searched.  The list should
+      always contain at least one mapping.
+
+   .. method:: new_child()
+
+      Returns a new :class:`ChainMap` containing a new :class:`dict` followed by
+      all of the maps in the current instance.  A call to ``d.new_child()`` is
+      equivalent to: ``ChainMap({}, *d.maps)``.  This method is used for
+      creating subcontexts that can be updated without altering values in any
+      of the parent mappings.
+
+   .. attribute:: parents()
+
+      Returns a new :class:`ChainMap` containing all of the maps in the current
+      instance except the first one.  This is useful for skipping the first map
+      in the search.  The use-cases are similar to those for the
+      :keyword:`nonlocal` keyword used in :term:`nested scopes <nested scope>`.
+      The use-cases also parallel those for the builtin :func:`super` function.
+      A reference to  ``d.parents`` is equivalent to: ``ChainMap(*d.maps[1:])``.
+
+  .. versionadded:: 3.3
+
+  Example of simulating Python's internal lookup chain::
+
+     import builtins
+     pylookup = ChainMap(locals(), globals(), vars(builtins))
+
+  Example of letting user specified values take precedence over environment
+  variables which in turn take precedence over default values::
+
+     import os, argparse
+     defaults = {'color': 'red', 'user': guest}
+     parser = argparse.ArgumentParser()
+     parser.add_argument('-u', '--user')
+     parser.add_argument('-c', '--color')
+     user_specified = vars(parser.parse_args())
+     combined = ChainMap(user_specified, os.environ, defaults)
+
+  Example patterns for using the :class:`ChainMap` class to simulate nested
+  contexts::
+
+    c = ChainMap()          Create root context
+    d = c.new_child()       Create nested child context
+    e = c.new_child()       Child of c, independent from d
+    e.maps[0]               Current context dictionary -- like Python's locals()
+    e.maps[-1]              Root context -- like Python's globals()
+    e.parents               Enclosing context chain -- like Python's nonlocals
+
+    d['x']                  Get first key in the chain of contexts
+    d['x'] = 1              Set value in current context
+    del['x']                Delete from current context
+    list(d)                 All nested values
+    k in d                  Check all nested values
+    len(d)                  Number of nested values
+    d.items()               All nested items
+    dict(d)                 Flatten into a regular dictionary
+
+  .. seealso::
+
+     * The `MultiContext class
+       <http://svn.enthought.com/svn/enthought/CodeTools/trunk/enthought/contexts/multi_context.py>`_
+       in the Enthought `CodeTools package
+       <https://github.com/enthought/codetools>`_\ has options to support
+       writing to any mapping in the chain.
+
+     * Django's `Context class
+       <http://code.djangoproject.com/browser/django/trunk/django/template/context.py>`_
+       for templating is a read-only chain of mappings.  It also features
+       pushing and popping of contexts similar to the
+       :meth:`~collections.ChainMap.new_child` method and the
+       :meth:`~collections.ChainMap.parents` property.
+
+     * The `Nested Contexts recipe
+       <http://code.activestate.com/recipes/577434/>`_ has options to control
+       whether writes and other mutations apply only to the first mapping or to
+       any mapping in the chain.
+
+     * A `greatly simplified read-only version of Chainmap
+       <http://code.activestate.com/recipes/305268/>`_\.
 
 :class:`Counter` objects
 ------------------------
@@ -581,11 +700,15 @@
    .. versionchanged:: 3.1
       Added support for *rename*.
 
-Example:
 
 .. doctest::
    :options: +NORMALIZE_WHITESPACE
 
+   >>> # Basic example
+   >>> Point = namedtuple('Point', 'x y')
+   >>> p = Point(x=10, y=11)
+
+   >>> # Example using the verbose option to print the class definition
    >>> Point = namedtuple('Point', 'x y', verbose=True)
    class Point(tuple):
            'Point(x, y)'
@@ -857,7 +980,7 @@
 original insertion position is changed and moved to the end::
 
     class LastUpdatedOrderedDict(OrderedDict):
-        'Store items is the order the keys were last added'
+        'Store items in the order the keys were last added'
         def __setitem__(self, key, value):
             if key in self:
                 del self[key]
@@ -949,117 +1072,3 @@
    be an instance of :class:`bytes`, :class:`str`, :class:`UserString` (or a
    subclass) or an arbitrary sequence which can be converted into a string using
    the built-in :func:`str` function.
-
-
-ABCs - abstract base classes
-----------------------------
-
-The collections module offers the following ABCs:
-
-=========================  =====================  ======================  ====================================================
-ABC                        Inherits               Abstract Methods        Mixin Methods
-=========================  =====================  ======================  ====================================================
-:class:`Container`                                ``__contains__``
-:class:`Hashable`                                 ``__hash__``
-:class:`Iterable`                                 ``__iter__``
-:class:`Iterator`          :class:`Iterable`      ``__next__``            ``__iter__``
-:class:`Sized`                                    ``__len__``
-:class:`Callable`                                 ``__call__``
-
-:class:`Sequence`          :class:`Sized`,        ``__getitem__``         ``__contains__``. ``__iter__``, ``__reversed__``.
-                           :class:`Iterable`,                             ``index``, and ``count``
-                           :class:`Container`
-
-:class:`MutableSequence`   :class:`Sequence`      ``__setitem__``         Inherited Sequence methods and
-                                                  ``__delitem__``,        ``append``, ``reverse``, ``extend``, ``pop``,
-                                                  and ``insert``          ``remove``, and ``__iadd__``
-
-:class:`Set`               :class:`Sized`,                                ``__le__``, ``__lt__``, ``__eq__``, ``__ne__``,
-                           :class:`Iterable`,                             ``__gt__``, ``__ge__``, ``__and__``, ``__or__``
-                           :class:`Container`                             ``__sub__``, ``__xor__``, and ``isdisjoint``
-
-:class:`MutableSet`        :class:`Set`           ``add`` and             Inherited Set methods and
-                                                  ``discard``             ``clear``, ``pop``, ``remove``, ``__ior__``,
-                                                                          ``__iand__``, ``__ixor__``, and ``__isub__``
-
-:class:`Mapping`           :class:`Sized`,        ``__getitem__``         ``__contains__``, ``keys``, ``items``, ``values``,
-                           :class:`Iterable`,                             ``get``, ``__eq__``, and ``__ne__``
-                           :class:`Container`
-
-:class:`MutableMapping`    :class:`Mapping`       ``__setitem__`` and     Inherited Mapping methods and
-                                                  ``__delitem__``         ``pop``, ``popitem``, ``clear``, ``update``,
-                                                                          and ``setdefault``
-
-
-:class:`MappingView`       :class:`Sized`                                 ``__len__``
-:class:`KeysView`          :class:`MappingView`,                          ``__contains__``,
-                           :class:`Set`                                   ``__iter__``
-:class:`ItemsView`         :class:`MappingView`,                          ``__contains__``,
-                           :class:`Set`                                   ``__iter__``
-:class:`ValuesView`        :class:`MappingView`                           ``__contains__``, ``__iter__``
-=========================  =====================  ======================  ====================================================
-
-These ABCs allow us to ask classes or instances if they provide
-particular functionality, for example::
-
-    size = None
-    if isinstance(myvar, collections.Sized):
-        size = len(myvar)
-
-Several of the ABCs are also useful as mixins that make it easier to develop
-classes supporting container APIs.  For example, to write a class supporting
-the full :class:`Set` API, it only necessary to supply the three underlying
-abstract methods: :meth:`__contains__`, :meth:`__iter__`, and :meth:`__len__`.
-The ABC supplies the remaining methods such as :meth:`__and__` and
-:meth:`isdisjoint` ::
-
-    class ListBasedSet(collections.Set):
-         ''' Alternate set implementation favoring space over speed
-             and not requiring the set elements to be hashable. '''
-         def __init__(self, iterable):
-             self.elements = lst = []
-             for value in iterable:
-                 if value not in lst:
-                     lst.append(value)
-         def __iter__(self):
-             return iter(self.elements)
-         def __contains__(self, value):
-             return value in self.elements
-         def __len__(self):
-             return len(self.elements)
-
-    s1 = ListBasedSet('abcdef')
-    s2 = ListBasedSet('defghi')
-    overlap = s1 & s2            # The __and__() method is supported automatically
-
-Notes on using :class:`Set` and :class:`MutableSet` as a mixin:
-
-(1)
-   Since some set operations create new sets, the default mixin methods need
-   a way to create new instances from an iterable. The class constructor is
-   assumed to have a signature in the form ``ClassName(iterable)``.
-   That assumption is factored-out to an internal classmethod called
-   :meth:`_from_iterable` which calls ``cls(iterable)`` to produce a new set.
-   If the :class:`Set` mixin is being used in a class with a different
-   constructor signature, you will need to override :meth:`from_iterable`
-   with a classmethod that can construct new instances from
-   an iterable argument.
-
-(2)
-   To override the comparisons (presumably for speed, as the
-   semantics are fixed), redefine :meth:`__le__` and
-   then the other operations will automatically follow suit.
-
-(3)
-   The :class:`Set` mixin provides a :meth:`_hash` method to compute a hash value
-   for the set; however, :meth:`__hash__` is not defined because not all sets
-   are hashable or immutable.  To add set hashabilty using mixins,
-   inherit from both :meth:`Set` and :meth:`Hashable`, then define
-   ``__hash__ = Set._hash``.
-
-.. seealso::
-
-   * `OrderedSet recipe <http://code.activestate.com/recipes/576694/>`_ for an
-     example built on :class:`MutableSet`.
-
-   * For more about ABCs, see the :mod:`abc` module and :pep:`3119`.

Modified: python/branches/pep-3151/Doc/library/colorsys.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/colorsys.rst	(original)
+++ python/branches/pep-3151/Doc/library/colorsys.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Conversion functions between RGB and other color systems.
 .. sectionauthor:: David Ascher <da at python.net>
 
+**Source code:** :source:`Lib/colorsys.py`
+
+--------------
 
 The :mod:`colorsys` module defines bidirectional conversions of color values
 between colors expressed in the RGB (Red Green Blue) color space used in

Modified: python/branches/pep-3151/Doc/library/compileall.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/compileall.rst	(original)
+++ python/branches/pep-3151/Doc/library/compileall.rst	Sat Feb 26 08:16:32 2011
@@ -6,47 +6,149 @@
 
 
 This module provides some utility functions to support installing Python
-libraries.  These functions compile Python source files in a directory tree,
-allowing users without permission to write to the libraries to take advantage of
-cached byte-code files.
-
-This module may also be used as a script (using the :option:`-m` Python flag) to
-compile Python sources.  Directories to recursively traverse (passing
-:option:`-l` stops the recursive behavior) for sources are listed on the command
-line.  If no arguments are given, the invocation is equivalent to ``-l
-sys.path``.  Printing lists of the files compiled can be disabled with the
-:option:`-q` flag.  In addition, the :option:`-x` option takes a regular
-expression argument.  All files that match the expression will be skipped.
-The :option:`-b` flag may be given to write legacy ``.pyc`` file path names,
-otherwise :pep:`3147` style byte-compiled path names are written.
+libraries.  These functions compile Python source files in a directory tree.
+This module can be used to create the cached byte-code files at library
+installation time, which makes them available for use even by users who don't
+have write permission to the library directories.
 
 
-.. function:: compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None, quiet=False, legacy=False)
+Command-line use
+----------------
+
+This module can work as a script (using :program:`python -m compileall`) to
+compile Python sources.
+
+.. program:: compileall
+
+.. cmdoption:: [directory|file]...
+
+   Positional arguments are files to compile or directories that contain
+   source files, traversed recursively.  If no argument is given, behave as if
+   the command line was ``-l <directories from sys.path>``.
+
+.. cmdoption:: -l
+
+   Do not recurse into subdirectories, only compile source code files directly
+   contained in the named or implied directories.
+
+.. cmdoption:: -f
+
+   Force rebuild even if timestamps are up-to-date.
+
+.. cmdoption:: -q
+
+   Do not print the list of files compiled, print only error messages.
+
+.. cmdoption:: -d destdir
+
+   Directory prepended to the path to each file being compiled.  This will
+   appear in compilation time tracebacks, and is also compiled in to the
+   byte-code file, where it will be used in tracebacks and other messages in
+   cases where the source file does not exist at the time the byte-code file is
+   executed.
+
+.. cmdoption:: -x regex
+
+   regex is used to search the full path to each file considered for
+   compilation, and if the regex produces a match, the file is skipped.
+
+.. cmdoption:: -i list
+
+   Read the file ``list`` and add each line that it contains to the list of
+   files and directories to compile.  If ``list`` is ``-``, read lines from
+   ``stdin``.
+
+.. cmdoption:: -b
+
+   Write the byte-code files to their legacy locations and names, which may
+   overwrite byte-code files created by another version of Python.  The default
+   is to write files to their :pep:`3147` locations and names, which allows
+   byte-code files from multiple versions of Python to coexist.
+
+.. versionchanged:: 3.2
+   Added the ``-i``, ``-b`` and ``-h`` options.
+
+
+Public functions
+----------------
+
+.. function:: compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None, quiet=False, legacy=False, optimize=-1)
 
    Recursively descend the directory tree named by *dir*, compiling all :file:`.py`
-   files along the way.  The *maxlevels* parameter is used to limit the depth of
-   the recursion; it defaults to ``10``.  If *ddir* is given, it is used as the
-   base path from  which the filenames used in error messages will be generated.
+   files along the way.
+
+   The *maxlevels* parameter is used to limit the depth of the recursion; it
+   defaults to ``10``.
+
+   If *ddir* is given, it is prepended to the path to each file being compiled
+   for use in compilation time tracebacks, and is also compiled in to the
+   byte-code file, where it will be used in tracebacks and other messages in
+   cases where the source file does not exist at the time the byte-code file is
+   executed.
+
    If *force* is true, modules are re-compiled even if the timestamps are up to
    date.
 
-   If *rx* is given, it specifies a regular expression of file names to exclude
-   from the search; that expression is searched for in the full path.
+   If *rx* is given, its search method is called on the complete path to each
+   file considered for compilation, and if it returns a true value, the file
+   is skipped.
+
+   If *quiet* is true, nothing is printed to the standard output unless errors
+   occur.
+
+   If *legacy* is true, byte-code files are written to their legacy locations
+   and names, which may overwrite byte-code files created by another version of
+   Python.  The default is to write files to their :pep:`3147` locations and
+   names, which allows byte-code files from multiple versions of Python to
+   coexist.
+
+   *optimize* specifies the optimization level for the compiler.  It is passed to
+   the built-in :func:`compile` function.
+
+   .. versionchanged:: 3.2
+      Added the *legacy* and *optimize* parameter.
+
 
-   If *quiet* is true, nothing is printed to the standard output in normal
-   operation.
+.. function:: compile_file(fullname, ddir=None, force=False, rx=None, quiet=False, legacy=False, optimize=-1)
 
-   If *legacy* is true, old-style ``.pyc`` file path names are written,
-   otherwise (the default), :pep:`3147` style path names are written.
+   Compile the file with path *fullname*.
 
+   If *ddir* is given, it is prepended to the path to the file being compiled
+   for use in compilation time tracebacks, and is also compiled in to the
+   byte-code file, where it will be used in tracebacks and other messages in
+   cases where the source file does not exist at the time the byte-code file is
+   executed.
 
-.. function:: compile_path(skip_curdir=True, maxlevels=0, force=False, legacy=False)
+   If *rx* is given, its search method is passed the full path name to the
+   file being compiled, and if it returns a true value, the file is not
+   compiled and ``True`` is returned.
+
+   If *quiet* is true, nothing is printed to the standard output unless errors
+   occur.
+
+   If *legacy* is true, byte-code files are written to their legacy locations
+   and names, which may overwrite byte-code files created by another version of
+   Python.  The default is to write files to their :pep:`3147` locations and
+   names, which allows byte-code files from multiple versions of Python to
+   coexist.
+
+   *optimize* specifies the optimization level for the compiler.  It is passed to
+   the built-in :func:`compile` function.
+
+   .. versionadded:: 3.2
+
+
+.. function:: compile_path(skip_curdir=True, maxlevels=0, force=False, legacy=False, optimize=-1)
 
    Byte-compile all the :file:`.py` files found along ``sys.path``. If
-   *skip_curdir* is true (the default), the current directory is not included in
-   the search.  The *maxlevels* parameter defaults to ``0``, and the *force*
-   and *legacy* parameters default to ``False``. All are
-   passed to the :func:`compile_dir` function.
+   *skip_curdir* is true (the default), the current directory is not included
+   in the search.  All other parameters are passed to the :func:`compile_dir`
+   function.  Note that unlike the other compile functions, ``maxlevels``
+   defaults to ``0``.
+
+   .. versionchanged:: 3.2
+      Added the *legacy* and *optimize* parameter.
+
 
 To force a recompile of all the :file:`.py` files in the :file:`Lib/`
 subdirectory and all its subdirectories::
@@ -64,4 +166,3 @@
 
    Module :mod:`py_compile`
       Byte-compile a single source file.
-

Modified: python/branches/pep-3151/Doc/library/concurrent.futures.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/concurrent.futures.rst	(original)
+++ python/branches/pep-3151/Doc/library/concurrent.futures.rst	Sat Feb 26 08:16:32 2011
@@ -1,16 +1,21 @@
-:mod:`concurrent.futures` --- Concurrent computation
-====================================================
+:mod:`concurrent.futures` --- Launching parallel tasks
+======================================================
 
 .. module:: concurrent.futures
    :synopsis: Execute computations concurrently using threads or processes.
 
+**Source code:** :source:`Lib/concurrent/futures/thread.py`
+and :source:`Lib/concurrent/futures/process.py`
+
 .. versionadded:: 3.2
 
+--------------
+
 The :mod:`concurrent.futures` module provides a high-level interface for
 asynchronously executing callables.
 
 The asynchronous execution can be be performed with threads, using
-:class:`ThreadPoolExecutor`, or seperate processes, using
+:class:`ThreadPoolExecutor`, or separate processes, using
 :class:`ProcessPoolExecutor`.  Both implement the same interface, which is
 defined by the abstract :class:`Executor` class.
 
@@ -216,7 +221,7 @@
     .. method:: cancel()
 
        Attempt to cancel the call.  If the call is currently being executed and
-       cannot be cancelled and the method will return ``False``, otherwise the
+       cannot be cancelled then the method will return ``False``, otherwise the
        call will be cancelled and the method will return ``True``.
 
     .. method:: cancelled()

Modified: python/branches/pep-3151/Doc/library/configparser.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/configparser.rst	(original)
+++ python/branches/pep-3151/Doc/library/configparser.rst	Sat Feb 26 08:16:32 2011
@@ -17,11 +17,10 @@
    single: ini file
    single: Windows ini file
 
-This module provides the classes :class:`RawConfigParser` and
-:class:`SafeConfigParser`.  They implement a basic configuration file parser
-language which provides a structure similar to what you would find in Microsoft
-Windows INI files.  You can use this to write Python programs which can be
-customized by end users easily.
+This module provides the :class:`ConfigParser` class which implements a basic
+configuration language which provides a structure similar to what's found in
+Microsoft Windows INI files.  You can use this to write Python programs which
+can be customized by end users easily.
 
 .. note::
 
@@ -34,272 +33,340 @@
       Support for a creating Unix shell-like mini-languages which can be used
       as an alternate format for application configuration files.
 
+   Module :mod:`json`
+      The json module implements a subset of JavaScript syntax which can also
+      be used for this purpose.
+
+
 Quick Start
 -----------
 
-.. highlightlang:: none
+Let's take a very basic configuration file that looks like this:
 
-Let's take a very basic configuration file that looks like this::
+.. code-block:: ini
 
-  [DEFAULT]
-    ServerAliveInterval = 45
-    Compression = yes
-    CompressionLevel = 9
-    ForwardX11 = yes
+   [DEFAULT]
+   ServerAliveInterval = 45
+   Compression = yes
+   CompressionLevel = 9
+   ForwardX11 = yes
 
-  [bitbucket.org]
-    User = hg
+   [bitbucket.org]
+   User = hg
 
-  [topsecret.server.com]
-    Port = 50022
-    ForwardX11 = no
+   [topsecret.server.com]
+   Port = 50022
+   ForwardX11 = no
 
-The supported file structure of INI files is described `in the following section
-<#supported-ini-file-structure>`_, fow now all there's to know is that the file
+The structure of INI files is described `in the following section
+<#supported-ini-file-structure>`_.  Essentially, the file
 consists of sections, each of which contains keys with values.
-:mod:`configparser` classes can read and write such files. Let's start by
+:mod:`configparser` classes can read and write such files.  Let's start by
 creating the above configuration file programatically.
 
-.. highlightlang:: python
 .. doctest::
 
-    >>> import configparser
-    >>> config = configparser.RawConfigParser()
-    >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
-    ...                      'Compression': 'yes',
-    ...                      'CompressionLevel': '9'}
-    >>> config['bitbucket.org'] = {}
-    >>> config['bitbucket.org']['User'] = 'hg'
-    >>> config['topsecret.server.com'] = {}
-    >>> topsecret = config['topsecret.server.com']
-    >>> topsecret['Port'] = '50022'     # mutates the parser
-    >>> topsecret['ForwardX11'] = 'no'  # same here
-    >>> config['DEFAULT']['ForwardX11'] = 'yes'
-    >>> with open('example.ini', 'w') as configfile:
-    ...   config.write(configfile)
-    ...
-
-As you can see, we can treat a config parser just like a dictionary. There are
-a few differences, `outlined later on <#mapping-protocol-access>`_, but the
-behaviour is very close to what you'd expect from a dictionary.
+   >>> import configparser
+   >>> config = configparser.ConfigParser()
+   >>> config['DEFAULT'] = {'ServerAliveInterval': '45',
+   ...                      'Compression': 'yes',
+   ...                      'CompressionLevel': '9'}
+   >>> config['bitbucket.org'] = {}
+   >>> config['bitbucket.org']['User'] = 'hg'
+   >>> config['topsecret.server.com'] = {}
+   >>> topsecret = config['topsecret.server.com']
+   >>> topsecret['Port'] = '50022'     # mutates the parser
+   >>> topsecret['ForwardX11'] = 'no'  # same here
+   >>> config['DEFAULT']['ForwardX11'] = 'yes'
+   >>> with open('example.ini', 'w') as configfile:
+   ...   config.write(configfile)
+   ...
+
+As you can see, we can treat a config parser much like a dictionary.
+There are differences, `outlined later <#mapping-protocol-access>`_, but
+the behavior is very close to what you would expect from a dictionary.
 
-Now that we've created and saved a configuration file, let's try reading it
-back and exploring the data it holds.
+Now that we have created and saved a configuration file, let's read it
+back and explore the data it holds.
 
-.. highlightlang:: python
 .. doctest::
 
-    >>> import configparser
-    >>> config = configparser.RawConfigParser()
-    >>> config.sections()
-    []
-    >>> config.read('example.ini')
-    ['example.ini']
-    >>> config.sections()
-    ['bitbucket.org', 'topsecret.server.com']
-    >>> 'bitbucket.org' in config
-    True
-    >>> 'bytebong.com' in config
-    False
-    >>> config['bitbucket.org']['User']
-    'hg'
-    >>> config['DEFAULT']['Compression']
-    'yes'
-    >>> topsecret = config['topsecret.server.com']
-    >>> topsecret['ForwardX11']
-    'no'
-    >>> topsecret['Port']
-    '50022'
-    >>> for key in config['bitbucket.org']: print(key)
-    ...
-    user
-    compressionlevel
-    serveraliveinterval
-    compression
-    forwardx11
-    >>> config['bitbucket.org']['ForwardX11']
-    'yes'
+   >>> import configparser
+   >>> config = configparser.ConfigParser()
+   >>> config.sections()
+   []
+   >>> config.read('example.ini')
+   ['example.ini']
+   >>> config.sections()
+   ['bitbucket.org', 'topsecret.server.com']
+   >>> 'bitbucket.org' in config
+   True
+   >>> 'bytebong.com' in config
+   False
+   >>> config['bitbucket.org']['User']
+   'hg'
+   >>> config['DEFAULT']['Compression']
+   'yes'
+   >>> topsecret = config['topsecret.server.com']
+   >>> topsecret['ForwardX11']
+   'no'
+   >>> topsecret['Port']
+   '50022'
+   >>> for key in config['bitbucket.org']: print(key)
+   ...
+   user
+   compressionlevel
+   serveraliveinterval
+   compression
+   forwardx11
+   >>> config['bitbucket.org']['ForwardX11']
+   'yes'
 
-As we can see above, the API is pretty straight forward. The only bit of magic
+As we can see above, the API is pretty straightforward.  The only bit of magic
 involves the ``DEFAULT`` section which provides default values for all other
-sections [customizable]_. Another thing to note is that keys in sections are
-case-insensitive so they're stored in lowercase [customizable]_.
+sections [1]_.  Note also that keys in sections are
+case-insensitive and stored in lowercase [1]_.
+
 
 Supported Datatypes
 -------------------
 
 Config parsers do not guess datatypes of values in configuration files, always
-storing them internally as strings. This means that if you need other datatypes,
-you should convert on your own:
+storing them internally as strings.  This means that if you need other
+datatypes, you should convert on your own:
 
-.. highlightlang:: python
 .. doctest::
 
-    >>> int(topsecret['Port'])
-    50022
-    >>> float(topsecret['CompressionLevel'])
-    9.0
-
-Converting to the boolean type is not that simple, though. Wrapping the return
-value around ``bool()`` would do us no good since ``bool('False')`` is still
-``True``. This is why config parsers also provide :meth:`getboolean`. This handy
-method is also case insensitive and correctly recognizes boolean values from
-``'yes'``/``'no'``, ``'on'``/``'off'`` and ``'1'``/``'0'`` [customizable]_.  An
-example of getting the boolean value:
+   >>> int(topsecret['Port'])
+   50022
+   >>> float(topsecret['CompressionLevel'])
+   9.0
+
+Extracting Boolean values is not that simple, though.  Passing the value
+to ``bool()`` would do no good since ``bool('False')`` is still
+``True``.  This is why config parsers also provide :meth:`getboolean`.
+This method is case-insensitive and recognizes Boolean values from
+``'yes'``/``'no'``, ``'on'``/``'off'`` and ``'1'``/``'0'`` [1]_.
+For example:
 
-.. highlightlang:: python
 .. doctest::
 
-    >>> topsecret.getboolean('ForwardX11')
-    False
-    >>> config['bitbucket.org'].getboolean('ForwardX11')
-    True
-    >>> config.getboolean('bitbucket.org', 'Compression')
-    True
+   >>> topsecret.getboolean('ForwardX11')
+   False
+   >>> config['bitbucket.org'].getboolean('ForwardX11')
+   True
+   >>> config.getboolean('bitbucket.org', 'Compression')
+   True
 
 Apart from :meth:`getboolean`, config parsers also provide equivalent
-:meth:`getint` and :meth:`getfloat` methods but these are far less useful
-because explicit casting is enough for these types.
+:meth:`getint` and :meth:`getfloat` methods, but these are far less
+useful since conversion using :func:`int` and :func:`float` is
+sufficient for these types.
+
 
 Fallback Values
 ---------------
 
-As with a regular dictionary, you can use a section's :meth:`get` method to
+As with a dictionary, you can use a section's :meth:`get` method to
 provide fallback values:
 
-.. highlightlang:: python
 .. doctest::
 
-    >>> topsecret.get('Port')
-    '50022'
-    >>> topsecret.get('CompressionLevel')
-    '9'
-    >>> topsecret.get('Cipher')
-    >>> topsecret.get('Cipher', '3des-cbc')
-    '3des-cbc'
-
-Please note that default values have precedence over fallback values. For
-instance, in our example the ``CompressionLevel`` key was specified only in the
-``DEFAULT`` section. If we try to get it from the section
-``topsecret.server.com``, we will always get the default, even if we specify
-a fallback:
+   >>> topsecret.get('Port')
+   '50022'
+   >>> topsecret.get('CompressionLevel')
+   '9'
+   >>> topsecret.get('Cipher')
+   >>> topsecret.get('Cipher', '3des-cbc')
+   '3des-cbc'
+
+Please note that default values have precedence over fallback values.
+For instance, in our example the ``'CompressionLevel'`` key was
+specified only in the ``'DEFAULT'`` section.  If we try to get it from
+the section ``'topsecret.server.com'``, we will always get the default,
+even if we specify a fallback:
 
-.. highlightlang:: python
 .. doctest::
 
-    >>> topsecret.get('CompressionLevel', '3')
-    '9'
+   >>> topsecret.get('CompressionLevel', '3')
+   '9'
 
 One more thing to be aware of is that the parser-level :meth:`get` method
 provides a custom, more complex interface, maintained for backwards
-compatibility. When using this method, a fallback value can be provided via the
-``fallback`` keyword-only argument:
+compatibility.  When using this method, a fallback value can be provided via
+the ``fallback`` keyword-only argument:
 
-.. highlightlang:: python
 .. doctest::
 
-    >>> config.get('bitbucket.org', 'monster',
-    ...            fallback='No such things as monsters')
-    'No such things as monsters'
+   >>> config.get('bitbucket.org', 'monster',
+   ...            fallback='No such things as monsters')
+   'No such things as monsters'
 
 The same ``fallback`` argument can be used with the :meth:`getint`,
 :meth:`getfloat` and :meth:`getboolean` methods, for example:
 
-.. highlightlang:: python
 .. doctest::
 
-    >>> 'BatchMode' in topsecret
-    False
-    >>> topsecret.getboolean('BatchMode', fallback=True)
-    True
-    >>> config['DEFAULT']['BatchMode'] = 'no'
-    >>> topsecret.getboolean('BatchMode', fallback=True)
-    False
+   >>> 'BatchMode' in topsecret
+   False
+   >>> topsecret.getboolean('BatchMode', fallback=True)
+   True
+   >>> config['DEFAULT']['BatchMode'] = 'no'
+   >>> topsecret.getboolean('BatchMode', fallback=True)
+   False
+
 
 Supported INI File Structure
 ----------------------------
 
 A configuration file consists of sections, each led by a ``[section]`` header,
 followed by key/value entries separated by a specific string (``=`` or ``:`` by
-default [customizable]_). By default, section names are case sensitive but keys
-are not [customizable]_. Leading und trailing whitespace is removed from keys and from values.
+default [1]_).  By default, section names are case sensitive but keys are not
+[1]_.  Leading and trailing whitespace is removed from keys and values.
 Values can be omitted, in which case the key/value delimiter may also be left
 out.  Values can also span multiple lines, as long as they are indented deeper
 than the first line of the value.  Depending on the parser's mode, blank lines
 may be treated as parts of multiline values or ignored.
 
-Configuration files may include comments, prefixed by specific characters (``#``
-and ``;`` by default [customizable]_).  Comments may appear on their own in an
-otherwise empty line, or may be entered in lines holding values or section
-names.  In the latter case, they need to be preceded by a whitespace character
-to be recognized as a comment.  (For backwards compatibility, by default only
-``;`` starts an inline comment, while ``#`` does not [customizable]_.)
-
-On top of the core functionality, :class:`SafeConfigParser` supports
-interpolation.  This means values can contain format strings which refer to
-other values in the same section, or values in a special ``DEFAULT`` section
-[customizable]_.  Additional defaults can be provided on initialization.
-
-.. highlightlang:: none
-
-For example::
-
-   [Paths]
-   home_dir: /Users
-   my_dir: %(home_dir)s/lumberjack
-   my_pictures: %(my_dir)s/Pictures
+Configuration files may include comments, prefixed by specific
+characters (``#`` and ``;`` by default [1]_).  Comments may appear on
+their own on an otherwise empty line, possibly indented. [1]_
+
+For example:
+
+.. code-block:: ini
+
+   [Simple Values]
+   key=value
+   spaces in keys=allowed
+   spaces in values=allowed as well
+   spaces around the delimiter = obviously
+   you can also use : to delimit keys from values
+
+   [All Values Are Strings]
+   values like this: 1000000
+   or this: 3.14159265359
+   are they treated as numbers? : no
+   integers, floats and booleans are held as: strings
+   can use the API to get converted values directly: true
 
    [Multiline Values]
    chorus: I'm a lumberjack, and I'm okay
-      I sleep all night and I work all day
+       I sleep all night and I work all day
 
    [No Values]
    key_without_value
    empty string value here =
 
-   [You can use comments] ; after a useful line
-   ; in an empty line
-   after: a_value ; here's another comment
-   inside: a         ;comment
-           multiline ;comment
-           value!    ;comment
-
-      [Sections Can Be Indented]
-         can_values_be_as_well = True
-         does_that_mean_anything_special = False
-         purpose = formatting for readability
-         multiline_values = are
-            handled just fine as
-            long as they are indented
-            deeper than the first line
-            of a value
-         # Did I mention we can indent comments, too?
-
-In the example above, :class:`SafeConfigParser` would resolve ``%(home_dir)s``
-to the value of ``home_dir`` (``/Users`` in this case).  ``%(my_dir)s`` in
-effect would resolve to ``/Users/lumberjack``.  All interpolations are done on
-demand so keys used in the chain of references do not have to be specified in
-any specific order in the configuration file.
-
-:class:`RawConfigParser` would simply return ``%(my_dir)s/Pictures`` as the
-value of ``my_pictures`` and ``%(home_dir)s/lumberjack`` as the value of
-``my_dir``.  Other features presented in the example are handled in the same
-manner by both parsers.
+   [You can use comments]
+   # like this
+   ; or this
+
+   # By default only in an empty line.
+   # Inline comments can be harmful because they prevent users
+   # from using the delimiting characters as parts of values.
+   # That being said, this can be customized.
+
+       [Sections Can Be Indented]
+           can_values_be_as_well = True
+           does_that_mean_anything_special = False
+           purpose = formatting for readability
+           multiline_values = are
+               handled just fine as
+               long as they are indented
+               deeper than the first line
+               of a value
+           # Did I mention we can indent comments, too?
+
+
+Interpolation of values
+-----------------------
+
+On top of the core functionality, :class:`ConfigParser` supports
+interpolation.  This means values can be preprocessed before returning them
+from ``get()`` calls.
+
+.. class:: BasicInterpolation()
+
+   The default implementation used by :class:`ConfigParser`.  It enables
+   values to contain format strings which refer to other values in the same
+   section, or values in the special default section [1]_.  Additional default
+   values can be provided on initialization.
+
+   For example:
+
+   .. code-block:: ini
+
+      [Paths]
+      home_dir: /Users
+      my_dir: %(home_dir)s/lumberjack
+      my_pictures: %(my_dir)s/Pictures
+
+
+   In the example above, :class:`ConfigParser` with *interpolation* set to
+   ``BasicInterpolation()`` would resolve ``%(home_dir)s`` to the value of
+   ``home_dir`` (``/Users`` in this case).  ``%(my_dir)s`` in effect would
+   resolve to ``/Users/lumberjack``.  All interpolations are done on demand so
+   keys used in the chain of references do not have to be specified in any
+   specific order in the configuration file.
+
+   With ``interpolation`` set to ``None``, the parser would simply return
+   ``%(my_dir)s/Pictures`` as the value of ``my_pictures`` and
+   ``%(home_dir)s/lumberjack`` as the value of ``my_dir``.
+
+.. class:: ExtendedInterpolation()
+
+   An alternative handler for interpolation which implements a more advanced
+   syntax, used for instance in ``zc.buildout``. Extended interpolation is
+   using ``${section:option}`` to denote a value from a foreign section.
+   Interpolation can span multiple levels. For convenience, if the ``section:``
+   part is omitted, interpolation defaults to the current section (and possibly
+   the default values from the special section).
+
+   For example, the configuration specified above with basic interpolation,
+   would look like this with extended interpolation:
+
+   .. code-block:: ini
+
+      [Paths]
+      home_dir: /Users
+      my_dir: ${home_dir}/lumberjack
+      my_pictures: ${my_dir}/Pictures
+
+   Values from other sections can be fetched as well:
+
+   .. code-block:: ini
+
+      [Common]
+      home_dir: /Users
+      library_dir: /Library
+      system_dir: /System
+      macports_dir: /opt/local
+
+      [Frameworks]
+      Python: 3.2
+      path: ${Common:system_dir}/Library/Frameworks/
+
+      [Arthur]
+      nickname: Two Sheds
+      last_name: Jackson
+      my_dir: ${Common:home_dir}/twosheds
+      my_pictures: ${my_dir}/Pictures
+      python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
 
 Mapping Protocol Access
 -----------------------
 
 .. versionadded:: 3.2
-.. highlightlang:: python
 
 Mapping protocol access is a generic name for functionality that enables using
-custom objects as if they were dictionaries. In case of :mod:`configparser`,
+custom objects as if they were dictionaries.  In case of :mod:`configparser`,
 the mapping interface implementation is using the
 ``parser['section']['option']`` notation.
 
 ``parser['section']`` in particular returns a proxy for the section's data in
-the parser. This means that the values are not copied but they are taken from
-the original parser on demand. What's even more important is that when values
+the parser.  This means that the values are not copied but they are taken from
+the original parser on demand.  What's even more important is that when values
 are changed on a section proxy, they are actually mutated in the original
 parser.
 
@@ -307,288 +374,388 @@
 The mapping interface is complete and adheres to the ``MutableMapping`` ABC.
 However, there are a few differences that should be taken into account:
 
-* by default, all keys in sections are accessible in a case-insensitive manner
-  [customizable]_. E.g. ``for option in parser["section"]`` yields only
-  ``optionxform``'ed option key names. This means lowercased keys by default.
-  At the same time, for a section that holds the key ``"a"``, both expressions
-  return ``True``::
+* By default, all keys in sections are accessible in a case-insensitive manner
+  [1]_.  E.g. ``for option in parser["section"]`` yields only ``optionxform``'ed
+  option key names.  This means lowercased keys by default.  At the same time,
+  for a section that holds the key ``'a'``, both expressions return ``True``::
 
-  "a" in parser["section"]
-  "A" in parser["section"]
+     "a" in parser["section"]
+     "A" in parser["section"]
 
-* all sections include ``DEFAULTSECT`` values as well which means that
-  ``.clear()`` on a section may not leave the section visibly empty. This is
+* All sections include ``DEFAULTSECT`` values as well which means that
+  ``.clear()`` on a section may not leave the section visibly empty.  This is
   because default values cannot be deleted from the section (because technically
-  they are not there). If they are overriden in the section, deleting causes the
-  default value to be visible again. Trying to delete a default value causes
-  a ``KeyError``.
-
-* trying to delete the ``DEFAULTSECT`` throws ``ValueError``
-
-* there are two parser-level methods in the legacy API that hide
-  the dictionary interface and are incompatible:
-
-  * ``parser.get(section, option, **kwargs)`` - the second argument is **not**
-    a fallback value
-
-  * ``parser.items(section)`` - this returns a list of ``(option, value)``
-    pairs for a specified ``section``.
+  they are not there).  If they are overriden in the section, deleting causes
+  the default value to be visible again.  Trying to delete a default value
+  causes a ``KeyError``.
+
+* Trying to delete the ``DEFAULTSECT`` raises ``ValueError``.
+
+* ``parser.get(section, option, **kwargs)`` - the second argument is **not**
+  a fallback value. Note however that the section-level ``get()`` methods are
+  compatible both with the mapping protocol and the classic configparser API.
+
+* ``parser.items()`` is compatible with the mapping protocol (returns a list of
+  *section_name*, *section_proxy* pairs including the DEFAULTSECT).  However,
+  this method can also be invoked with arguments: ``parser.items(section, raw,
+  vars)``. The latter call returns a list of *option*, *value* pairs for
+  a specified ``section``, with all interpolations expanded (unless
+  ``raw=True`` is provided).
 
 The mapping protocol is implemented on top of the existing legacy API so that
-subclassing the original interface makes the mappings work as expected as well.
-One difference is the explicit lack of support for the `__name__` special key.
-This is because the existing behaviour of `__name__` is very inconsistent and
-supporting it would only lead to problems. Details `here
-<http://mail.python.org/pipermail/python-dev/2010-July/102556.html>`_.
+subclasses overriding the original interface still should have mappings working
+as expected.
+
 
 Customizing Parser Behaviour
 ----------------------------
 
 There are nearly as many INI format variants as there are applications using it.
 :mod:`configparser` goes a long way to provide support for the largest sensible
-set of INI styles available. The default functionality is mainly dictated by
+set of INI styles available.  The default functionality is mainly dictated by
 historical background and it's very likely that you will want to customize some
 of the features.
 
-The most natural way to change the way a specific config parser works is to use
+The most common way to change the way a specific config parser works is to use
 the :meth:`__init__` options:
 
 * *defaults*, default value: ``None``
 
   This option accepts a dictionary of key-value pairs which will be initially
-  put in the ``DEFAULTSECT``. This makes for an elegant way to support concise
-  configuration files that don't specify values which are the same as the
-  documented default.
+  put in the ``DEFAULT`` section.  This makes for an elegant way to support
+  concise configuration files that don't specify values which are the same as
+  the documented default.
 
-  Hint: if you want to specify default values for a specific section, use the
+  Hint: if you want to specify default values for a specific section, use
   :meth:`read_dict` before you read the actual file.
 
 * *dict_type*, default value: :class:`collections.OrderedDict`
 
   This option has a major impact on how the mapping protocol will behave and how
-  the written configuration files will look like. With the default ordered
+  the written configuration files look.  With the default ordered
   dictionary, every section is stored in the order they were added to the
-  parser. Same goes for options within sections.
+  parser.  Same goes for options within sections.
 
   An alternative dictionary type can be used for example to sort sections and
-  options on write-back. You can also use a regular dictionary for performance
+  options on write-back.  You can also use a regular dictionary for performance
   reasons.
 
   Please note: there are ways to add a set of key-value pairs in a single
-  operation. When you use a regular dictionary in those operations, the order of
-  the keys may be random. For example:
+  operation.  When you use a regular dictionary in those operations, the order
+  of the keys may be random.  For example:
 
-  .. highlightlang:: python
   .. doctest::
 
-    >>> parser = configparser.RawConfigParser()
-    >>> parser.read_dict({'section1': {'key1': 'value1',
-    ...                                'key2': 'value2',
-    ...                                'key3': 'value3'},
-    ...                   'section2': {'keyA': 'valueA',
-    ...                                'keyB': 'valueB',
-    ...                                'keyC': 'valueC'},
-    ...                   'section3': {'foo': 'x',
-    ...                                'bar': 'y',
-    ...                                'baz': 'z'}
-    ... })
-    >>> parser.sections()
-    ['section3', 'section2', 'section1']
-    >>> [option for option in parser['section3']]
-    ['baz', 'foo', 'bar']
+     >>> parser = configparser.ConfigParser()
+     >>> parser.read_dict({'section1': {'key1': 'value1',
+     ...                                'key2': 'value2',
+     ...                                'key3': 'value3'},
+     ...                   'section2': {'keyA': 'valueA',
+     ...                                'keyB': 'valueB',
+     ...                                'keyC': 'valueC'},
+     ...                   'section3': {'foo': 'x',
+     ...                                'bar': 'y',
+     ...                                'baz': 'z'}
+     ... })
+     >>> parser.sections()
+     ['section3', 'section2', 'section1']
+     >>> [option for option in parser['section3']]
+     ['baz', 'foo', 'bar']
 
   In these operations you need to use an ordered dictionary as well:
 
-  .. highlightlang:: python
   .. doctest::
 
-    >>> from collections import OrderedDict
-    >>> parser = configparser.RawConfigParser()
-    >>> parser.read_dict(
-    ...   OrderedDict((
-    ...     ('s1',
-    ...      OrderedDict((
-    ...        ('1', '2'),
-    ...        ('3', '4'),
-    ...        ('5', '6'),
-    ...      ))
-    ...     ),
-    ...     ('s2',
-    ...      OrderedDict((
-    ...        ('a', 'b'),
-    ...        ('c', 'd'),
-    ...        ('e', 'f'),
-    ...      ))
-    ...     ),
-    ...   ))
-    ... )
-    >>> parser.sections()
-    ['s1', 's2']
-    >>> [option for option in parser['s1']]
-    ['1', '3', '5']
-    >>> [option for option in parser['s2'].values()]
-    ['b', 'd', 'f']
+     >>> from collections import OrderedDict
+     >>> parser = configparser.ConfigParser()
+     >>> parser.read_dict(
+     ...   OrderedDict((
+     ...     ('s1',
+     ...      OrderedDict((
+     ...        ('1', '2'),
+     ...        ('3', '4'),
+     ...        ('5', '6'),
+     ...      ))
+     ...     ),
+     ...     ('s2',
+     ...      OrderedDict((
+     ...        ('a', 'b'),
+     ...        ('c', 'd'),
+     ...        ('e', 'f'),
+     ...      ))
+     ...     ),
+     ...   ))
+     ... )
+     >>> parser.sections()
+     ['s1', 's2']
+     >>> [option for option in parser['s1']]
+     ['1', '3', '5']
+     >>> [option for option in parser['s2'].values()]
+     ['b', 'd', 'f']
 
 * *allow_no_value*, default value: ``False``
 
   Some configuration files are known to include settings without values, but
   which otherwise conform to the syntax supported by :mod:`configparser`.  The
-  *allow_no_value* parameter to the :meth:`__init__` method can be used to
+  *allow_no_value* parameter to the constructor can be used to
   indicate that such values should be accepted:
 
-  .. highlightlang:: python
   .. doctest::
 
-    >>> import configparser
+     >>> import configparser
 
-    >>> sample_config = """
-    ... [mysqld]
-    ...   user = mysql
-    ...   pid-file = /var/run/mysqld/mysqld.pid
-    ...   skip-external-locking
-    ...   old_passwords = 1
-    ...   skip-bdb
-    ...   skip-innodb # we don't need ACID today
-    ... """
-    >>> config = configparser.RawConfigParser(allow_no_value=True)
-    >>> config.read_string(sample_config)
-
-    >>> # Settings with values are treated as before:
-    >>> config["mysqld"]["user"]
-    'mysql'
-
-    >>> # Settings without values provide None:
-    >>> config["mysqld"]["skip-bdb"]
-
-    >>> # Settings which aren't specified still raise an error:
-    >>> config["mysqld"]["does-not-exist"]
-    Traceback (most recent call last):
-      ...
-    KeyError: 'does-not-exist'
+     >>> sample_config = """
+     ... [mysqld]
+     ...   user = mysql
+     ...   pid-file = /var/run/mysqld/mysqld.pid
+     ...   skip-external-locking
+     ...   old_passwords = 1
+     ...   skip-bdb
+     ...   # we don't need ACID today
+     ...   skip-innodb
+     ... """
+     >>> config = configparser.ConfigParser(allow_no_value=True)
+     >>> config.read_string(sample_config)
+
+     >>> # Settings with values are treated as before:
+     >>> config["mysqld"]["user"]
+     'mysql'
+
+     >>> # Settings without values provide None:
+     >>> config["mysqld"]["skip-bdb"]
+
+     >>> # Settings which aren't specified still raise an error:
+     >>> config["mysqld"]["does-not-exist"]
+     Traceback (most recent call last):
+       ...
+     KeyError: 'does-not-exist'
 
 * *delimiters*, default value: ``('=', ':')``
 
   Delimiters are substrings that delimit keys from values within a section. The
   first occurence of a delimiting substring on a line is considered a delimiter.
-  This means values (but not keus) can contain substrings that are in the
-  *delimiters*.
+  This means values (but not keys) can contain the delimiters.
 
   See also the *space_around_delimiters* argument to
-  :meth:`RawConfigParser.write`.
+  :meth:`ConfigParser.write`.
+
+* *comment_prefixes*, default value: ``('#', ';')``
 
-* *comment_prefixes*, default value: ``_COMPATIBLE`` (``'#'`` valid on empty
-  lines, ``';'`` valid also on non-empty lines)
+* *inline_comment_prefixes*, default value: ``None``
 
-  Comment prefixes are substrings that indicate the start of a valid comment
-  within a config file. The peculiar default value allows for comments starting
-  with ``'#'`` or ``';'`` but only the latter can be used in a non-empty line.
-  This is obviously dictated by backwards compatibiliy. A more predictable
-  approach would be to specify prefixes as ``('#', ';')`` which will allow for
-  both prefixes to be used in non-empty lines.
+  Comment prefixes are strings that indicate the start of a valid comment within
+  a config file. *comment_prefixes* are used only on otherwise empty lines
+  (optionally indented) whereas *inline_comment_prefixes* can be used after
+  every valid value (e.g.  section names, options and empty lines as well). By
+  default inline comments are disabled and ``'#'`` and ``';'`` are used as
+  prefixes for whole line comments.
+
+  .. versionchanged:: 3.2
+     In previous versions of :mod:`configparser` behaviour matched
+     ``comment_prefixes=('#',';')`` and ``inline_comment_prefixes=(';',)``.
 
   Please note that config parsers don't support escaping of comment prefixes so
-  leaving characters out of *comment_prefixes* is a way of ensuring they can be
-  used as parts of keys or values.
+  using *inline_comment_prefixes* may prevent users from specifying option
+  values with characters used as comment prefixes. When in doubt, avoid setting
+  *inline_comment_prefixes*. In any circumstances, the only way of storing
+  comment prefix characters at the beginning of a line in multiline values is to
+  interpolate the prefix, for example::
+
+    >>> from configparser import ConfigParser, ExtendedInterpolation
+    >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
+    >>> # the default BasicInterpolation could be used as well
+    >>> parser.read_string("""
+    ... [DEFAULT]
+    ... hash = #
+    ...
+    ... [hashes]
+    ... shebang =
+    ...   ${hash}!/usr/bin/env python
+    ...   ${hash} -*- coding: utf-8 -*-
+    ...
+    ... extensions =
+    ...   enabled_extension
+    ...   another_extension
+    ...   #disabled_by_comment
+    ...   yet_another_extension
+    ...
+    ... interpolation not necessary = if # is not at line start
+    ... even in multiline values = line #1
+    ...   line #2
+    ...   line #3
+    ... """)
+    >>> print(parser['hashes']['shebang'])
+
+    #!/usr/bin/env python
+    # -*- coding: utf-8 -*-
+    >>> print(parser['hashes']['extensions'])
+
+    enabled_extension
+    another_extension
+    yet_another_extension
+    >>> print(parser['hashes']['interpolation not necessary'])
+    if # is not at line start
+    >>> print(parser['hashes']['even in multiline values'])
+    line #1
+    line #2
+    line #3
 
-* *strict*, default value: ``False``
+* *strict*, default value: ``True``
 
-  If set to ``True``, the parser will not allow for any section or option
+  When set to ``True``, the parser will not allow for any section or option
   duplicates while reading from a single source (using :meth:`read_file`,
-  :meth:`read_string` or :meth:`read_dict`). The default is ``False`` only
-  because of backwards compatibility reasons. It's recommended to use strict
+  :meth:`read_string` or :meth:`read_dict`). It is recommended to use strict
   parsers in new applications.
 
-* *empty_lines_in_values*, default value: ``True``
+  .. versionchanged:: 3.2
+     In previous versions of :mod:`configparser` behaviour matched
+     ``strict=False``.
 
-  .. highlightlang:: none
+* *empty_lines_in_values*, default value: ``True``
 
-  In config parsers, values can be multiline as long as they're indented deeper
-  than the key that holds them. By default parsers also let empty lines to be
-  parts of values. At the same time, keys can be arbitrarily indented themselves
-  to improve readability. In consequence, when configuration files get big and
-  complex, it's easy for the user to lose track of the file structure. Take for
-  instance::
-
-    [Section]
-    key = multiline
-      value with a gotcha
-
-     this = is still a part of the multiline value of 'key'
-
-
-  This can be especially problematic for the user to see if she's using
-  a proportional font to edit the file. That's why when your application does
-  not need values with empty lines, you should consider disallowing them. This
-  will make empty lines split keys every time. In the example above, it would
+  In config parsers, values can span multiple lines as long as they are
+  indented more than the key that holds them.  By default parsers also let
+  empty lines to be parts of values.  At the same time, keys can be arbitrarily
+  indented themselves to improve readability.  In consequence, when
+  configuration files get big and complex, it is easy for the user to lose
+  track of the file structure.  Take for instance:
+
+  .. code-block:: ini
+
+     [Section]
+     key = multiline
+       value with a gotcha
+
+      this = is still a part of the multiline value of 'key'
+
+  This can be especially problematic for the user to see if she's using a
+  proportional font to edit the file.  That is why when your application does
+  not need values with empty lines, you should consider disallowing them.  This
+  will make empty lines split keys every time.  In the example above, it would
   produce two keys, ``key`` and ``this``.
 
-.. highlightlang:: python
+* *default_section*, default value: ``configparser.DEFAULTSECT`` (that is:
+  ``"DEFAULT"``)
 
-More advanced customization may be achieved by overriding default values of the
-following parser members:
+  The convention of allowing a special section of default values for other
+  sections or interpolation purposes is a powerful concept of this library,
+  letting users create complex declarative configurations. This section is
+  normally called ``"DEFAULT"`` but this can be customized to point to any
+  other valid section name. Some typical values include: ``"general"`` or
+  ``"common"``. The name provided is used for recognizing default sections when
+  reading from any source and is used when writing configuration back to
+  a file. Its current value can be retrieved using the
+  ``parser_instance.default_section`` attribute and may be modified at runtime
+  (i.e. to convert files from one format to another).
+
+* *interpolation*, default value: ``configparser.BasicInterpolation``
+
+  Interpolation behaviour may be customized by providing a custom handler
+  through the *interpolation* argument. ``None`` can be used to turn off
+  interpolation completely, ``ExtendedInterpolation()`` provides a more
+  advanced variant inspired by ``zc.buildout``. More on the subject in the
+  `dedicated documentation section <#interpolation-of-values>`_.
+  :class:`RawConfigParser` has a default value of ``None``.
+
+
+More advanced customization may be achieved by overriding default values of
+these parser attributes.  The defaults are defined on the classes, so they
+may be overriden by subclasses or by attribute assignment.
 
-* `RawConfigParser.BOOLEAN_STATES`
+.. attribute:: BOOLEAN_STATES
 
   By default when using :meth:`getboolean`, config parsers consider the
   following values ``True``: ``'1'``, ``'yes'``, ``'true'``, ``'on'`` and the
-  following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``. You can
-  override this by specifying a custom dictionary of strings and their boolean
-  outcomes. For example:
+  following values ``False``: ``'0'``, ``'no'``, ``'false'``, ``'off'``.  You
+  can override this by specifying a custom dictionary of strings and their
+  Boolean outcomes. For example:
 
-  .. highlightlang:: python
   .. doctest::
 
-    >>> custom = configparser.RawConfigParser()
-    >>> custom['section1'] = {'funky': 'nope'}
-    >>> custom['section1'].getboolean('funky')
-    Traceback (most recent call last):
-    ...
-    ValueError: Not a boolean: nope
-    >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
-    >>> custom['section1'].getboolean('funky')
-    False
+     >>> custom = configparser.ConfigParser()
+     >>> custom['section1'] = {'funky': 'nope'}
+     >>> custom['section1'].getboolean('funky')
+     Traceback (most recent call last):
+     ...
+     ValueError: Not a boolean: nope
+     >>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
+     >>> custom['section1'].getboolean('funky')
+     False
 
-  Other typical boolean pairs include ``accept``/``reject`` or
+  Other typical Boolean pairs include ``accept``/``reject`` or
   ``enabled``/``disabled``.
 
-* :meth:`RawConfigParser.optionxform`
+.. method:: optionxform(option)
 
-  This is a method that transforms option names on every read or set operation.
-  By default it converts the name to lowercase. This also means that when
-  a configuration file gets written, all keys will be lowercase. If you find
-  that behaviour unsuitable, you can override this method.  For example:
+  This method transforms option names on every read, get, or set
+  operation.  The default converts the name to lowercase.  This also
+  means that when a configuration file gets written, all keys will be
+  lowercase.  Override this method if that's unsuitable.
+  For example:
 
-  .. highlightlang:: python
   .. doctest::
 
-    >>> config = """
-    ... [Section1]
-    ... Key = Value
-    ...
-    ... [Section2]
-    ... AnotherKey = Value
-    ... """
-    >>> typical = configparser.RawConfigParser()
-    >>> typical.read_string(config)
-    >>> list(typical['Section1'].keys())
-    ['key']
-    >>> list(typical['Section2'].keys())
-    ['anotherkey']
-    >>> custom = configparser.RawConfigParser()
-    >>> custom.optionxform = lambda option: option
-    >>> custom.read_string(config)
-    >>> list(custom['Section1'].keys())
-    ['Key']
-    >>> list(custom['Section2'].keys())
-    ['AnotherKey']
+     >>> config = """
+     ... [Section1]
+     ... Key = Value
+     ...
+     ... [Section2]
+     ... AnotherKey = Value
+     ... """
+     >>> typical = configparser.ConfigParser()
+     >>> typical.read_string(config)
+     >>> list(typical['Section1'].keys())
+     ['key']
+     >>> list(typical['Section2'].keys())
+     ['anotherkey']
+     >>> custom = configparser.RawConfigParser()
+     >>> custom.optionxform = lambda option: option
+     >>> custom.read_string(config)
+     >>> list(custom['Section1'].keys())
+     ['Key']
+     >>> list(custom['Section2'].keys())
+     ['AnotherKey']
+
+.. attribute:: SECTCRE
+
+  A compiled regular expression used to parse section headers. The default
+  matches ``[section]`` to the name ``"section"``. Whitespace is considered part
+  of the section name, thus ``[  larch  ]`` will be read as a section of name
+  ``"  larch  "``. Override this attribute if that's unsuitable.  For example:
+
+  .. doctest::
+
+     >>> config = """
+     ... [Section 1]
+     ... option = value
+     ...
+     ... [  Section 2  ]
+     ... another = val
+     ... """
+     >>> typical = ConfigParser()
+     >>> typical.read_string(config)
+     >>> typical.sections()
+     ['Section 1', '  Section 2  ']
+     >>> custom = ConfigParser()
+     >>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
+     >>> custom.read_string(config)
+     >>> custom.sections()
+     ['Section 1', 'Section 2']
+
+  .. note::
+
+     While ConfigParser objects also use an ``OPTCRE`` attribute for recognizing
+     option lines, it's not recommended to override it because that would
+     interfere with constructor options *allow_no_value* and *delimiters*.
+
 
 Legacy API Examples
 -------------------
 
 Mainly because of backwards compatibility concerns, :mod:`configparser`
-provides also a legacy API with explicit ``get``/``set`` methods. While there
-are valid use cases for the methods outlined below, mapping protocol access
-is preferred for new projects. The legacy API is at times more advanced,
+provides also a legacy API with explicit ``get``/``set`` methods.  While there
+are valid use cases for the methods outlined below, mapping protocol access is
+preferred for new projects.  The legacy API is at times more advanced,
 low-level and downright counterintuitive.
 
 An example of writing to a configuration file::
@@ -597,12 +764,11 @@
 
    config = configparser.RawConfigParser()
 
-   # Please note that using RawConfigParser's and the raw mode of
-   # ConfigParser's respective set functions, you can assign non-string values
-   # to keys internally, but will receive an error when attempting to write to
-   # a file or when you get it in non-raw mode. Setting values using the
-   # mapping protocol or SafeConfigParser's set() does not allow such
-   # assignments to take place.
+   # Please note that using RawConfigParser's set functions, you can assign
+   # non-string values to keys internally, but will receive an error when
+   # attempting to write to a file or when you get it in non-raw mode. Setting
+   # values using the mapping protocol or ConfigParser's set() does not allow
+   # such assignments to take place.
    config.add_section('Section1')
    config.set('Section1', 'int', '15')
    config.set('Section1', 'bool', 'true')
@@ -633,12 +799,11 @@
    if config.getboolean('Section1', 'bool'):
        print(config.get('Section1', 'foo'))
 
-To get interpolation, you will need to use a :class:`SafeConfigParser` or, if
-you absolutely have to, a :class:`ConfigParser`::
+To get interpolation, use :class:`ConfigParser`::
 
    import configparser
 
-   cfg = configparser.SafeConfigParser()
+   cfg = configparser.ConfigParser()
    cfg.read('example.cfg')
 
    # Set the optional `raw` argument of get() to True if you wish to disable
@@ -667,14 +832,13 @@
    print(cfg.get('Section1', 'monster', fallback=None))
          # -> None
 
-
-Defaults are available in all three types of ConfigParsers. They are used in
+Default values are available in both types of ConfigParsers.  They are used in
 interpolation if an option used is not defined elsewhere. ::
 
    import configparser
 
    # New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
-   config = configparser.SafeConfigParser({'bar': 'Life', 'baz': 'hard'})
+   config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
    config.read('example.cfg')
 
    print(config.get('Section1', 'foo')) # -> "Python is fun!"
@@ -682,378 +846,330 @@
    config.remove_option('Section1', 'baz')
    print(config.get('Section1', 'foo')) # -> "Life is hard!"
 
-.. _rawconfigparser-objects:
 
-RawConfigParser Objects
------------------------
+.. _configparser-objects:
 
-.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
+ConfigParser Objects
+--------------------
 
-   The basic configuration object.  When *defaults* is given, it is initialized
+.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation())
+
+   The main configuration parser.  When *defaults* is given, it is initialized
    into the dictionary of intrinsic defaults.  When *dict_type* is given, it
    will be used to create the dictionary objects for the list of sections, for
    the options within a section, and for the default values.
 
-   When *delimiters* is given, it will be used as the set of substrings that
+   When *delimiters* is given, it is used as the set of substrings that
    divide keys from values.  When *comment_prefixes* is given, it will be used
-   as the set of substrings that prefix comments in a line, both for the whole
+   as the set of substrings that prefix comments in otherwise empty lines.
+   Comments can be indented. When *inline_comment_prefixes* is given, it will be
+   used as the set of substrings that prefix comments in non-empty lines.
+
    line and inline comments.  For backwards compatibility, the default value for
    *comment_prefixes* is a special value that indicates that ``;`` and ``#`` can
    start whole line comments while only ``;`` can start inline comments.
 
-   When *strict* is ``True`` (default: ``False``), the parser won't allow for
+   When *strict* is ``True`` (the default), the parser won't allow for
    any section or option duplicates while reading from a single source (file,
    string or dictionary), raising :exc:`DuplicateSectionError` or
-   :exc:`DuplicateOptionError`. When *empty_lines_in_values* is ``False``
+   :exc:`DuplicateOptionError`.  When *empty_lines_in_values* is ``False``
    (default: ``True``), each empty line marks the end of an option.  Otherwise,
    internal empty lines of a multiline option are kept as part of the value.
    When *allow_no_value* is ``True`` (default: ``False``), options without
-   values are accepted; the value presented for these is ``None``.
+   values are accepted; the value held for these is ``None`` and they are
+   serialized without the trailing delimiter.
 
-   This class does not support the magical interpolation behavior.
+   When *default_section* is given, it specifies the name for the special
+   section holding default values for other sections and interpolation purposes
+   (normally named ``"DEFAULT"``). This value can be retrieved and changed on
+   runtime using the ``default_section`` instance attribute.
+
+   Interpolation behaviour may be customized by providing a custom handler
+   through the *interpolation* argument. ``None`` can be used to turn off
+   interpolation completely, ``ExtendedInterpolation()`` provides a more
+   advanced variant inspired by ``zc.buildout``. More on the subject in the
+   `dedicated documentation section <#interpolation-of-values>`_.
+
+   All option names used in interpolation will be passed through the
+   :meth:`optionxform` method just like any other option name reference.  For
+   example, using the default implementation of :meth:`optionxform` (which
+   converts option names to lower case), the values ``foo %(bar)s`` and ``foo
+   %(BAR)s`` are equivalent.
 
    .. versionchanged:: 3.1
       The default *dict_type* is :class:`collections.OrderedDict`.
 
    .. versionchanged:: 3.2
-      *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
-      *empty_lines_in_values* were added.
-
-
-.. method:: RawConfigParser.defaults()
-
-   Return a dictionary containing the instance-wide defaults.
-
-
-.. method:: RawConfigParser.sections()
-
-   Return a list of the sections available; ``DEFAULT`` is not included in the
-   list.
-
-
-.. method:: RawConfigParser.add_section(section)
-
-   Add a section named *section* to the instance.  If a section by the given name
-   already exists, :exc:`DuplicateSectionError` is raised. If the name
-   ``DEFAULT`` (or any of it's case-insensitive variants) is passed,
-   :exc:`ValueError` is raised.
+      *allow_no_value*, *delimiters*, *comment_prefixes*, *strict*,
+      *empty_lines_in_values*, *default_section* and *interpolation* were
+      added.
 
-.. method:: RawConfigParser.has_section(section)
-
-   Indicates whether the named section is present in the configuration. The
-   ``DEFAULT`` section is not acknowledged.
-
-
-.. method:: RawConfigParser.options(section)
-
-   Returns a list of options available in the specified *section*.
-
-
-.. method:: RawConfigParser.has_option(section, option)
-
-   If the given section exists, and contains the given option, return
-   :const:`True`; otherwise return :const:`False`.
-
-
-.. method:: RawConfigParser.read(filenames, encoding=None)
-
-   Attempt to read and parse a list of filenames, returning a list of filenames
-   which were successfully parsed.  If *filenames* is a string, it is treated as
-   a single filename.  If a file named in *filenames* cannot be opened, that
-   file will be ignored.  This is designed so that you can specify a list of
-   potential configuration file locations (for example, the current directory,
-   the user's home directory, and some system-wide directory), and all existing
-   configuration files in the list will be read.  If none of the named files
-   exist, the :class:`ConfigParser` instance will contain an empty dataset.  An
-   application which requires initial values to be loaded from a file should
-   load the required file or files using :meth:`read_file` before calling
-   :meth:`read` for any optional files::
-
-      import configparser, os
-
-      config = configparser.ConfigParser()
-      config.read_file(open('defaults.cfg'))
-      config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')], encoding='cp1250')
-
-   .. versionadded:: 3.2
-      The *encoding* parameter.  Previously, all files were read using the
-      default encoding for :func:`open`.
 
+   .. method:: defaults()
 
-.. method:: RawConfigParser.read_file(f, source=None)
+      Return a dictionary containing the instance-wide defaults.
 
-   Read and parse configuration data from the file or file-like object in *f*
-   (only the :meth:`readline` method is used).  The file-like object must
-   operate in text mode, i.e. return strings from :meth:`readline`.
 
-   Optional argument *source* specifies the name of the file being read. It not
-   given and *f* has a :attr:`name` attribute, that is used for *source*; the
-   default is ``<???>``.
+   .. method:: sections()
 
-   .. versionadded:: 3.2
-      Renamed from :meth:`readfp` (with the ``filename`` attribute renamed to
-      ``source`` for consistency with other ``read_*`` methods).
+      Return a list of the sections available; the *default section* is not
+      included in the list.
 
 
-.. method:: RawConfigParser.read_string(string, source='<string>')
+   .. method:: add_section(section)
 
-   Parse configuration data from a given string.
+      Add a section named *section* to the instance.  If a section by the given
+      name already exists, :exc:`DuplicateSectionError` is raised.  If the
+      *default section* name is passed, :exc:`ValueError` is raised.  The name
+      of the section must be a string; if not, :exc:`TypeError` is raised.
 
-   Optional argument *source* specifies a context-specific name of the string
-   passed. If not given, ``<string>`` is used.
+      .. versionchanged:: 3.2
+         Non-string section names raise :exc:`TypeError`.
 
-   .. versionadded:: 3.2
 
+   .. method:: has_section(section)
 
-.. method:: RawConfigParser.read_dict(dictionary, source='<dict>')
+      Indicates whether the named *section* is present in the configuration.
+      The *default section* is not acknowledged.
 
-   Load configuration from a dictionary. Keys are section names, values are
-   dictionaries with keys and values that should be present in the section. If
-   the used dictionary type preserves order, sections and their keys will be
-   added in order. Values are automatically converted to strings.
 
-   Optional argument *source* specifies a context-specific name of the
-   dictionary passed.  If not given, ``<dict>`` is used.
+   .. method:: options(section)
 
-   .. versionadded:: 3.2
+      Return a list of options available in the specified *section*.
 
-.. method:: RawConfigParser.get(section, option, [vars, fallback])
 
-   Get an *option* value for the named *section*. If *vars* is provided, it
-   must be a dictionary.  The *option* is looked up in *vars* (if provided),
-   *section*, and in *DEFAULTSECT* in that order. If the key is not found and
-   *fallback* is provided, it is used as a fallback value. ``None`` can be
-   provided as a *fallback* value.
+   .. method:: has_option(section, option)
 
-   .. versionchanged:: 3.2
-      Arguments *vars* and *fallback* are keyword only to protect users from
-      trying to use the third argument as the *fallback* fallback (especially
-      when using the mapping protocol).
+      If the given *section* exists, and contains the given *option*, return
+      :const:`True`; otherwise return :const:`False`. If the specified
+      *section* is :const:`None` or an empty string, DEFAULT is assumed.
 
 
-.. method:: RawConfigParser.getint(section, option, [vars, fallback])
+   .. method:: read(filenames, encoding=None)
 
-   A convenience method which coerces the *option* in the specified *section* to
-   an integer. See :meth:`get` for explanation of *vars* and *fallback*.
+      Attempt to read and parse a list of filenames, returning a list of
+      filenames which were successfully parsed.  If *filenames* is a string, it
+      is treated as a single filename.  If a file named in *filenames* cannot
+      be opened, that file will be ignored.  This is designed so that you can
+      specify a list of potential configuration file locations (for example,
+      the current directory, the user's home directory, and some system-wide
+      directory), and all existing configuration files in the list will be
+      read.  If none of the named files exist, the :class:`ConfigParser`
+      instance will contain an empty dataset.  An application which requires
+      initial values to be loaded from a file should load the required file or
+      files using :meth:`read_file` before calling :meth:`read` for any
+      optional files::
 
+         import configparser, os
 
-.. method:: RawConfigParser.getfloat(section, option, [vars, fallback])
+         config = configparser.ConfigParser()
+         config.read_file(open('defaults.cfg'))
+         config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
+                     encoding='cp1250')
 
-   A convenience method which coerces the *option* in the specified *section* to
-   a floating point number.  See :meth:`get` for explanation of *vars* and
-   *fallback*.
+      .. versionadded:: 3.2
+         The *encoding* parameter.  Previously, all files were read using the
+         default encoding for :func:`open`.
 
 
-.. method:: RawConfigParser.getboolean(section, option, [vars, fallback])
+   .. method:: read_file(f, source=None)
 
-   A convenience method which coerces the *option* in the specified *section*
-   to a Boolean value.  Note that the accepted values for the option are
-   ``"1"``, ``"yes"``, ``"true"``, and ``"on"``, which cause this method to
-   return ``True``, and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which
-   cause it to return ``False``.  These string values are checked in
-   a case-insensitive manner.  Any other value will cause it to raise
-   :exc:`ValueError`. See :meth:`get` for explanation of *vars* and *fallback*.
+      Read and parse configuration data from the file or file-like object in
+      *f* (only the :meth:`readline` method is used).  The file-like object
+      must operate in text mode.  Specifically, it must return strings from
+      :meth:`readline`.
 
+      Optional argument *source* specifies the name of the file being read.  If
+      not given and *f* has a :attr:`name` attribute, that is used for
+      *source*; the default is ``'<???>'``.
 
-.. method:: RawConfigParser.items(section)
+      .. versionadded:: 3.2
+         Replaces :meth:`readfp`.
 
-   Return a list of ``(name, value)`` pairs for each option in the given
-   *section*.
 
+   .. method:: read_string(string, source='<string>')
 
-.. method:: RawConfigParser.set(section, option, value)
+      Parse configuration data from a string.
 
-   If the given section exists, set the given option to the specified value;
-   otherwise raise :exc:`NoSectionError`.  While it is possible to use
-   :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters set
-   to true) for *internal* storage of non-string values, full functionality
-   (including interpolation and output to files) can only be achieved using
-   string values.
+      Optional argument *source* specifies a context-specific name of the
+      string passed.  If not given, ``'<string>'`` is used.  This should
+      commonly be a filesystem path or a URL.
 
-.. warning::
+      .. versionadded:: 3.2
 
-   This method lets users assign non-string values to keys internally. This
-   behaviour is unsupported and will cause errors when attempting to write to
-   a file or get it in non-raw mode. **Use the mapping protocol API** which does
-   not allow such assignments to take place.
 
+   .. method:: read_dict(dictionary, source='<dict>')
 
-.. method:: RawConfigParser.write(fileobject, space_around_delimiters=True)
+      Load configuration from any object that provides a dict-like ``items()``
+      method.  Keys are section names, values are dictionaries with keys and
+      values that should be present in the section.  If the used dictionary
+      type preserves order, sections and their keys will be added in order.
+      Values are automatically converted to strings.
 
-   Write a representation of the configuration to the specified
-   :term:`file object`, which must be opened in text mode (accepting strings).
-   This representation can be parsed by a future :meth:`read` call. If
-   ``space_around_delimiters`` is ``True`` (the default), delimiters between
-   keys and values are surrounded by spaces.
+      Optional argument *source* specifies a context-specific name of the
+      dictionary passed.  If not given, ``<dict>`` is used.
 
+      This method can be used to copy state between parsers.
 
-.. method:: RawConfigParser.remove_option(section, option)
+      .. versionadded:: 3.2
 
-   Remove the specified *option* from the specified *section*. If the section does
-   not exist, raise :exc:`NoSectionError`.  If the option existed to be removed,
-   return :const:`True`; otherwise return :const:`False`.
 
+   .. method:: get(section, option, raw=False, [vars, fallback])
 
-.. method:: RawConfigParser.remove_section(section)
+      Get an *option* value for the named *section*.  If *vars* is provided, it
+      must be a dictionary.  The *option* is looked up in *vars* (if provided),
+      *section*, and in *DEFAULTSECT* in that order.  If the key is not found
+      and *fallback* is provided, it is used as a fallback value.  ``None`` can
+      be provided as a *fallback* value.
 
-   Remove the specified *section* from the configuration. If the section in fact
-   existed, return ``True``. Otherwise return ``False``.
+      All the ``'%'`` interpolations are expanded in the return values, unless
+      the *raw* argument is true.  Values for interpolation keys are looked up
+      in the same manner as the option.
 
+      .. versionchanged:: 3.2
+         Arguments *raw*, *vars* and *fallback* are keyword only to protect
+         users from trying to use the third argument as the *fallback* fallback
+         (especially when using the mapping protocol).
 
-.. method:: RawConfigParser.optionxform(option)
 
-   Transforms the option name *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 version of *option*;
-   subclasses may override this or client code can set an attribute of this name
-   on instances to affect this behavior.
+   .. method:: getint(section, option, raw=False, [vars, fallback])
 
-   You don't necessarily need to subclass a ConfigParser to use this method, you
-   can also re-set it on an instance, to a function that takes a string
-   argument.  Setting it to ``str``, for example, would make option names case
-   sensitive::
+      A convenience method which coerces the *option* in the specified *section*
+      to an integer.  See :meth:`get` for explanation of *raw*, *vars* and
+      *fallback*.
 
-      cfgparser = ConfigParser()
-      ...
-      cfgparser.optionxform = str
 
-   Note that when reading configuration files, whitespace around the
-   option names are stripped before :meth:`optionxform` is called.
+   .. method:: getfloat(section, option, raw=False, [vars, fallback])
 
+      A convenience method which coerces the *option* in the specified *section*
+      to a floating point number.  See :meth:`get` for explanation of *raw*,
+      *vars* and *fallback*.
 
-.. method:: RawConfigParser.readfp(fp, filename=None)
 
-   .. deprecated:: 3.2
-      Please use :meth:`read_file` instead.
+   .. method:: getboolean(section, option, raw=False, [vars, fallback])
 
+      A convenience method which coerces the *option* in the specified *section*
+      to a Boolean value.  Note that the accepted values for the option are
+      ``'1'``, ``'yes'``, ``'true'``, and ``'on'``, which cause this method to
+      return ``True``, and ``'0'``, ``'no'``, ``'false'``, and ``'off'``, which
+      cause it to return ``False``.  These string values are checked in a
+      case-insensitive manner.  Any other value will cause it to raise
+      :exc:`ValueError`.  See :meth:`get` for explanation of *raw*, *vars* and
+      *fallback*.
 
-.. _configparser-objects:
 
-ConfigParser Objects
---------------------
+   .. method:: items([section], raw=False, vars=None)
 
-.. warning::
-   Whenever you can, consider using :class:`SafeConfigParser` which
-   adds validation and escaping for the interpolation.
+      When *section* is not given, return a list of *section_name*,
+      *section_proxy* pairs, including DEFAULTSECT.
 
-The :class:`ConfigParser` class extends some methods of the
-:class:`RawConfigParser` interface, adding some optional arguments.
+      Otherwise, return a list of *name*, *value* pairs for the options in the
+      given *section*.  Optional arguments have the same meaning as for the
+      :meth:`get` method.
 
-.. class:: ConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
 
-   Derived class of :class:`RawConfigParser` that implements the magical
-   interpolation feature and adds optional arguments to the :meth:`get` and
-   :meth:`items` methods.
+   .. method:: set(section, option, value)
 
-   :class:`SafeConfigParser` is generally recommended over this class if you
-   need interpolation.
+      If the given section exists, set the given option to the specified value;
+      otherwise raise :exc:`NoSectionError`.  *option* and *value* must be
+      strings; if not, :exc:`TypeError` is raised.
 
-   The values in *defaults* must be appropriate for the ``%()s`` string
-   interpolation.  Note that *__name__* is an intrinsic default; its value is
-   the section name, and will override any value provided in *defaults*.
 
-   All option names used in interpolation will be passed through the
-   :meth:`optionxform` method just like any other option name reference.  For
-   example, using the default implementation of :meth:`optionxform` (which
-   converts option names to lower case), the values ``foo %(bar)s`` and ``foo
-   %(BAR)s`` are equivalent.
+   .. method:: write(fileobject, space_around_delimiters=True)
 
-   .. versionchanged:: 3.1
-      The default *dict_type* is :class:`collections.OrderedDict`.
+      Write a representation of the configuration to the specified :term:`file
+      object`, which must be opened in text mode (accepting strings).  This
+      representation can be parsed by a future :meth:`read` call.  If
+      *space_around_delimiters* is true, delimiters between
+      keys and values are surrounded by spaces.
 
-   .. versionchanged:: 3.2
-      *allow_no_value*, *delimiters*, *comment_prefixes*,
-      *strict* and *empty_lines_in_values* were added.
 
+   .. method:: remove_option(section, option)
 
-.. method:: ConfigParser.get(section, option, raw=False, [vars, fallback])
+      Remove the specified *option* from the specified *section*.  If the
+      section does not exist, raise :exc:`NoSectionError`.  If the option
+      existed to be removed, return :const:`True`; otherwise return
+      :const:`False`.
 
-   Get an *option* value for the named *section*.  If *vars* is provided, it
-   must be a dictionary.  The *option* is looked up in *vars* (if provided),
-   *section*, and in *DEFAULTSECT* in that order. If the key is not found and
-   *fallback* is provided, it is used as a fallback value. ``None`` can be
-   provided as a *fallback* value.
 
-   All the ``'%'`` interpolations are expanded in the return values, unless the
-   *raw* argument is true.  Values for interpolation keys are looked up in the
-   same manner as the option.
+   .. method:: remove_section(section)
 
-   .. versionchanged:: 3.2
-      Arguments *raw*, *vars* and *fallback* are keyword only to protect users
-      from trying to use the third argument as the *fallback* fallback
-      (especially when using the mapping protocol).
+      Remove the specified *section* from the configuration.  If the section in
+      fact existed, return ``True``.  Otherwise return ``False``.
 
 
-.. method:: ConfigParser.getint(section, option, raw=False, [vars, fallback])
+   .. method:: optionxform(option)
 
-   A convenience method which coerces the *option* in the specified *section* to
-   an integer. See :meth:`get` for explanation of *raw*, *vars* and *fallback*.
+      Transforms the option name *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 version of
+      *option*; subclasses may override this or client code can set an attribute
+      of this name on instances to affect this behavior.
 
+      You don't need to subclass the parser to use this method, you can also
+      set it on an instance, to a function that takes a string argument and
+      returns a string.  Setting it to ``str``, for example, would make option
+      names case sensitive::
 
-.. method:: ConfigParser.getfloat(section, option, raw=False, [vars, fallback])
+         cfgparser = ConfigParser()
+         cfgparser.optionxform = str
 
-   A convenience method which coerces the *option* in the specified *section* to
-   a floating point number. See :meth:`get` for explanation of *raw*, *vars*
-   and *fallback*.
+      Note that when reading configuration files, whitespace around the option
+      names is stripped before :meth:`optionxform` is called.
 
 
-.. method:: ConfigParser.getboolean(section, option, raw=False, [vars, fallback])
+   .. method:: readfp(fp, filename=None)
 
-   A convenience method which coerces the *option* in the specified *section*
-   to a Boolean value.  Note that the accepted values for the option are
-   ``"1"``, ``"yes"``, ``"true"``, and ``"on"``, which cause this method to
-   return ``True``, and ``"0"``, ``"no"``, ``"false"``, and ``"off"``, which
-   cause it to return ``False``.  These string values are checked in
-   a case-insensitive manner.  Any other value will cause it to raise
-   :exc:`ValueError`. See :meth:`get` for explanation of *raw*, *vars* and
-   *fallback*.
+      .. deprecated:: 3.2
+         Use :meth:`read_file` instead.
 
 
-.. method:: ConfigParser.items(section, raw=False, vars=None)
+.. data:: MAX_INTERPOLATION_DEPTH
 
-   Return a list of ``(name, value)`` pairs for each option in the given
-   *section*.  Optional arguments have the same meaning as for the :meth:`get`
-   method.
+   The maximum depth for recursive interpolation for :meth:`get` when the *raw*
+   parameter is false.  This is relevant only when the default *interpolation*
+   is used.
 
 
-.. data:: MAX_INTERPOLATION_DEPTH
+.. _rawconfigparser-objects:
 
-   The maximum depth for recursive interpolation for :meth:`get` when the *raw*
-   parameter is false.  This is relevant only for the :class:`ConfigParser` class.
+RawConfigParser Objects
+-----------------------
 
-.. _safeconfigparser-objects:
+.. class:: RawConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configaparser.DEFAULTSECT, interpolation=None)
 
-SafeConfigParser Objects
-------------------------
+   Legacy variant of the :class:`ConfigParser` with interpolation disabled
+   by default and unsafe ``add_section`` and ``set`` methods.
 
-.. class:: SafeConfigParser(defaults=None, dict_type=collections.OrderedDict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=_COMPATIBLE, strict=False, empty_lines_in_values=True)
+   .. note::
+      Consider using :class:`ConfigParser` instead which checks types of
+      the values to be stored internally. If you don't want interpolation, you
+      can use ``ConfigParser(interpolation=None)``.
 
-   Derived class of :class:`ConfigParser` that implements a sane variant of the
-   magical interpolation feature.  This implementation is more predictable as it
-   validates the interpolation syntax used within a configuration file.  This
-   class also enables escaping the interpolation character (e.g. a key can have
-   ``%`` as part of the value by specifying ``%%`` in the file).
 
-   Applications that don't require interpolation should use
-   :class:`RawConfigParser`, otherwise :class:`SafeConfigParser` is the best
-   option.
+   .. method:: add_section(section)
 
-   .. versionchanged:: 3.1
-      The default *dict_type* is :class:`collections.OrderedDict`.
+      Add a section named *section* to the instance.  If a section by the given
+      name already exists, :exc:`DuplicateSectionError` is raised.  If the
+      *default section* name is passed, :exc:`ValueError` is raised.
 
-   .. versionchanged:: 3.2
-      *allow_no_value*, *delimiters*, *comment_prefixes*, *strict* and
-      *empty_lines_in_values* were added.
+      Type of *section* is not checked which lets users create non-string named
+      sections. This behaviour is unsupported and may cause internal errors.
 
 
-The :class:`SafeConfigParser` class implements the same extended interface as
-:class:`ConfigParser`, with the following addition:
+   .. method:: set(section, option, value)
 
-.. method:: SafeConfigParser.set(section, option, value)
+      If the given section exists, set the given option to the specified value;
+      otherwise raise :exc:`NoSectionError`.  While it is possible to use
+      :class:`RawConfigParser` (or :class:`ConfigParser` with *raw* parameters
+      set to true) for *internal* storage of non-string values, full
+      functionality (including interpolation and output to files) can only be
+      achieved using string values.
 
-   If the given section exists, set the given option to the specified value;
-   otherwise raise :exc:`NoSectionError`.  *value* must be a string; if it is
-   not, :exc:`TypeError` is raised.
+      This method lets users assign non-string values to keys internally.  This
+      behaviour is unsupported and will cause errors when attempting to write
+      to a file or get it in non-raw mode.  **Use the mapping protocol API**
+      which does not allow such assignments to take place.
 
 
 Exceptions
@@ -1061,7 +1177,7 @@
 
 .. exception:: Error
 
-   Base class for all other configparser exceptions.
+   Base class for all other :mod:`configparser` exceptions.
 
 
 .. exception:: NoSectionError
@@ -1103,25 +1219,26 @@
 .. exception:: InterpolationDepthError
 
    Exception raised when string interpolation cannot be completed because the
-   number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`. Subclass of
+   number of iterations exceeds :const:`MAX_INTERPOLATION_DEPTH`.  Subclass of
    :exc:`InterpolationError`.
 
 
 .. exception:: InterpolationMissingOptionError
 
-   Exception raised when an option referenced from a value does not exist. Subclass
-   of :exc:`InterpolationError`.
+   Exception raised when an option referenced from a value does not exist.
+   Subclass of :exc:`InterpolationError`.
 
 
 .. exception:: InterpolationSyntaxError
 
-   Exception raised when the source text into which substitutions are made does not
-   conform to the required syntax. Subclass of :exc:`InterpolationError`.
+   Exception raised when the source text into which substitutions are made does
+   not conform to the required syntax.  Subclass of :exc:`InterpolationError`.
 
 
 .. exception:: MissingSectionHeaderError
 
-   Exception raised when attempting to parse a file which has no section headers.
+   Exception raised when attempting to parse a file which has no section
+   headers.
 
 
 .. exception:: ParsingError
@@ -1132,6 +1249,9 @@
       The ``filename`` attribute and :meth:`__init__` argument were renamed to
       ``source`` for consistency.
 
-.. [customizable] Config parsers allow for very heavy customization. If you're
-                  interested in changing the behaviour outlined by the footnote
-                  reference, consult the `Customizing Parser Behaviour`_ section.
+
+.. rubric:: Footnotes
+
+.. [1] Config parsers allow for heavy customization.  If you are interested in
+       changing the behaviour outlined by the footnote reference, consult the
+       `Customizing Parser Behaviour`_ section.

Modified: python/branches/pep-3151/Doc/library/contextlib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/contextlib.rst	(original)
+++ python/branches/pep-3151/Doc/library/contextlib.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: contextlib
    :synopsis: Utilities for with-statement contexts.
 
+**Source code:** :source:`Lib/contextlib.py`
+
+--------------
 
 This module provides utilities for common tasks involving the :keyword:`with`
 statement. For more information see also :ref:`typecontextmanager` and

Modified: python/branches/pep-3151/Doc/library/crypt.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/crypt.rst	(original)
+++ python/branches/pep-3151/Doc/library/crypt.rst	Sat Feb 26 08:16:32 2011
@@ -15,9 +15,9 @@
 
 This module implements an interface to the :manpage:`crypt(3)` routine, which is
 a one-way hash function based upon a modified DES algorithm; see the Unix man
-page for further details.  Possible uses include allowing Python scripts to
-accept typed passwords from the user, or attempting to crack Unix passwords with
-a dictionary.
+page for further details.  Possible uses include storing hashed passwords
+so you can check passwords without storing the actual password, or attempting
+to crack Unix passwords with a dictionary.
 
 .. index:: single: crypt(3)
 
@@ -26,15 +26,81 @@
 extensions available on the current implementation will also  be available on
 this module.
 
+Hashing Methods
+---------------
 
-.. function:: crypt(word, salt)
+The :mod:`crypt` module defines the list of hashing methods (not all methods
+are available on all platforms):
+
+.. data:: METHOD_SHA512
+
+   A Modular Crypt Format method with 16 character salt and 86 character
+   hash.  This is the strongest method.
+
+   .. versionadded:: 3.3
+
+.. data:: METHOD_SHA256
+
+   Another Modular Crypt Format method with 16 character salt and 43
+   character hash.
+
+   .. versionadded:: 3.3
+
+.. data:: METHOD_MD5
+
+   Another Modular Crypt Format method with 8 character salt and 22
+   character hash.
+
+   .. versionadded:: 3.3
+
+.. data:: METHOD_CRYPT
+
+   The traditional method with a 2 character salt and 13 characters of
+   hash.  This is the weakest method.
+
+   .. versionadded:: 3.3
+
+
+Module Attributes
+-----------------
+
+
+.. attribute:: methods
+
+   A list of available password hashing algorithms, as
+   ``crypt.METHOD_*`` objects.  This list is sorted from strongest to
+   weakest, and is guaranteed to have at least ``crypt.METHOD_CRYPT``.
+
+   .. versionadded:: 3.3
+
+
+Module Functions
+----------------
+
+The :mod:`crypt` module defines the following functions:
+
+.. function:: crypt(word, salt=None)
 
    *word* will usually be a user's password as typed at a prompt or  in a graphical
-   interface.  *salt* is usually a random two-character string which will be used
-   to perturb the DES algorithm in one of 4096 ways.  The characters in *salt* must
-   be in the set ``[./a-zA-Z0-9]``.  Returns the hashed password as a string, which
-   will be composed of characters from the same alphabet as the salt (the first two
-   characters represent the salt itself).
+   interface.  The optional *salt* is either a string as returned from
+   :func:`mksalt`, one of the ``crypt.METHOD_*`` values (though not all
+   may be available on all platforms), or a full encrypted password
+   including salt, as returned by this function.  If *salt* is not
+   provided, the strongest method will be used (as returned by
+   :func:`methods`.
+
+   Checking a password is usually done by passing the plain-text password
+   as *word* and the full results of a previous :func:`crypt` call,
+   which should be the same as the results of this call.
+
+   *salt* (either a random 2 or 16 character string, possibly prefixed with
+   ``$digit$`` to indicate the method) which will be used to perturb the
+   encryption algorithm.  The characters in *salt* must be in the set
+   ``[./a-zA-Z0-9]``, with the exception of Modular Crypt Format which
+   prefixes a ``$digit$``.
+
+   Returns the hashed password as a string, which will be composed of
+   characters from the same alphabet as the salt.
 
    .. index:: single: crypt(3)
 
@@ -42,6 +108,27 @@
    different sizes in the *salt*, it is recommended to use  the full crypted
    password as salt when checking for a password.
 
+.. versionchanged:: 3.3
+   Before version 3.3, *salt*  must be specified as a string and cannot
+   accept ``crypt.METHOD_*`` values (which don't exist anyway).
+
+
+.. function:: mksalt(method=None)
+
+   Return a randomly generated salt of the specified method.  If no
+   *method* is given, the strongest method available as returned by
+   :func:`methods` is used.
+
+   The return value is a string either of 2 characters in length for
+   ``crypt.METHOD_CRYPT``, or 19 characters starting with ``$digit$`` and
+   16 random characters from the set ``[./a-zA-Z0-9]``, suitable for
+   passing as the *salt* argument to :func:`crypt`.
+
+.. versionadded:: 3.3
+
+Examples
+--------
+
 A simple example illustrating typical use::
 
    import crypt, getpass, pwd
@@ -57,3 +144,11 @@
        else:
            return 1
 
+To generate a hash of a password using the strongest available method and
+check it against the original::
+
+   import crypt
+
+   hashed = crypt.crypt(plaintext)
+   if hashed != crypt.crypt(plaintext, hashed):
+      raise "Hashed version doesn't validate against original"

Modified: python/branches/pep-3151/Doc/library/csv.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/csv.rst	(original)
+++ python/branches/pep-3151/Doc/library/csv.rst	Sat Feb 26 08:16:32 2011
@@ -50,7 +50,7 @@
 
    Return a reader object which will iterate over lines in the given *csvfile*.
    *csvfile* can be any object which supports the :term:`iterator` protocol and returns a
-   string each time its :meth:`!next` method is called --- :term:`file objects
+   string each time its :meth:`!__next__` method is called --- :term:`file objects
    <file object>` and list objects are both suitable.   If *csvfile* is a file object,
    it should be opened with ``newline=''``. [#]_  An optional
    *dialect* parameter can be given which is used to define a set of parameters

Modified: python/branches/pep-3151/Doc/library/ctypes.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/ctypes.rst	(original)
+++ python/branches/pep-3151/Doc/library/ctypes.rst	Sat Feb 26 08:16:32 2011
@@ -216,6 +216,8 @@
 +----------------------+------------------------------------------+----------------------------+
 | ctypes type          | C type                                   | Python type                |
 +======================+==========================================+============================+
+| :class:`c_bool`      | :c:type:`_Bool`                          | bool (1)                   |
++----------------------+------------------------------------------+----------------------------+
 | :class:`c_char`      | :c:type:`char`                           | 1-character bytes object   |
 +----------------------+------------------------------------------+----------------------------+
 | :class:`c_wchar`     | :c:type:`wchar_t`                        | 1-character string         |
@@ -254,6 +256,9 @@
 | :class:`c_void_p`    | :c:type:`void *`                         | int or ``None``            |
 +----------------------+------------------------------------------+----------------------------+
 
+(1)
+   The constructor accepts any object with a truth value.
+
 All these types can be created by calling them with an optional initializer of
 the correct type and value::
 
@@ -369,7 +374,7 @@
 :attr:`_as_parameter_` attribute and uses this as the function argument.  Of
 course, it must be one of integer, string, or bytes::
 
-   >>> class Bottles(object):
+   >>> class Bottles:
    ...     def __init__(self, number):
    ...         self._as_parameter_ = number
    ...
@@ -1930,22 +1935,6 @@
    but it is possible to enlarge the buffer.
 
 
-.. function:: set_conversion_mode(encoding, errors)
-
-   This function sets the rules that ctypes objects use when converting between
-   bytes objects and (unicode) strings. *encoding* must be a string specifying an
-   encoding, like ``'utf-8'`` or ``'mbcs'``, *errors* must be a string specifying
-   the error handling on encoding/decoding errors. Examples of possible values are
-   ``'strict'``, ``'replace'``, or ``'ignore'``.
-
-   :func:`set_conversion_mode` returns a 2-tuple containing the previous
-   conversion rules. On windows, the initial conversion rules are ``('mbcs',
-   'ignore')``, on other systems ``('ascii', 'strict')``.
-
-   You can set the *encoding* to ``'undefined'`` to completely disable automatic
-   conversions.
-
-
 .. function:: set_errno(value)
 
    Set the current value of the ctypes-private copy of the system :data:`errno`

Modified: python/branches/pep-3151/Doc/library/curses.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/curses.rst	(original)
+++ python/branches/pep-3151/Doc/library/curses.rst	Sat Feb 26 08:16:32 2011
@@ -49,7 +49,7 @@
       Tutorial material on using curses with Python, by Andrew Kuchling and Eric
       Raymond.
 
-   The :file:`Demo/curses/` directory in the Python source distribution contains
+   The :file:`Tools/demo/` directory in the Python source distribution contains
    some example programs using the curses bindings provided by this module.
 
 

Modified: python/branches/pep-3151/Doc/library/datatypes.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/datatypes.rst	(original)
+++ python/branches/pep-3151/Doc/library/datatypes.rst	Sat Feb 26 08:16:32 2011
@@ -21,6 +21,7 @@
    datetime.rst
    calendar.rst
    collections.rst
+   collections.abc.rst
    heapq.rst
    bisect.rst
    array.rst

Modified: python/branches/pep-3151/Doc/library/datetime.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/datetime.rst	(original)
+++ python/branches/pep-3151/Doc/library/datetime.rst	Sat Feb 26 08:16:32 2011
@@ -1661,9 +1661,6 @@
 implementation.  Note that the 1999 version of the C standard added additional
 format codes.
 
-The exact range of years for which :meth:`strftime` works also varies across
-platforms.  Regardless of platform, years before 1900 cannot be used.
-
 +-----------+--------------------------------+-------+
 | Directive | Meaning                        | Notes |
 +===========+================================+=======+
@@ -1706,7 +1703,7 @@
 |           | AM or PM.                      |       |
 +-----------+--------------------------------+-------+
 | ``%S``    | Second as a decimal number     | \(3)  |
-|           | [00,61].                       |       |
+|           | [00,59].                       |       |
 +-----------+--------------------------------+-------+
 | ``%U``    | Week number of the year        | \(4)  |
 |           | (Sunday as the first day of    |       |
@@ -1736,10 +1733,11 @@
 | ``%y``    | Year without century as a      |       |
 |           | decimal number [00,99].        |       |
 +-----------+--------------------------------+-------+
-| ``%Y``    | Year with century as a decimal |       |
-|           | number.                        |       |
+| ``%Y``    | Year with century as a decimal | \(5)  |
+|           | number [0001,9999] (strptime), |       |
+|           | [1000,9999] (strftime).        |       |
 +-----------+--------------------------------+-------+
-| ``%z``    | UTC offset in the form +HHMM   | \(5)  |
+| ``%z``    | UTC offset in the form +HHMM   | \(6)  |
 |           | or -HHMM (empty string if the  |       |
 |           | the object is naive).          |       |
 +-----------+--------------------------------+-------+
@@ -1763,18 +1761,26 @@
    the output hour field if the ``%I`` directive is used to parse the hour.
 
 (3)
-   The range really is ``0`` to ``61``; according to the Posix standard this
-   accounts for leap seconds and the (very rare) double leap seconds.
-   The :mod:`time` module may produce and does accept leap seconds since
-   it is based on the Posix standard, but the :mod:`datetime` module
-   does not accept leap seconds in :meth:`strptime` input nor will it
-   produce them in :func:`strftime` output.
+   Unlike :mod:`time` module, :mod:`datetime` module does not support
+   leap seconds.
 
 (4)
    When used with the :meth:`strptime` method, ``%U`` and ``%W`` are only used in
    calculations when the day of the week and the year are specified.
 
 (5)
+   For technical reasons, :meth:`strftime` method does not support
+   dates before year 1000: ``t.strftime(format)`` will raise a
+   :exc:`ValueError` when ``t.year < 1000`` even if ``format`` does
+   not contain ``%Y`` directive.  The :meth:`strptime` method can
+   parse years in the full [1, 9999] range, but years < 1000 must be
+   zero-filled to 4-digit width.
+
+   .. versionchanged:: 3.2
+      In previous versions, :meth:`strftime` method was restricted to
+      years >= 1900.
+
+(6)
    For example, if :meth:`utcoffset` returns ``timedelta(hours=-3, minutes=-30)``,
    ``%z`` is replaced with the string ``'-0330'``.
 

Modified: python/branches/pep-3151/Doc/library/dbm.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/dbm.rst	(original)
+++ python/branches/pep-3151/Doc/library/dbm.rst	Sat Feb 26 08:16:32 2011
@@ -20,7 +20,7 @@
 
 .. function:: whichdb(filename)
 
-   This functionattempts to guess which of the several simple database modules
+   This function attempts to guess which of the several simple database modules
    available --- :mod:`dbm.gnu`, :mod:`dbm.ndbm` or :mod:`dbm.dumb` --- should
    be used to open a given file.
 
@@ -61,10 +61,15 @@
    modified by the prevailing umask).
 
 
-The object returned by :func:`.open` supports most of the same functionality as
+The object returned by :func:`.open` supports the same basic functionality as
 dictionaries; keys and their corresponding values can be stored, retrieved, and
 deleted, and the :keyword:`in` operator and the :meth:`keys` method are
-available. Key and values are always stored as bytes. This means that when
+available, as well as :meth:`get` and :meth:`setdefault`.
+
+.. versionchanged:: 3.2
+   :meth:`get` and :meth:`setdefault` are now available in all database modules.
+
+Key and values are always stored as bytes. This means that when
 strings are used they are implicitly converted to the default encoding before
 being stored.
 
@@ -86,10 +91,8 @@
    # Notice how the value is now in bytes.
    assert db['www.cnn.com'] == b'Cable News Network'
 
-   # Loop through contents.  Other dictionary methods
-   # such as .keys(), .values() also work.
-   for k, v in db.iteritems():
-       print(k, '\t', v)
+   # Often-used methods of the dict interface work too.
+   print(db.get('python.org', b'not present'))
 
    # Storing a non-string key or value will raise an exception (most
    # likely a TypeError).

Modified: python/branches/pep-3151/Doc/library/decimal.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/decimal.rst	(original)
+++ python/branches/pep-3151/Doc/library/decimal.rst	Sat Feb 26 08:16:32 2011
@@ -144,7 +144,7 @@
    >>> Decimal((0, (3, 1, 4), -2))
    Decimal('3.14')
    >>> Decimal(str(2.0 ** 0.5))
-   Decimal('1.41421356237')
+   Decimal('1.4142135623730951')
    >>> Decimal(2) ** Decimal('0.5')
    Decimal('1.414213562373095048801688724')
    >>> Decimal('NaN')
@@ -1657,7 +1657,8 @@
            build(trailneg)
        for i in range(places):
            build(next() if digits else '0')
-       build(dp)
+       if places:
+           build(dp)
        if not digits:
            build('0')
        i = 0
@@ -1717,6 +1718,9 @@
    def cos(x):
        """Return the cosine of x as measured in radians.
 
+       The Taylor series approximation works best for a small value of x.
+       For larger values, first compute x = x % (2 * pi).
+
        >>> print(cos(Decimal('0.5')))
        0.8775825618903727161162815826
        >>> print(cos(0.5))
@@ -1740,6 +1744,9 @@
    def sin(x):
        """Return the sine of x as measured in radians.
 
+       The Taylor series approximation works best for a small value of x.
+       For larger values, first compute x = x % (2 * pi).
+
        >>> print(sin(Decimal('0.5')))
        0.4794255386042030002732879352
        >>> print(sin(0.5))

Modified: python/branches/pep-3151/Doc/library/difflib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/difflib.rst	(original)
+++ python/branches/pep-3151/Doc/library/difflib.rst	Sat Feb 26 08:16:32 2011
@@ -17,6 +17,7 @@
 information in various formats, including HTML and context and unified
 diffs. For comparing directories and files, see also, the :mod:`filecmp` module.
 
+
 .. class:: SequenceMatcher
 
    This is a flexible class for comparing pairs of sequences of any type, so long
@@ -35,6 +36,17 @@
    complicated way on how many elements the sequences have in common; best case
    time is linear.
 
+   **Automatic junk heuristic:** :class:`SequenceMatcher` supports a heuristic that
+   automatically treats certain sequence items as junk. The heuristic counts how many
+   times each individual item appears in the sequence. If an item's duplicates (after
+   the first one) account for more than 1% of the sequence and the sequence is at least
+   200 items long, this item is marked as "popular" and is treated as junk for
+   the purpose of sequence matching. This heuristic can be turned off by setting
+   the ``autojunk`` argument to ``False`` when creating the :class:`SequenceMatcher`.
+
+   .. versionadded:: 3.2
+      The *autojunk* parameter.
+
 
 .. class:: Differ
 
@@ -324,7 +336,7 @@
 The :class:`SequenceMatcher` class has this constructor:
 
 
-.. class:: SequenceMatcher(isjunk=None, a='', b='')
+.. class:: SequenceMatcher(isjunk=None, a='', b='', autojunk=True)
 
    Optional argument *isjunk* must be ``None`` (the default) or a one-argument
    function that takes a sequence element and returns true if and only if the
@@ -340,8 +352,23 @@
    The optional arguments *a* and *b* are sequences to be compared; both default to
    empty strings.  The elements of both sequences must be :term:`hashable`.
 
-   :class:`SequenceMatcher` objects have the following methods:
+   The optional argument *autojunk* can be used to disable the automatic junk
+   heuristic.
 
+   .. versionadded:: 3.2
+      The *autojunk* parameter.
+
+   SequenceMatcher objects get three data attributes: *bjunk* is the
+   set of elements of *b* for which *isjunk* is True; *bpopular* is the set of
+   non-junk elements considered popular by the heuristic (if it is not
+   disabled); *b2j* is a dict mapping the remaining elements of *b* to a list
+   of positions where they occur. All three are reset whenever *b* is reset
+   with :meth:`set_seqs` or :meth:`set_seq2`.
+
+   .. versionadded:: 3.2
+      The *bjunk* and *bpopular* attributes.
+
+   :class:`SequenceMatcher` objects have the following methods:
 
    .. method:: set_seqs(a, b)
 
@@ -520,7 +547,7 @@
 SequenceMatcher Examples
 ------------------------
 
-This example compares two strings, considering blanks to be "junk:"
+This example compares two strings, considering blanks to be "junk":
 
    >>> s = SequenceMatcher(lambda x: x == " ",
    ...                     "private Thread currentThread;",

Modified: python/branches/pep-3151/Doc/library/dis.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/dis.rst	(original)
+++ python/branches/pep-3151/Doc/library/dis.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: dis
    :synopsis: Disassembler for Python bytecode.
 
+**Source code:** :source:`Lib/dis.py`
+
+--------------
 
 The :mod:`dis` module supports the analysis of CPython :term:`bytecode` by
 disassembling it. The CPython bytecode which this module takes as an
@@ -12,7 +15,7 @@
 
 .. impl-detail::
 
-   Bytecode is an implementation detail of the CPython interpreter!  No
+   Bytecode is an implementation detail of the CPython interpreter.  No
    guarantees are made that bytecode will not be added, removed, or changed
    between versions of Python.  Use of this module should not be considered to
    work across Python VMs or Python releases.
@@ -729,11 +732,6 @@
    Used by the :keyword:`del` statement.
 
 
-.. opcode:: SET_LINENO (lineno)
-
-   This opcode is obsolete.
-
-
 .. opcode:: RAISE_VARARGS (argc)
 
    Raises an exception. *argc* indicates the number of parameters to the raise

Modified: python/branches/pep-3151/Doc/library/doctest.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/doctest.rst	(original)
+++ python/branches/pep-3151/Doc/library/doctest.rst	Sat Feb 26 08:16:32 2011
@@ -88,7 +88,7 @@
    $
 
 There's no output!  That's normal, and it means all the examples worked.  Pass
-:option:`-v` to the script, and :mod:`doctest` prints a detailed log of what
+``-v`` to the script, and :mod:`doctest` prints a detailed log of what
 it's trying, and prints a summary at the end::
 
    $ python example.py -v
@@ -151,7 +151,7 @@
 final line of output is ``***Test Failed*** N failures.``, where *N* is the
 number of examples that failed.
 
-Run it with the :option:`-v` switch instead::
+Run it with the ``-v`` switch instead::
 
    python M.py -v
 
@@ -160,7 +160,7 @@
 
 You can force verbose mode by passing ``verbose=True`` to :func:`testmod`, or
 prohibit it by passing ``verbose=False``.  In either of those cases,
-``sys.argv`` is not examined by :func:`testmod` (so passing :option:`-v` or not
+``sys.argv`` is not examined by :func:`testmod` (so passing ``-v`` or not
 has no effect).
 
 There is also a command line shortcut for running :func:`testmod`.  You can
@@ -229,7 +229,7 @@
 that can be used to tell it to look for files in other locations.
 
 Like :func:`testmod`, :func:`testfile`'s verbosity can be set with the
-:option:`-v` command-line switch or with the optional keyword argument
+``-v`` command-line switch or with the optional keyword argument
 *verbose*.
 
 There is also a command line shortcut for running :func:`testfile`.  You can
@@ -922,7 +922,7 @@
 
    def load_tests(loader, tests, ignore):
        tests.addTests(doctest.DocTestSuite(my_module_with_doctests))
-       return test
+       return tests
 
 There are two main functions for creating :class:`unittest.TestSuite` instances
 from text files and modules with doctests:
@@ -1377,7 +1377,7 @@
    verbosity.  If *verbose* is ``True``, then information is printed about each
    example, as it is run.  If *verbose* is ``False``, then only failures are
    printed.  If *verbose* is unspecified, or ``None``, then verbose output is used
-   iff the command-line switch :option:`-v` is used.
+   iff the command-line switch ``-v`` is used.
 
    The optional keyword argument *optionflags* can be used to control how the test
    runner compares expected output to actual output, and how it displays failures.

Modified: python/branches/pep-3151/Doc/library/dummy_threading.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/dummy_threading.rst	(original)
+++ python/branches/pep-3151/Doc/library/dummy_threading.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: dummy_threading
    :synopsis: Drop-in replacement for the threading module.
 
+**Source code:** :source:`Lib/dummy_threading.py`
+
+--------------
 
 This module provides a duplicate interface to the :mod:`threading` module.  It
 is meant to be imported when the :mod:`_thread` module is not provided on a

Modified: python/branches/pep-3151/Doc/library/email.charset.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/email.charset.rst	(original)
+++ python/branches/pep-3151/Doc/library/email.charset.rst	Sat Feb 26 08:16:32 2011
@@ -142,12 +142,6 @@
       it is *input_charset*.
 
 
-   .. method:: encoded_header_len()
-
-      Return the length of the encoded header string, properly calculating for
-      quoted-printable or base64 encoding.
-
-
    .. method:: header_encode(string)
 
       Header-encode the string *string*.
@@ -156,6 +150,16 @@
       *header_encoding* attribute.
 
 
+   .. method:: header_encode_lines(string, maxlengths)
+
+      Header-encode a *string* by converting it first to bytes.
+
+      This is similar to :meth:`header_encode` except that the string is fit
+      into maximum line lengths as given by the argument *maxlengths*, which
+      must be an iterator: each element returned from this iterator will provide
+      the next maximum line length.
+
+
    .. method:: body_encode(string)
 
       Body-encode the string *string*.

Modified: python/branches/pep-3151/Doc/library/email.generator.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/email.generator.rst	(original)
+++ python/branches/pep-3151/Doc/library/email.generator.rst	Sat Feb 26 08:16:32 2011
@@ -79,8 +79,8 @@
 
       Messages parsed with a Bytes parser that have a
       :mailheader:`Content-Transfer-Encoding` of 8bit will be converted to a
-      use a 7bit Content-Transfer-Encoding.  Any other non-ASCII bytes in the
-      message structure will be converted to '?' characters.
+      use a 7bit Content-Transfer-Encoding.  Non-ASCII bytes in the headers
+      will be :rfc:`2047` encoded with a charset of `unknown-8bit`.
 
       .. versionchanged:: 3.2
          Added support for re-encoding 8bit message bodies, and the *linesep*

Modified: python/branches/pep-3151/Doc/library/email.header.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/email.header.rst	(original)
+++ python/branches/pep-3151/Doc/library/email.header.rst	Sat Feb 26 08:16:32 2011
@@ -63,7 +63,7 @@
    character set is used both as *s*'s initial charset and as the default for
    subsequent :meth:`append` calls.
 
-   The maximum line length can be specified explicit via *maxlinelen*.  For
+   The maximum line length can be specified explicitly via *maxlinelen*.  For
    splitting the first line to a shorter value (to account for the field header
    which isn't included in *s*, e.g. :mailheader:`Subject`) pass in the name of the
    field in *header_name*.  The default *maxlinelen* is 76, and the default value
@@ -94,14 +94,15 @@
       decoded with that character set.
 
       If *s* is an instance of :class:`str`, then *charset* is a hint specifying
-      the character set of the characters in the string.  In this case, when
-      producing an :rfc:`2822`\ -compliant header using :rfc:`2047` rules, the
-      Unicode string will be encoded using the following charsets in order:
-      ``us-ascii``, the *charset* hint, ``utf-8``.  The first character set to
-      not provoke a :exc:`UnicodeError` is used.
+      the character set of the characters in the string.
 
-      Optional *errors* is passed through to any :func:`encode` or
-      :func:`ustr.encode` call, and defaults to "strict".
+      In either case, when producing an :rfc:`2822`\ -compliant header using
+      :rfc:`2047` rules, the string will be encoded using the output codec of
+      the charset.  If the string cannot be encoded using the output codec, a
+      UnicodeError will be raised.
+
+      Optional *errors* is passed as the errors argument to the decode call
+      if *s* is a byte string.
 
 
    .. method:: encode(splitchars=';, \\t', maxlinelen=None, linesep='\\n')
@@ -129,13 +130,15 @@
 
    .. method:: __str__()
 
-      A synonym for :meth:`Header.encode`.  Useful for ``str(aHeader)``.
-
+      Returns an approximation of the :class:`Header` as a string, using an
+      unlimited line length.  All pieces are converted to unicode using the
+      specified encoding and joined together appropriately.  Any pieces with a
+      charset of `unknown-8bit` are decoded as `ASCII` using the `replace`
+      error handler.
 
-   .. method:: __unicode__()
+      .. versionchanged:: 3.2
+         Added handling for the `unknown-8bit` charset.
 
-      A helper for :class:`str`'s :func:`encode` method.  Returns the header as
-      a Unicode string.
 
    .. method:: __eq__(other)
 

Modified: python/branches/pep-3151/Doc/library/email.message.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/email.message.rst	(original)
+++ python/branches/pep-3151/Doc/library/email.message.rst	Sat Feb 26 08:16:32 2011
@@ -169,9 +169,10 @@
    Note that in all cases, any envelope header present in the message is not
    included in the mapping interface.
 
-   In a model generated from bytes, any header values that (in contravention
-   of the RFCs) contain non-ASCII bytes will have those bytes transformed
-   into '?' characters when the values are retrieved through this interface.
+   In a model generated from bytes, any header values that (in contravention of
+   the RFCs) contain non-ASCII bytes will, when retrieved through this
+   interface, be represented as :class:`~email.header.Header` objects with
+   a charset of `unknown-8bit`.
 
 
    .. method:: __len__()
@@ -270,7 +271,15 @@
       taken as the parameter name, with underscores converted to dashes (since
       dashes are illegal in Python identifiers).  Normally, the parameter will
       be added as ``key="value"`` unless the value is ``None``, in which case
-      only the key will be added.
+      only the key will be added.  If the value contains non-ASCII characters,
+      it can be specified as a three tuple in the format
+      ``(CHARSET, LANGUAGE, VALUE)``, where ``CHARSET`` is a string naming the
+      charset to be used to encode the value, ``LANGUAGE`` can usually be set
+      to ``None`` or the empty string (see :rfc:`2231` for other possibilities),
+      and ``VALUE`` is the string value containing non-ASCII code points.  If
+      a three tuple is not passed and the value contains non-ASCII characters,
+      it is automatically encoded in :rfc:`2231` format using a ``CHARSET``
+      of ``utf-8`` and a ``LANGUAGE`` of ``None``.
 
       Here's an example::
 
@@ -280,6 +289,15 @@
 
          Content-Disposition: attachment; filename="bud.gif"
 
+      An example with with non-ASCII characters::
+
+         msg.add_header('Content-Disposition', 'attachment',
+                        filename=('iso-8859-1', '', 'Fußballer.ppt'))
+
+      Which produces ::
+
+         Content-Disposition: attachment; filename*="iso-8859-1''Fu%DFballer.ppt"
+
 
    .. method:: replace_header(_name, _value)
 
@@ -369,7 +387,7 @@
       :rfc:`2231`, you can collapse the parameter value by calling
       :func:`email.utils.collapse_rfc2231_value`, passing in the return value
       from :meth:`get_param`.  This will return a suitably decoded Unicode
-      string whn the value is a tuple, or the original string unquoted if it
+      string when the value is a tuple, or the original string unquoted if it
       isn't.  For example::
 
          rawparam = msg.get_param('foo')

Modified: python/branches/pep-3151/Doc/library/email.util.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/email.util.rst	(original)
+++ python/branches/pep-3151/Doc/library/email.util.rst	Sat Feb 26 08:16:32 2011
@@ -105,11 +105,17 @@
    ``False``.  The default is ``False``.
 
 
-.. function:: make_msgid(idstring=None)
+.. function:: make_msgid(idstring=None, domain=None)
 
    Returns a string suitable for an :rfc:`2822`\ -compliant
    :mailheader:`Message-ID` header.  Optional *idstring* if given, is a string
-   used to strengthen the uniqueness of the message id.
+   used to strengthen the uniqueness of the message id.  Optional *domain* if
+   given provides the portion of the msgid after the '@'.  The default is the
+   local hostname.  It is not normally necessary to override this default, but
+   may be useful certain cases, such as a constructing distributed system that
+   uses a consistent domain name across multiple hosts.
+
+   .. versionchanged:: 3.2 domain keyword added
 
 
 .. function:: decode_rfc2231(s)

Modified: python/branches/pep-3151/Doc/library/exceptions.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/exceptions.rst	(original)
+++ python/branches/pep-3151/Doc/library/exceptions.rst	Sat Feb 26 08:16:32 2011
@@ -18,12 +18,10 @@
 
 The built-in exceptions listed below can be generated by the interpreter or
 built-in functions.  Except where mentioned, they have an "associated value"
-indicating the detailed cause of the error. 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 usually passed to the exception
-class's constructor.  If the exception class is derived from the standard root
-class :exc:`BaseException`, the associated value is present as the exception
-instance's :attr:`args` attribute.
+indicating the detailed cause of the error.  This may be a string or a tuple of
+several items of information (e.g., an error code and a string explaining the
+code).  The associated value is usually passed as arguments to the exception
+class's constructor.
 
 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 situation in which the
@@ -38,16 +36,32 @@
 
 The following exceptions are used mostly as base classes for other exceptions.
 
-.. XXX document with_traceback()
-
 .. exception:: BaseException
 
    The base class for all built-in exceptions.  It is not meant to be directly
-   inherited by user-defined classes (for that use :exc:`Exception`).  If
+   inherited by user-defined classes (for that, use :exc:`Exception`).  If
    :func:`bytes` or :func:`str` is called on an instance of this class, the
-   representation of the argument(s) to the instance are returned or the empty
-   string when there were no arguments.  All arguments are  stored in :attr:`args`
-   as a tuple.
+   representation of the argument(s) to the instance are returned, or the empty
+   string when there were no arguments.
+
+   .. attribute:: args
+
+      The tuple of arguments given to the exception constructor.  Some built-in
+      exceptions (like :exc:`IOError`) expect a certain number of arguments and
+      assign a special meaning to the elements of this tuple, while others are
+      usually called only with a single string giving an error message.
+
+   .. method:: with_traceback(tb)
+
+      This method sets *tb* as the new traceback for the exception and returns
+      the exception object.  It is usually used in exception handling code like
+      this::
+
+         try:
+             ...
+         except SomeException:
+             tb = sys.exc_info()[2]
+             raise OtherException(...).with_traceback(tb)
 
 
 .. exception:: Exception
@@ -63,6 +77,12 @@
    :exc:`FloatingPointError`.
 
 
+.. exception:: BufferError
+
+   Raised when a :ref:`buffer <bufferobjects>` related operation cannot be
+   performed.
+
+
 .. exception:: LookupError
 
    The base class for the exceptions that are raised when a key or index used on
@@ -120,7 +140,7 @@
 
    Raised when a floating point operation fails.  This exception is always defined,
    but can only be raised when Python is configured with the
-   :option:`--with-fpectl` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
+   ``--with-fpectl`` option, or the :const:`WANT_SIGFPE_HANDLER` symbol is
    defined in the :file:`pyconfig.h` file.
 
 
@@ -257,6 +277,18 @@
    of the exception instance returns only the message.
 
 
+.. exception:: IndentationError
+
+   Base class for syntax errors related to incorrect indentation.  This is a
+   subclass of :exc:`SyntaxError`.
+
+
+.. exception:: TabError
+
+   Raised when indentation contains an inconsistent use of tabs and spaces.
+   This is a subclass of :exc:`IndentationError`.
+
+
 .. exception:: SystemError
 
    Raised when the interpreter finds an internal error, but the situation does not

Modified: python/branches/pep-3151/Doc/library/filecmp.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/filecmp.rst	(original)
+++ python/branches/pep-3151/Doc/library/filecmp.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Compare files efficiently.
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
+**Source code:** :source:`Lib/filecmp.py`
+
+--------------
 
 The :mod:`filecmp` module defines functions to compare files and directories,
 with various optional time/correctness trade-offs. For comparing files,

Modified: python/branches/pep-3151/Doc/library/fileformats.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/fileformats.rst	(original)
+++ python/branches/pep-3151/Doc/library/fileformats.rst	Sat Feb 26 08:16:32 2011
@@ -5,7 +5,7 @@
 ************
 
 The modules described in this chapter parse various miscellaneous file formats
-that aren't markup languages or are related to e-mail.
+that aren't markup languages and are not related to e-mail.
 
 
 .. toctree::

Modified: python/branches/pep-3151/Doc/library/fileinput.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/fileinput.rst	(original)
+++ python/branches/pep-3151/Doc/library/fileinput.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Guido van Rossum <guido at python.org>
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/fileinput.py`
+
+--------------
 
 This module implements a helper class and functions to quickly write a
 loop over standard input or a list of files. If you just want to read or

Modified: python/branches/pep-3151/Doc/library/fnmatch.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/fnmatch.rst	(original)
+++ python/branches/pep-3151/Doc/library/fnmatch.rst	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,10 @@
 
 .. index:: module: re
 
+**Source code:** :source:`Lib/fnmatch.py`
+
+--------------
+
 This module provides support for Unix shell-style wildcards, which are *not* the
 same as regular expressions (which are documented in the :mod:`re` module).  The
 special characters used in shell-style wildcards are:
@@ -88,4 +92,3 @@
 
    Module :mod:`glob`
       Unix shell-style path expansion.
-

Modified: python/branches/pep-3151/Doc/library/fractions.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/fractions.rst	(original)
+++ python/branches/pep-3151/Doc/library/fractions.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
 .. sectionauthor:: Jeffrey Yasskin <jyasskin at gmail.com>
 
+**Source code:** :source:`Lib/fractions.py`
+
+--------------
 
 The :mod:`fractions` module provides support for rational number arithmetic.
 

Modified: python/branches/pep-3151/Doc/library/ftplib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/ftplib.rst	(original)
+++ python/branches/pep-3151/Doc/library/ftplib.rst	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,10 @@
    pair: FTP; protocol
    single: FTP; ftplib (standard module)
 
+**Source code:** :source:`Lib/ftplib.py`
+
+--------------
+
 This module defines the class :class:`FTP` and a few related items. The
 :class:`FTP` class implements the client side of the FTP protocol.  You can use
 this to write Python programs that perform a variety of automated FTP jobs, such

Modified: python/branches/pep-3151/Doc/library/functions.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/functions.rst	(original)
+++ python/branches/pep-3151/Doc/library/functions.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,24 @@
 The Python interpreter has a number of functions and types built into it that
 are always available.  They are listed here in alphabetical order.
 
+===================  =================  ==================  ================  ====================
+..                   ..                 Built-in Functions  ..                ..
+===================  =================  ==================  ================  ====================
+:func:`abs`          :func:`dict`       :func:`help`        :func:`min`       :func:`setattr`
+:func:`all`          :func:`dir`        :func:`hex`         :func:`next`      :func:`slice`
+:func:`any`          :func:`divmod`     :func:`id`          :func:`object`    :func:`sorted`
+:func:`ascii`        :func:`enumerate`  :func:`input`       :func:`oct`       :func:`staticmethod`
+:func:`bin`          :func:`eval`       :func:`int`         :func:`open`      :func:`str`
+:func:`bool`         :func:`exec`       :func:`isinstance`  :func:`ord`       :func:`sum`
+:func:`bytearray`    :func:`filter`     :func:`issubclass`  :func:`pow`       :func:`super`
+:func:`bytes`        :func:`float`      :func:`iter`        :func:`print`     :func:`tuple`
+:func:`callable`     :func:`format`     :func:`len`         :func:`property`  :func:`type`
+:func:`chr`          :func:`frozenset`  :func:`list`        :func:`range`     :func:`vars`
+:func:`classmethod`  :func:`getattr`    :func:`locals`      :func:`repr`      :func:`zip`
+:func:`compile`      :func:`globals`    :func:`map`         :func:`reversed`  :func:`__import__`
+:func:`complex`      :func:`hasattr`    :func:`max`         :func:`round`
+:func:`delattr`      :func:`hash`       :func:`memoryview`  :func:`set`
+===================  =================  ==================  ================  ====================
 
 .. function:: abs(x)
 
@@ -70,7 +88,7 @@
    Return a new array of bytes.  The :class:`bytearray` type is a mutable
    sequence of integers in the range 0 <= x < 256.  It has most of the usual
    methods of mutable sequences, described in :ref:`typesseq-mutable`, as well
-   as most methods that the :class:`str` type has, see :ref:`bytes-methods`.
+   as most methods that the :class:`bytes` type has, see :ref:`bytes-methods`.
 
    The optional *source* parameter can be used to initialize the array in a few
    different ways:
@@ -103,13 +121,30 @@
    Bytes objects can also be created with literals, see :ref:`strings`.
 
 
+.. function:: callable(object)
+
+   Return :const:`True` if the *object* argument appears callable,
+   :const:`False` if not.  If this returns true, it is still possible that a
+   call fails, but if it is false, calling *object* will never succeed.
+   Note that classes are callable (calling a class returns a new instance);
+   instances are callable if their class has a :meth:`__call__` method.
+
+   .. versionadded:: 3.2
+      This function was first removed in Python 3.0 and then brought back
+      in Python 3.2.
+
+
 .. function:: chr(i)
 
-   Return the string of one character whose Unicode codepoint is the integer
+   Return the string representing a character whose Unicode codepoint is the integer
    *i*.  For example, ``chr(97)`` returns the string ``'a'``. This is the
-   inverse of :func:`ord`.  The valid range for the argument depends how Python
-   was configured -- it may be either UCS2 [0..0xFFFF] or UCS4 [0..0x10FFFF].
-   :exc:`ValueError` will be raised if *i* is outside that range.
+   inverse of :func:`ord`.  The valid range for the argument is from 0 through
+   1,114,111 (0x10FFFF in base 16).  :exc:`ValueError` will be raised if *i* is
+   outside that range.
+
+   Note that on narrow Unicode builds, the result is a string of
+   length two for *i* greater than 65,535 (0xFFFF in hexadecimal).
+
 
 
 .. function:: classmethod(function)
@@ -139,7 +174,7 @@
    type hierarchy in :ref:`types`.
 
 
-.. function:: compile(source, filename, mode, flags=0, dont_inherit=False)
+.. function:: compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
 
    Compile the *source* into a code or AST object.  Code objects can be executed
    by :func:`exec` or :func:`eval`.  *source* can either be a string or an AST
@@ -171,6 +206,12 @@
    can be found as the :attr:`compiler_flag` attribute on the :class:`_Feature`
    instance in the :mod:`__future__` module.
 
+   The argument *optimize* specifies the optimization level of the compiler; the
+   default value of ``-1`` selects the optimization level of the interpreter as
+   given by :option:`-O` options.  Explicit levels are ``0`` (no optimization;
+   ``__debug__`` is true), ``1`` (asserts are removed, ``__debug__`` is false)
+   or ``2`` (docstrings are removed too).
+
    This function raises :exc:`SyntaxError` if the compiled source is invalid,
    and :exc:`TypeError` if the source contains null bytes.
 
@@ -183,7 +224,7 @@
 
    .. versionchanged:: 3.2
       Allowed use of Windows and Mac newlines.  Also input in ``'exec'`` mode
-      does not have to end in a newline anymore.
+      does not have to end in a newline anymore.  Added the *optimize* parameter.
 
 
 .. function:: complex([real[, imag]])
@@ -255,7 +296,7 @@
       ['Struct', '__builtins__', '__doc__', '__file__', '__name__',
        '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
        'unpack', 'unpack_from']
-      >>> class Foo(object):
+      >>> class Foo:
       ...     def __dir__(self):
       ...         return ["kan", "ga", "roo"]
       ...
@@ -395,26 +436,54 @@
 
 .. function:: float([x])
 
-   Convert a string or a number to floating point.  If the argument is a string,
-   it must contain a possibly signed decimal or floating point number, possibly
-   embedded in whitespace. The argument may also be ``'[+|-]nan'`` or
-   ``'[+|-]inf'``.  Otherwise, the argument may be an integer or a floating
-   point number, and a floating point number with the same value (within
-   Python's floating point precision) is returned.  If no argument is given,
-   ``0.0`` is returned.
+   .. index::
+      single: NaN
+      single: Infinity
 
-   .. note::
+   Convert a string or a number to floating point.
 
-      .. index::
-         single: NaN
-         single: Infinity
-
-      When passing in a string, values for NaN and Infinity may be returned,
-      depending on the underlying C library.  Float accepts the strings
-      ``'nan'``, ``'inf'`` and ``'-inf'`` for NaN and positive or negative
-      infinity.  The case and a leading + are ignored as well as a leading - is
-      ignored for NaN.  Float always represents NaN and infinity as ``nan``,
-      ``inf`` or ``-inf``.
+   If the argument is a string, it should contain a decimal number, optionally
+   preceded by a sign, and optionally embedded in whitespace.  The optional
+   sign may be ``'+'`` or ``'-'``; a ``'+'`` sign has no effect on the value
+   produced.  The argument may also be a string representing a NaN
+   (not-a-number), or a positive or negative infinity.  More precisely, the
+   input must conform to the following grammar after leading and trailing
+   whitespace characters are removed:
+
+   .. productionlist::
+      sign: "+" | "-"
+      infinity: "Infinity" | "inf"
+      nan: "nan"
+      numeric_value: `floatnumber` | `infinity` | `nan`
+      numeric_string: [`sign`] `numeric_value`
+
+   Here ``floatnumber`` is the form of a Python floating-point literal,
+   described in :ref:`floating`.  Case is not significant, so, for example,
+   "inf", "Inf", "INFINITY" and "iNfINity" are all acceptable spellings for
+   positive infinity.
+
+   Otherwise, if the argument is an integer or a floating point number, a
+   floating point number with the same value (within Python's floating point
+   precision) is returned.  If the argument is outside the range of a Python
+   float, an :exc:`OverflowError` will be raised.
+
+   For a general Python object ``x``, ``float(x)`` delegates to
+   ``x.__float__()``.
+
+   If no argument is given, ``0.0`` is returned.
+
+   Examples::
+
+      >>> float('+1.23')
+      1.23
+      >>> float('   -12345\n')
+      -12345.0
+      >>> float('1e-003')
+      0.001
+      >>> float('+1E6')
+      1000000.0
+      >>> float('-Infinity')
+      -inf
 
    The float type is described in :ref:`typesnumeric`.
 
@@ -822,14 +891,14 @@
 .. XXX works for bytes too, but should it?
 .. function:: ord(c)
 
-   Given a string of length one, return an integer representing the Unicode code
-   point of the character.  For example, ``ord('a')`` returns the integer ``97``
+   Given a string representing one Uncicode character, return an integer
+   representing the Unicode code
+   point of that character.  For example, ``ord('a')`` returns the integer ``97``
    and ``ord('\u2020')`` returns ``8224``.  This is the inverse of :func:`chr`.
 
-   If the argument length is not one, a :exc:`TypeError` will be raised.  (If
-   Python was built with UCS2 Unicode, then the character's code point must be
-   in the range [0..65535] inclusive; otherwise the string length is two!)
-
+   On wide Unicode builds, if the argument length is not one, a
+   :exc:`TypeError` will be raised.  On narrow Unicode builds, strings
+   of length two are accepted when they form a UTF-16 surrogate pair.
 
 .. function:: pow(x, y[, z])
 
@@ -871,7 +940,7 @@
    function for setting, and *fdel* a function for del'ing, an attribute.  Typical
    use is to define a managed attribute ``x``::
 
-      class C(object):
+      class C:
           def __init__(self):
               self._x = None
 
@@ -890,7 +959,7 @@
    property will copy *fget*'s docstring (if it exists).  This makes it possible to
    create read-only properties easily using :func:`property` as a :term:`decorator`::
 
-      class Parrot(object):
+      class Parrot:
           def __init__(self):
               self._voltage = 100000
 
@@ -907,7 +976,7 @@
    corresponding accessor function set to the decorated function.  This is
    best explained with an example::
 
-      class C(object):
+      class C:
           def __init__(self):
               self._x = None
 
@@ -960,8 +1029,33 @@
       >>> list(range(1, 0))
       []
 
+   Range objects implement the :class:`collections.Sequence` ABC, and provide
+   features such as containment tests, element index lookup, slicing and
+   support for negative indices:
+
+      >>> r = range(0, 20, 2)
+      >>> r
+      range(0, 20, 2)
+      >>> 11 in r
+      False
+      >>> 10 in r
+      True
+      >>> r.index(10)
+      5
+      >>> r[5]
+      10
+      >>> r[:5]
+      range(0, 10, 2)
+      >>> r[-1]
+      18
+
+   Ranges containing absolute values larger than :data:`sys.maxsize` are permitted
+   but some features (such as :func:`len`) will raise :exc:`OverflowError`.
+
    .. versionchanged:: 3.2
-      Testing integers for membership takes constant time instead of iterating
+      Implement the Sequence ABC.
+      Support slicing and negative indices.
+      Test integers for membership in constant time instead of iterating
       through all items.
 
 
@@ -1211,7 +1305,7 @@
    attribute.  For example, the following two statements create identical
    :class:`type` objects:
 
-      >>> class X(object):
+      >>> class X:
       ...     a = 1
       ...
       >>> X = type('X', (object,), dict(a=1))

Modified: python/branches/pep-3151/Doc/library/functools.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/functools.rst	(original)
+++ python/branches/pep-3151/Doc/library/functools.rst	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,9 @@
 .. moduleauthor:: Nick Coghlan <ncoghlan at gmail.com>
 .. sectionauthor:: Peter Harris <scav at blueyonder.co.uk>
 
+**Source code:** :source:`Lib/functools.py`
+
+--------------
 
 The :mod:`functools` module is for higher-order functions: functions that act on
 or return other functions. In general, any callable object can be treated as a
@@ -15,7 +18,7 @@
 
 The :mod:`functools` module defines the following functions:
 
-..  function:: cmp_to_key(func)
+.. function:: cmp_to_key(func)
 
    Transform an old-style comparison function to a key-function.  Used with
    tools that accept key functions (such as :func:`sorted`, :func:`min`,
@@ -27,7 +30,7 @@
    A compare function is any callable that accept two arguments, compares them,
    and returns a negative number for less-than, zero for equality, or a positive
    number for greater-than.  A key function is a callable that accepts one
-   argument and returns another value that indicates the position in the desired
+   argument and returns another value indicating the position in the desired
    collation sequence.
 
    Example::
@@ -37,37 +40,76 @@
    .. versionadded:: 3.2
 
 
-.. decorator:: lru_cache(maxsize)
+.. decorator:: lru_cache(maxsize=100)
 
    Decorator to wrap a function with a memoizing callable that saves up to the
    *maxsize* most recent calls.  It can save time when an expensive or I/O bound
    function is periodically called with the same arguments.
 
-   The *maxsize* parameter defaults to 100.  Since a dictionary is used to cache
-   results, the positional and keyword arguments to the function must be
-   hashable.
-
-   The wrapped function is instrumented with two attributes, :attr:`cache_hits`
-   and :attr:`cache_misses` which count the number of successful or unsuccessful
-   cache lookups.  These statistics are helpful for tuning the *maxsize*
-   parameter and for measuring the cache's effectiveness.
+   Since a dictionary is used to cache results, the positional and keyword
+   arguments to the function must be hashable.
+
+   If *maxsize* is set to None, the LRU feature is disabled and the cache
+   can grow without bound.
+
+   To help measure the effectiveness of the cache and tune the *maxsize*
+   parameter, the wrapped function is instrumented with a :func:`cache_info`
+   function that returns a :term:`named tuple` showing *hits*, *misses*,
+   *maxsize* and *currsize*.  In a multi-threaded environment, the hits
+   and misses are approximate.
 
-   The wrapped function also has a :attr:`cache_clear` attribute which can be
-   called (with no arguments) to clear the cache.
+   The decorator also provides a :func:`cache_clear` function for clearing or
+   invalidating the cache.
 
    The original underlying function is accessible through the
-   :attr:`__wrapped__` attribute.  This allows introspection, bypassing
-   the cache, or rewrapping the function with a different caching tool.
+   :attr:`__wrapped__` attribute.  This is useful for introspection, for
+   bypassing the cache, or for rewrapping the function with a different cache.
 
-   A `LRU (least recently used) cache
-   <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_
-   is indicated when the pattern of calls changes over time, such as
-   when more recent calls are the best predictors of upcoming calls
-   (for example, the most popular articles on a news server tend to
-   change every day).
+   An `LRU (least recently used) cache
+   <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_ works
+   best when more recent calls are the best predictors of upcoming calls (for
+   example, the most popular articles on a news server tend to change daily).
+   The cache's size limit assures that the cache does not grow without bound on
+   long-running processes such as web servers.
+
+   Example of an LRU cache for static web content::
+
+        @lru_cache(maxsize=20)
+        def get_pep(num):
+            'Retrieve text of a Python Enhancement Proposal'
+            resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
+            try:
+                with urllib.request.urlopen(resource) as s:
+                    return s.read()
+            except urllib.error.HTTPError:
+                return 'Not Found'
+
+        >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
+        ...     pep = get_pep(n)
+        ...     print(n, len(pep))
+
+        >>> print(get_pep.cache_info())
+        CacheInfo(hits=3, misses=8, maxsize=20, currsize=8)
+
+   Example of efficiently computing
+   `Fibonacci numbers <http://en.wikipedia.org/wiki/Fibonacci_number>`_
+   using a cache to implement a
+   `dynamic programming <http://en.wikipedia.org/wiki/Dynamic_programming>`_
+   technique::
+
+        @lru_cache(maxsize=None)
+        def fib(n):
+            if n < 2:
+                return n
+            return fib(n-1) + fib(n-2)
 
-   .. versionadded:: 3.2
+        >>> print([fib(n) for n in range(16)])
+        [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
+
+        >>> print(fib.cache_info())
+        CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
 
+   .. versionadded:: 3.2
 
 .. decorator:: total_ordering
 

Modified: python/branches/pep-3151/Doc/library/getopt.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/getopt.rst	(original)
+++ python/branches/pep-3151/Doc/library/getopt.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,10 @@
    :synopsis: Portable parser for command line options; support both short and
               long option names.
 
+**Source code:** :source:`Lib/getopt.py`
+
+--------------
+
 .. note::
    The :mod:`getopt` module is a parser for command line options whose API is
    designed to be familiar to users of the C :c:func:`getopt` function. Users who
@@ -47,7 +51,7 @@
    empty string.  Long options on the command line can be recognized so long as
    they provide a prefix of the option name that matches exactly one of the
    accepted options.  For example, if *longopts* is ``['foo', 'frob']``, the
-   option :option:`--fo` will match as :option:`--foo`, but :option:`--f` will
+   option ``--fo`` will match as ``--foo``, but ``--f`` will
    not match uniquely, so :exc:`GetoptError` will be raised.
 
    The return value consists of two elements: the first is a list of ``(option,
@@ -68,7 +72,7 @@
    intermixed. The :func:`getopt` function stops processing options as soon as a
    non-option argument is encountered.
 
-   If the first character of the option string is '+', or if the environment
+   If the first character of the option string is ``'+'``, or if the environment
    variable :envvar:`POSIXLY_CORRECT` is set, then option processing stops as
    soon as a non-option argument is encountered.
 

Modified: python/branches/pep-3151/Doc/library/gettext.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/gettext.rst	(original)
+++ python/branches/pep-3151/Doc/library/gettext.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Barry A. Warsaw <barry at zope.com>
 .. sectionauthor:: Barry A. Warsaw <barry at zope.com>
 
+**Source code:** :source:`Lib/gettext.py`
+
+--------------
 
 The :mod:`gettext` module provides internationalization (I18N) and localization
 (L10N) services for your Python modules and applications. It supports both the

Modified: python/branches/pep-3151/Doc/library/glob.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/glob.rst	(original)
+++ python/branches/pep-3151/Doc/library/glob.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,10 @@
 
 .. index:: single: filenames; pathname expansion
 
+**Source code:** :source:`Lib/glob.py`
+
+--------------
+
 The :mod:`glob` module finds all the pathnames matching a specified pattern
 according to the rules used by the Unix shell.  No tilde expansion is done, but
 ``*``, ``?``, and character ranges expressed with ``[]`` will be correctly

Modified: python/branches/pep-3151/Doc/library/grp.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/grp.rst	(original)
+++ python/branches/pep-3151/Doc/library/grp.rst	Sat Feb 26 08:16:32 2011
@@ -30,7 +30,9 @@
 The gid is an integer, name and password are strings, and the member list is a
 list of strings. (Note that most users are not explicitly listed as members of
 the group they are in according to the password database.  Check both databases
-to get complete membership information.)
+to get complete membership information.  Also note that a ``gr_name`` that
+starts with a ``+`` or ``-`` is likely to be a YP/NIS reference and may not be
+accessible via :func:`getgrnam` or :func:`getgrgid`.)
 
 It defines the following items:
 

Modified: python/branches/pep-3151/Doc/library/gzip.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/gzip.rst	(original)
+++ python/branches/pep-3151/Doc/library/gzip.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,10 @@
 .. module:: gzip
    :synopsis: Interfaces for gzip compression and decompression using file objects.
 
+**Source code:** :source:`Lib/gzip.py`
+
+--------------
+
 This module provides a simple interface to compress and decompress files just
 like the GNU programs :program:`gzip` and :program:`gunzip` would.
 

Modified: python/branches/pep-3151/Doc/library/hashlib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/hashlib.rst	(original)
+++ python/branches/pep-3151/Doc/library/hashlib.rst	Sat Feb 26 08:16:32 2011
@@ -11,6 +11,10 @@
    single: message digest, MD5
    single: secure hash algorithm, SHA1, SHA224, SHA256, SHA384, SHA512
 
+**Source code:** :source:`Lib/hashlib.py`
+
+--------------
+
 This module implements a common interface to many different secure hash and
 message digest algorithms.  Included are the FIPS secure hash algorithms SHA1,
 SHA224, SHA256, SHA384, and SHA512 (defined in FIPS 180-2) as well as RSA's MD5
@@ -135,7 +139,7 @@
 .. method:: hash.digest()
 
    Return the digest of the data passed to the :meth:`update` method so far.
-   This is a bytes array of size :attr:`digest_size` which may contain bytes in
+   This is a bytes object of size :attr:`digest_size` which may contain bytes in
    the whole range from 0 to 255.
 
 

Modified: python/branches/pep-3151/Doc/library/heapq.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/heapq.rst	(original)
+++ python/branches/pep-3151/Doc/library/heapq.rst	Sat Feb 26 08:16:32 2011
@@ -8,14 +8,19 @@
 .. sectionauthor:: François Pinard
 .. sectionauthor:: Raymond Hettinger
 
+**Source code:** :source:`Lib/heapq.py`
+
+--------------
+
 This module provides an implementation of the heap queue algorithm, also known
 as the priority queue algorithm.
 
-Heaps are arrays for which ``heap[k] <= heap[2*k+1]`` and ``heap[k] <=
-heap[2*k+2]`` for all *k*, counting elements from zero.  For the sake of
-comparison, non-existing elements are considered to be infinite.  The
-interesting property of a heap is that ``heap[0]`` is always its smallest
-element.
+Heaps are binary trees for which every parent node has a value less than or
+equal to any of its children.  This implementation uses arrays for which
+``heap[k] <= heap[2*k+1]`` and ``heap[k] <= heap[2*k+2]`` for all *k*, counting
+elements from zero.  For the sake of comparison, non-existing elements are
+considered to be infinite.  The interesting property of a heap is that its
+smallest element is always the root, ``heap[0]``.
 
 The API below differs from textbook heap algorithms in two aspects: (a) We use
 zero-based indexing.  This makes the relationship between the index for a node

Modified: python/branches/pep-3151/Doc/library/hmac.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/hmac.rst	(original)
+++ python/branches/pep-3151/Doc/library/hmac.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,9 @@
 .. moduleauthor:: Gerhard Häring <ghaering at users.sourceforge.net>
 .. sectionauthor:: Gerhard Häring <ghaering at users.sourceforge.net>
 
+**Source code:** :source:`Lib/hmac.py`
+
+--------------
 
 This module implements the HMAC algorithm as described by :rfc:`2104`.
 

Modified: python/branches/pep-3151/Doc/library/html.entities.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/html.entities.rst	(original)
+++ python/branches/pep-3151/Doc/library/html.entities.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Definitions of HTML general entities.
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/html/entities.py`
+
+--------------
 
 This module defines three dictionaries, ``name2codepoint``, ``codepoint2name``,
 and ``entitydefs``. ``entitydefs`` is used to provide the :attr:`entitydefs`

Modified: python/branches/pep-3151/Doc/library/html.parser.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/html.parser.rst	(original)
+++ python/branches/pep-3151/Doc/library/html.parser.rst	Sat Feb 26 08:16:32 2011
@@ -9,12 +9,20 @@
    single: HTML
    single: XHTML
 
+**Source code:** :source:`Lib/html/parser.py`
+
+--------------
+
 This module defines a class :class:`HTMLParser` which serves as the basis for
 parsing text files formatted in HTML (HyperText Mark-up Language) and XHTML.
 
-.. class:: HTMLParser()
+.. class:: HTMLParser(strict=True)
 
-   The :class:`HTMLParser` class is instantiated without arguments.
+   Create a parser instance.  If *strict* is ``True`` (the default), invalid
+   html results in :exc:`~html.parser.HTMLParseError` exceptions [#]_.  If
+   *strict* is ``False``, the parser uses heuristics to make a best guess at
+   the intention of any invalid html it encounters, similar to the way most
+   browsers do.
 
    An :class:`HTMLParser` instance is fed HTML data and calls handler functions when tags
    begin and end.  The :class:`HTMLParser` class is meant to be overridden by the
@@ -23,6 +31,8 @@
    This parser does not check that end tags match start tags or call the end-tag
    handler for elements which are closed implicitly by closing an outer element.
 
+   .. versionchanged:: 3.2 *strict* keyword added
+
 An exception is defined as well:
 
 
@@ -191,3 +201,8 @@
    Encountered a html end tag
 
 
+.. rubric:: Footnotes
+
+.. [#] For backward compatibility reasons *strict* mode does not raise
+       exceptions for all non-compliant HTML.  That is, some invalid HTML
+       is tolerated even in *strict* mode.

Modified: python/branches/pep-3151/Doc/library/html.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/html.rst	(original)
+++ python/branches/pep-3151/Doc/library/html.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 
 .. versionadded:: 3.2
 
+**Source code:** :source:`Lib/html/__init__.py`
+
+--------------
 
 This module defines utilities to manipulate HTML.
 

Modified: python/branches/pep-3151/Doc/library/http.client.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/http.client.rst	(original)
+++ python/branches/pep-3151/Doc/library/http.client.rst	Sat Feb 26 08:16:32 2011
@@ -11,6 +11,10 @@
 
 .. index:: module: urllib.request
 
+**Source code:** :source:`Lib/http/client.py`
+
+--------------
+
 This module defines classes which implement the client side of the HTTP and
 HTTPS protocols.  It is normally not used directly --- the module
 :mod:`urllib.request` uses it to handle URLs that use HTTP and HTTPS.
@@ -23,19 +27,16 @@
 The module provides the following classes:
 
 
-.. class:: HTTPConnection(host, port=None, strict=None[, timeout[, source_address]])
+.. class:: HTTPConnection(host, port=None[, strict[, timeout[, source_address]]])
 
    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 ``host:port``, else the default HTTP port (80) is
-   used.  When True, the optional parameter *strict* (which defaults to a false
-   value) causes ``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 *timeout* parameter is given, blocking
+   used.  If the optional *timeout* parameter is given, blocking
    operations (like connection attempts) will timeout after that many seconds
    (if it is not given, the global default timeout setting is used).
-   The optional *source_address* parameter may be a typle of a (host, port)
+   The optional *source_address* parameter may be a tuple of a (host, port)
    to use as the source address the HTTP connection is made from.
 
    For example, the following calls all create instances that connect to the server
@@ -49,8 +50,12 @@
    .. versionchanged:: 3.2
       *source_address* was added.
 
+   .. versionchanged:: 3.2
+      The *strict* parameter is deprecated.  HTTP 0.9-style "Simple Responses"
+      are not supported anymore.
 
-.. class:: HTTPSConnection(host, port=None, key_file=None, cert_file=None, strict=None[, timeout[, source_address]], *, context=None, check_hostname=None)
+
+.. class:: HTTPSConnection(host, port=None, key_file=None, cert_file=None[, strict[, timeout[, source_address]]], *, context=None, check_hostname=None)
 
    A subclass of :class:`HTTPConnection` that uses SSL for communication with
    secure servers.  Default port is ``443``.  If *context* is specified, it
@@ -80,12 +85,20 @@
       This class now supports HTTPS virtual hosts if possible (that is,
       if :data:`ssl.HAS_SNI` is true).
 
+   .. versionchanged:: 3.2
+      The *strict* parameter is deprecated.  HTTP 0.9-style "Simple Responses"
+      are not supported anymore.
 
-.. class:: HTTPResponse(sock, debuglevel=0, strict=0, method=None, url=None)
+
+.. class:: HTTPResponse(sock, debuglevel=0[, strict], method=None, url=None)
 
    Class whose instances are returned upon successful connection.  Not
    instantiated directly by user.
 
+   .. versionchanged:: 3.2
+      The *strict* parameter is deprecated.  HTTP 0.9-style "Simple Responses"
+      are not supported anymore.
+
 
 The following exceptions are raised as appropriate:
 
@@ -384,14 +397,18 @@
    string.
 
    The *body* may also be an open :term:`file object`, in which case the
-   contents of the file is sent; this file object should support
-   ``fileno()`` and ``read()`` methods. The header Content-Length is
-   automatically set to the length of the file as reported by
-   stat.
+   contents of the file is sent; this file object should support ``fileno()``
+   and ``read()`` methods. The header Content-Length is automatically set to
+   the length of the file as reported by stat. The *body* argument may also be
+   an iterable and Content-Length header should be explicitly provided when the
+   body is an iterable.
 
    The *headers* argument should be a mapping of extra HTTP
    headers to send with the request.
 
+   .. versionadded:: 3.2
+      *body* can now be an iterable.
+
 .. method:: HTTPConnection.getresponse()
 
    Should be called after a request is sent to get the response from the server.
@@ -405,8 +422,10 @@
 
 .. method:: HTTPConnection.set_debuglevel(level)
 
-   Set the debugging level (the amount of debugging output printed). The default
-   debug level is ``0``, meaning no debugging output is printed.
+   Set the debugging level.  The default debug level is ``0``, meaning no
+   debugging output is printed.  Any value greater than ``0`` will cause all
+   currently defined debug output to be printed to stdout.  The ``debuglevel``
+   is passed to any new :class:`HTTPResponse` objects that are created.
 
    .. versionadded:: 3.1
 

Modified: python/branches/pep-3151/Doc/library/http.cookiejar.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/http.cookiejar.rst	(original)
+++ python/branches/pep-3151/Doc/library/http.cookiejar.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: John J. Lee <jjl at pobox.com>
 .. sectionauthor:: John J. Lee <jjl at pobox.com>
 
+**Source code:** :source:`Lib/http/cookiejar.py`
+
+--------------
 
 The :mod:`http.cookiejar` module defines classes for automatic handling of HTTP
 cookies.  It is useful for accessing web sites that require small pieces of data

Modified: python/branches/pep-3151/Doc/library/http.cookies.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/http.cookies.rst	(original)
+++ python/branches/pep-3151/Doc/library/http.cookies.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Timothy O'Malley <timo at alum.mit.edu>
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
+**Source code:** :source:`Lib/http/cookies.py`
+
+--------------
 
 The :mod:`http.cookies` module defines classes for abstracting the concept of
 cookies, an HTTP state management mechanism. It supports both simple string-only

Modified: python/branches/pep-3151/Doc/library/http.server.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/http.server.rst	(original)
+++ python/branches/pep-3151/Doc/library/http.server.rst	Sat Feb 26 08:16:32 2011
@@ -11,6 +11,10 @@
    single: URL
    single: httpd
 
+**Source code:** :source:`Lib/http/server.py`
+
+--------------
+
 This module defines classes for implementing HTTP servers (Web servers).
 
 One class, :class:`HTTPServer`, is a :class:`socketserver.TCPServer` subclass.
@@ -182,22 +186,29 @@
 
    .. method:: send_header(keyword, value)
 
-      Writes a specific HTTP header to the output stream. *keyword* should
-      specify the header keyword, with *value* specifying its value.
+      Stores the HTTP header to an internal buffer which will be written to the
+      output stream when :meth:`end_headers` method is invoked.
+      *keyword* should specify the header keyword, with *value*
+      specifying its value.
+
+      .. versionchanged:: 3.2 Storing the headers in an internal buffer
+
 
    .. method:: send_response_only(code, message=None)
 
       Sends the reponse header only, used for the purposes when ``100
-      Continue`` response is sent by the server to the client. If the *message*
-      is not specified, the HTTP message corresponding the response *code*  is
-      sent.
+      Continue`` response is sent by the server to the client. The headers not
+      buffered and sent directly the output stream.If the *message* is not
+      specified, the HTTP message corresponding the response *code*  is sent.
 
       .. versionadded:: 3.2
 
    .. method:: end_headers()
 
-      Sends a blank line, indicating the end of the HTTP headers in the
-      response.
+      Write the buffered HTTP headers to the output stream and send a blank
+      line, indicating the end of the HTTP headers in the response.
+
+      .. versionchanged:: 3.2 Writing the buffered headers to the output stream.
 
    .. method:: log_request(code='-', size='-')
 

Modified: python/branches/pep-3151/Doc/library/idle.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/idle.rst	(original)
+++ python/branches/pep-3151/Doc/library/idle.rst	Sat Feb 26 08:16:32 2011
@@ -286,13 +286,13 @@
 
 If there are arguments:
 
-#. If :option:`-e` is used, arguments are files opened for editing and
+#. If ``-e`` is used, arguments are files opened for editing and
    ``sys.argv`` reflects the arguments passed to IDLE itself.
 
-#. Otherwise, if :option:`-c` is used, all arguments are placed in
+#. Otherwise, if ``-c`` is used, all arguments are placed in
    ``sys.argv[1:...]``, with ``sys.argv[0]`` set to ``'-c'``.
 
-#. Otherwise, if neither :option:`-e` nor :option:`-c` is used, the first
+#. Otherwise, if neither ``-e`` nor ``-c`` is used, the first
    argument is a script which is executed with the remaining arguments in
    ``sys.argv[1:...]``  and ``sys.argv[0]`` set to the script name.  If the script
    name is '-', no script is executed but an interactive Python session is started;

Modified: python/branches/pep-3151/Doc/library/imaplib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/imaplib.rst	(original)
+++ python/branches/pep-3151/Doc/library/imaplib.rst	Sat Feb 26 08:16:32 2011
@@ -16,6 +16,10 @@
    pair: IMAP4_SSL; protocol
    pair: IMAP4_stream; protocol
 
+**Source code:** :source:`Lib/imaplib.py`
+
+--------------
+
 This module defines three classes, :class:`IMAP4`, :class:`IMAP4_SSL` and
 :class:`IMAP4_stream`, which encapsulate a connection to an IMAP4 server and
 implement a large subset of the IMAP4rev1 client protocol as defined in
@@ -56,6 +60,7 @@
    write permission, and the mailbox will need to be re-opened to re-obtain write
    permission.
 
+
 There's also a subclass for secure connections:
 
 
@@ -68,6 +73,7 @@
    and *certfile* are also optional - they can contain a PEM formatted private key
    and certificate chain file for the SSL connection.
 
+
 The second subclass allows for connections created by a child process:
 
 
@@ -83,9 +89,9 @@
 
 .. function:: Internaldate2tuple(datestr)
 
-   Converts an IMAP4 INTERNALDATE string to Coordinated Universal Time. Returns a
-   :mod:`time` module tuple.
-
+   Parse an IMAP4 ``INTERNALDATE`` string and return corresponding local
+   time.  The return value is a :class:`time.struct_time` tuple or
+   None if the string has wrong format.
 
 .. function:: Int2AP(num)
 
@@ -100,9 +106,13 @@
 
 .. function:: Time2Internaldate(date_time)
 
-   Converts a :mod:`time` module tuple to an IMAP4 ``INTERNALDATE`` representation.
-   Returns a string in the form: ``"DD-Mmm-YYYY HH:MM:SS +HHMM"`` (including
-   double-quotes).
+   Convert *date_time* to an IMAP4 ``INTERNALDATE`` representation.  The
+   return value is a string in the form: ``"DD-Mmm-YYYY HH:MM:SS
+   +HHMM"`` (including double-quotes).  The *date_time* argument can be a
+   number (int or float) represening seconds since epoch (as returned
+   by :func:`time.time`), a 9-tuple representing local time (as returned by
+   :func:`time.localtime`), or a double-quoted string.  In the last case, it
+   is assumed to already be in the correct format.
 
 Note that IMAP4 message numbers change as the mailbox changes; in particular,
 after an ``EXPUNGE`` command performs deletions the remaining messages are
@@ -288,9 +298,10 @@
 
 .. method:: IMAP4.open(host, port)
 
-   Opens socket to *port* at *host*. The connection objects established by this
+   Opens socket to *port* at *host*.  This method is implicitly called by
+   the :class:`IMAP4` constructor.  The connection objects established by this
    method will be used in the ``read``, ``readline``, ``send``, and ``shutdown``
-   methods. You may override this method.
+   methods.  You may override this method.
 
 
 .. method:: IMAP4.partial(message_num, message_part, start, length)
@@ -380,7 +391,8 @@
 
 .. method:: IMAP4.shutdown()
 
-   Close connection established in ``open``. You may override this method.
+   Close connection established in ``open``.  This method is implicitly
+   called by :meth:`IMAP4.logout`.  You may override this method.
 
 
 .. method:: IMAP4.socket()
@@ -406,6 +418,15 @@
    This is an ``IMAP4rev1`` extension command.
 
 
+.. method:: IMAP4.starttls(ssl_context=None)
+
+   Send a ``STARTTLS`` command.  The *ssl_context* argument is optional
+   and should be a :class:`ssl.SSLContext` object.  This will enable
+   encryption on the IMAP connection.
+
+   .. versionadded:: 3.2
+
+
 .. method:: IMAP4.status(mailbox, names)
 
    Request named status conditions for *mailbox*.

Modified: python/branches/pep-3151/Doc/library/imghdr.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/imghdr.rst	(original)
+++ python/branches/pep-3151/Doc/library/imghdr.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: imghdr
    :synopsis: Determine the type of image contained in a file or byte stream.
 
+**Source code:** :source:`Lib/imghdr.py`
+
+--------------
 
 The :mod:`imghdr` module determines the type of image contained in a file or
 byte stream.

Modified: python/branches/pep-3151/Doc/library/imp.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/imp.rst	(original)
+++ python/branches/pep-3151/Doc/library/imp.rst	Sat Feb 26 08:16:32 2011
@@ -190,8 +190,8 @@
    continue to use the old class definition.  The same is true for derived classes.
 
 
-The following functions and data provide conveniences for handling :pep:`3147`
-byte-compiled file paths.
+The following functions are conveniences for handling :pep:`3147` byte-compiled
+file paths.
 
 .. versionadded:: 3.2
 
@@ -258,88 +258,6 @@
 
    The module was found as a frozen module (see :func:`init_frozen`).
 
-The following constant and functions are obsolete; their functionality is
-available through :func:`find_module` or :func:`load_module`. They are kept
-around for backward compatibility:
-
-
-.. data:: SEARCH_ERROR
-
-   Unused.
-
-
-.. function:: init_builtin(name)
-
-   Initialize the built-in module called *name* and return its module object along
-   with storing it in ``sys.modules``.  If the module was already initialized, it
-   will be initialized *again*.  Re-initialization involves the copying of the
-   built-in module's ``__dict__`` from the cached module over the module's entry in
-   ``sys.modules``.  If there is no built-in module called *name*, ``None`` is
-   returned.
-
-
-.. function:: init_frozen(name)
-
-   Initialize the frozen module called *name* and return its module object.  If
-   the module was already initialized, it will be initialized *again*.  If there
-   is no frozen module called *name*, ``None`` is returned.  (Frozen modules are
-   modules written in Python whose compiled byte-code object is incorporated
-   into a custom-built Python interpreter by Python's :program:`freeze`
-   utility. See :file:`Tools/freeze/` for now.)
-
-
-.. function:: is_builtin(name)
-
-   Return ``1`` if there is a built-in module called *name* which can be
-   initialized again.  Return ``-1`` if there is a built-in module called *name*
-   which cannot be initialized again (see :func:`init_builtin`).  Return ``0`` if
-   there is no built-in module called *name*.
-
-
-.. function:: is_frozen(name)
-
-   Return ``True`` if there is a frozen module (see :func:`init_frozen`) called
-   *name*, or ``False`` if there is no such module.
-
-
-.. function:: load_compiled(name, pathname, [file])
-
-   .. index:: pair: file; byte-code
-
-   Load and initialize a module implemented as a byte-compiled code file and return
-   its module object.  If the module was already initialized, it will be
-   initialized *again*.  The *name* argument is used to create or access a module
-   object.  The *pathname* argument points to the byte-compiled code file.  The
-   *file* argument is the byte-compiled code file, open for reading in binary mode,
-   from the beginning. It must currently be a real file object, not a user-defined
-   class emulating a file.
-
-
-.. function:: load_dynamic(name, pathname[, file])
-
-   Load and initialize a module implemented as a dynamically loadable shared
-   library and return its module object.  If the module was already initialized, it
-   will be initialized *again*. Re-initialization involves copying the ``__dict__``
-   attribute of the cached instance of the module over the value used in the module
-   cached in ``sys.modules``.  The *pathname* argument must point to the shared
-   library.  The *name* argument is used to construct the name of the
-   initialization function: an external C function called ``initname()`` in the
-   shared library is called.  The optional *file* argument is ignored.  (Note:
-   using shared libraries is highly system dependent, and not all systems support
-   it.)
-
-
-.. function:: load_source(name, pathname[, file])
-
-   Load and initialize a module implemented as a Python source file and return its
-   module object.  If the module was already initialized, it will be initialized
-   *again*.  The *name* argument is used to create or access a module object.  The
-   *pathname* argument points to the source file.  The *file* argument is the
-   source file, open for reading as text, from the beginning. It must currently be
-   a real file object, not a user-defined class emulating a file.  Note that if a
-   properly matching byte-compiled file (with suffix :file:`.pyc` or :file:`.pyo`)
-   exists, it will be used instead of parsing the given source file.
-
 
 .. class:: NullImporter(path_string)
 
@@ -390,10 +308,3 @@
            # Since we may exit via an exception, close fp explicitly.
            if fp:
                fp.close()
-
-.. index:: module: knee
-
-A more complete example that implements hierarchical module names and includes a
-:func:`reload` function can be found in the module :mod:`knee`.  The :mod:`knee`
-module can be found in :file:`Demo/imputil/` in the Python source distribution.
-

Modified: python/branches/pep-3151/Doc/library/importlib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/importlib.rst	(original)
+++ python/branches/pep-3151/Doc/library/importlib.rst	Sat Feb 26 08:16:32 2011
@@ -32,7 +32,7 @@
 
     `Packages specification <http://www.python.org/doc/essays/packages.html>`__
         Original specification of packages. Some semantics have changed since
-        the writing of this document (e.g. redirecting based on :keyword:`None`
+        the writing of this document (e.g. redirecting based on ``None``
         in :data:`sys.modules`).
 
     The :func:`.__import__` function
@@ -109,7 +109,7 @@
         module. If the :term:`finder` is found on :data:`sys.meta_path` and the
         module to be searched for is a subpackage or module then *path* will
         be the value of :attr:`__path__` from the parent package. If a loader
-        cannot be found, :keyword:`None` is returned.
+        cannot be found, ``None`` is returned.
 
 
 .. class:: Loader
@@ -185,14 +185,14 @@
     .. method:: get_code(fullname)
 
         An abstract method to return the :class:`code` object for a module.
-        :keyword:`None` is returned if the module does not have a code object
+        ``None`` is returned if the module does not have a code object
         (e.g. built-in module).  :exc:`ImportError` is raised if loader cannot
         find the requested module.
 
     .. method:: get_source(fullname)
 
         An abstract method to return the source of a module. It is returned as
-        a text string with universal newlines. Returns :keyword:`None` if no
+        a text string with universal newlines. Returns ``None`` if no
         source is available (e.g. a built-in module). Raises :exc:`ImportError`
         if the loader cannot find the module specified.
 
@@ -320,7 +320,7 @@
     .. method:: source_path(fullname)
 
         An abstract method that returns the path to the source code for a
-        module. Should return :keyword:`None` if there is no source code.
+        module. Should return ``None`` if there is no source code.
         Raises :exc:`ImportError` if the loader knows it cannot handle the
         module.
 
@@ -329,7 +329,7 @@
         A concrete implementation of
         :meth:`importlib.abc.ExecutionLoader.get_filename` that
         relies on :meth:`source_path`. If :meth:`source_path` returns
-        :keyword:`None`, then :exc:`ImportError` is raised.
+        ``None``, then :exc:`ImportError` is raised.
 
     .. method:: load_module(fullname)
 
@@ -374,13 +374,13 @@
 
         An abstract method which returns the modification time for the source
         code of the specified module. The modification time should be an
-        integer. If there is no source code, return :keyword:`None`. If the
+        integer. If there is no source code, return ``None``. If the
         module cannot be found then :exc:`ImportError` is raised.
 
     .. method:: bytecode_path(fullname)
 
         An abstract method which returns the path to the bytecode for the
-        specified module, if it exists. It returns :keyword:`None`
+        specified module, if it exists. It returns ``None``
         if no bytecode exists (yet).
         Raises :exc:`ImportError` if the loader knows it cannot handle the
         module.
@@ -398,8 +398,8 @@
     .. method:: write_bytecode(fullname, bytecode)
 
         An abstract method which has the loader write *bytecode* for future
-        use. If the bytecode is written, return :keyword:`True`. Return
-        :keyword:`False` if the bytecode could not be written. This method
+        use. If the bytecode is written, return ``True``. Return
+        ``False`` if the bytecode could not be written. This method
         should not be called if :data:`sys.dont_write_bytecode` is true.
         The *bytecode* argument should be a bytes string or bytes array.
 
@@ -457,7 +457,7 @@
         :data:`sys.path_importer_cache`, then :data:`sys.path_hooks` is
         searched for a finder for the path entry and, if found, is stored in
         :data:`sys.path_importer_cache` along with being queried about the
-        module. If no finder is ever found then :keyword:`None` is returned.
+        module. If no finder is ever found then ``None`` is returned.
 
 
 :mod:`importlib.util` -- Utility code for importers
@@ -506,7 +506,7 @@
 
     A :term:`decorator` for a :term:`loader` to set the :attr:`__package__`
     attribute on the module returned by the loader. If :attr:`__package__` is
-    set and has a value other than :keyword:`None` it will not be changed.
+    set and has a value other than ``None`` it will not be changed.
     Note that the module returned by the loader is what has the attribute
     set on and not the module found in :data:`sys.modules`.
 

Modified: python/branches/pep-3151/Doc/library/index.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/index.rst	(original)
+++ python/branches/pep-3151/Doc/library/index.rst	Sat Feb 26 08:16:32 2011
@@ -49,6 +49,7 @@
    strings.rst
    datatypes.rst
    numeric.rst
+   functional.rst
    filesys.rst
    persistence.rst
    archiving.rst

Modified: python/branches/pep-3151/Doc/library/inspect.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/inspect.rst	(original)
+++ python/branches/pep-3151/Doc/library/inspect.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Ka-Ping Yee <ping at lfw.org>
 .. sectionauthor:: Ka-Ping Yee <ping at lfw.org>
 
+**Source code:** :source:`Lib/inspect.py`
+
+--------------
 
 The :mod:`inspect` module provides several useful functions to help get
 information about live objects such as modules, classes, methods, functions,
@@ -176,17 +179,16 @@
 
 .. function:: getmoduleinfo(path)
 
-   Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode,
-   module_type)`` of values that describe how Python will interpret the file
-   identified by *path* if it is a module, or ``None`` if it would not be
-   identified as a module.  The return tuple is ``(name, suffix, mode, mtype)``,
-   where *name* is the name of the module without the name of any enclosing
-   package, *suffix* is the trailing part of the file name (which may not be a
-   dot-delimited extension), *mode* is the :func:`open` mode that would be used
-   (``'r'`` or ``'rb'``), and *mtype* is an integer giving the type of the
-   module.  *mtype* will have a value which can be compared to the constants
-   defined in the :mod:`imp` module; see the documentation for that module for
-   more information on module types.
+   Returns a :term:`named tuple` ``ModuleInfo(name, suffix, mode, module_type)``
+   of values that describe how Python will interpret the file identified by
+   *path* if it is a module, or ``None`` if it would not be identified as a
+   module.  In that tuple, *name* is the name of the module without the name of
+   any enclosing package, *suffix* is the trailing part of the file name (which
+   may not be a dot-delimited extension), *mode* is the :func:`open` mode that
+   would be used (``'r'`` or ``'rb'``), and *module_type* is an integer giving
+   the type of the module.  *module_type* will have a value which can be
+   compared to the constants defined in the :mod:`imp` module; see the
+   documentation for that module for more information on module types.
 
 
 .. function:: getmodulename(path)
@@ -391,12 +393,12 @@
 .. function:: getargspec(func)
 
    Get the names and default values of a Python function's arguments. A
-   :term:`named tuple` ``ArgSpec(args, varargs, keywords,
-   defaults)`` is returned. *args* is a list of
-   the argument names. *varargs* and *varkw* are the names of the ``*`` and
-   ``**`` arguments or ``None``. *defaults* is a tuple of default argument
-   values or None if there are no default arguments; if this tuple has *n*
-   elements, they correspond to the last *n* elements listed in *args*.
+   :term:`named tuple` ``ArgSpec(args, varargs, keywords, defaults)`` is
+   returned. *args* is a list of the argument names. *varargs* and *keywords*
+   are the names of the ``*`` and ``**`` arguments or ``None``. *defaults* is a
+   tuple of default argument values or None if there are no default arguments;
+   if this tuple has *n* elements, they correspond to the last *n* elements
+   listed in *args*.
 
    .. deprecated:: 3.0
       Use :func:`getfullargspec` instead, which provides information about
@@ -425,8 +427,8 @@
 
    Get information about arguments passed into a particular frame.  A
    :term:`named tuple` ``ArgInfo(args, varargs, keywords, locals)`` is
-   returned. *args* is a list of the argument names.  *varargs* and *varkw* are
-   the names of the ``*`` and ``**`` arguments or ``None``.  *locals* is the
+   returned. *args* is a list of the argument names.  *varargs* and *keywords*
+   are the names of the ``*`` and ``**`` arguments or ``None``.  *locals* is the
    locals dictionary of the given frame.
 
 
@@ -563,3 +565,84 @@
    entry in the list represents the caller; the last entry represents where the
    exception was raised.
 
+
+Fetching attributes statically
+------------------------------
+
+Both :func:`getattr` and :func:`hasattr` can trigger code execution when
+fetching or checking for the existence of attributes. Descriptors, like
+properties, will be invoked and :meth:`__getattr__` and :meth:`__getattribute__`
+may be called.
+
+For cases where you want passive introspection, like documentation tools, this
+can be inconvenient. `getattr_static` has the same signature as :func:`getattr`
+but avoids executing code when it fetches attributes.
+
+.. function:: getattr_static(obj, attr, default=None)
+
+   Retrieve attributes without triggering dynamic lookup via the
+   descriptor protocol, `__getattr__` or `__getattribute__`.
+
+   Note: this function may not be able to retrieve all attributes
+   that getattr can fetch (like dynamically created attributes)
+   and may find attributes that getattr can't (like descriptors
+   that raise AttributeError). It can also return descriptors objects
+   instead of instance members.
+
+   .. versionadded:: 3.2
+
+The only known case that can cause `getattr_static` to trigger code execution,
+and cause it to return incorrect results (or even break), is where a class uses
+:data:`~object.__slots__` and provides a `__dict__` member using a property or
+descriptor. If you find other cases please report them so they can be fixed
+or documented.
+
+`getattr_static` does not resolve descriptors, for example slot descriptors or
+getset descriptors on objects implemented in C. The descriptor object
+is returned instead of the underlying attribute.
+
+You can handle these with code like the following. Note that
+for arbitrary getset descriptors invoking these may trigger
+code execution::
+
+   # example code for resolving the builtin descriptor types
+   class _foo:
+       __slots__ = ['foo']
+
+   slot_descriptor = type(_foo.foo)
+   getset_descriptor = type(type(open(__file__)).name)
+   wrapper_descriptor = type(str.__dict__['__add__'])
+   descriptor_types = (slot_descriptor, getset_descriptor, wrapper_descriptor)
+
+   result = getattr_static(some_object, 'foo')
+   if type(result) in descriptor_types:
+       try:
+           result = result.__get__()
+       except AttributeError:
+           # descriptors can raise AttributeError to
+           # indicate there is no underlying value
+           # in which case the descriptor itself will
+           # have to do
+           pass
+
+
+Current State of a Generator
+----------------------------
+
+When implementing coroutine schedulers and for other advanced uses of
+generators, it is useful to determine whether a generator is currently
+executing, is waiting to start or resume or execution, or has already
+terminated. :func:`getgeneratorstate` allows the current state of a
+generator to be determined easily.
+
+.. function:: getgeneratorstate(generator)
+
+   Get current state of a generator-iterator.
+
+   Possible states are:
+    * GEN_CREATED: Waiting to start execution.
+    * GEN_RUNNING: Currently being executed by the interpreter.
+    * GEN_SUSPENDED: Currently suspended at a yield expression.
+    * GEN_CLOSED: Execution has completed.
+
+   .. versionadded:: 3.2

Modified: python/branches/pep-3151/Doc/library/io.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/io.rst	(original)
+++ python/branches/pep-3151/Doc/library/io.rst	Sat Feb 26 08:16:32 2011
@@ -54,12 +54,6 @@
 The text stream API is described in detail in the documentation for the
 :class:`TextIOBase`.
 
-.. note::
-
-   Text I/O over a binary storage (such as a file) is significantly slower than
-   binary I/O over the same storage.  This can become noticeable if you handle
-   huge amounts of text data (for example very large log files).
-
 
 Binary I/O
 ^^^^^^^^^^
@@ -361,9 +355,9 @@
 
    .. method:: readinto(b)
 
-      Read up to len(b) bytes into bytearray *b* and return the number ofbytes
-      read.  If the object is in non-blocking mode and no bytes are available,
-      ``None`` is returned.
+      Read up to len(b) bytes into bytearray *b* and return the number
+      of bytes read.  If the object is in non-blocking mode and no
+      bytes are available, ``None`` is returned.
 
    .. method:: write(b)
 
@@ -506,8 +500,8 @@
 Buffered Streams
 ^^^^^^^^^^^^^^^^
 
-In many situations, buffered I/O streams will provide higher performance
-(bandwidth and latency) than raw I/O streams.  Their API is also more usable.
+Buffered I/O streams provide a higher-level interface to an I/O device
+than raw I/O does.
 
 .. class:: BytesIO([initial_bytes])
 
@@ -784,14 +778,70 @@
       # .getvalue() will now raise an exception.
       output.close()
 
-   .. note::
-
-      :class:`StringIO` uses a native text storage and doesn't suffer from the
-      performance issues of other text streams, such as those based on
-      :class:`TextIOWrapper`.
 
 .. class:: IncrementalNewlineDecoder
 
    A helper codec that decodes newlines for universal newlines mode.  It
    inherits :class:`codecs.IncrementalDecoder`.
 
+
+Performance
+-----------
+
+This section discusses the performance of the provided concrete I/O
+implementations.
+
+Binary I/O
+^^^^^^^^^^
+
+By reading and writing only large chunks of data even when the user asks for a
+single byte, buffered I/O hides any inefficiency in calling and executing the
+operating system's unbuffered I/O routines.  The gain depends on the OS and the
+kind of I/O which is performed.  For example, on some modern OSes such as Linux,
+unbuffered disk I/O can be as fast as buffered I/O.  The bottom line, however,
+is that buffered I/O offers predictable performance regardless of the platform
+and the backing device.  Therefore, it is most always preferable to use buffered
+I/O rather than unbuffered I/O for binary datal
+
+Text I/O
+^^^^^^^^
+
+Text I/O over a binary storage (such as a file) is significantly slower than
+binary I/O over the same storage, because it requires conversions between
+unicode and binary data using a character codec.  This can become noticeable
+handling huge amounts of text data like large log files.  Also,
+:meth:`TextIOWrapper.tell` and :meth:`TextIOWrapper.seek` are both quite slow
+due to the reconstruction algorithm used.
+
+:class:`StringIO`, however, is a native in-memory unicode container and will
+exhibit similar speed to :class:`BytesIO`.
+
+Multi-threading
+^^^^^^^^^^^^^^^
+
+:class:`FileIO` objects are thread-safe to the extent that the operating system
+calls (such as ``read(2)`` under Unix) they wrap are thread-safe too.
+
+Binary buffered objects (instances of :class:`BufferedReader`,
+:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
+protect their internal structures using a lock; it is therefore safe to call
+them from multiple threads at once.
+
+:class:`TextIOWrapper` objects are not thread-safe.
+
+Reentrancy
+^^^^^^^^^^
+
+Binary buffered objects (instances of :class:`BufferedReader`,
+:class:`BufferedWriter`, :class:`BufferedRandom` and :class:`BufferedRWPair`)
+are not reentrant.  While reentrant calls will not happen in normal situations,
+they can arise from doing I/O in a :mod:`signal` handler.  If a thread tries to
+renter a buffered object which it is already accessing, a :exc:`RuntimeError` is
+raised.  Note this doesn't prohibit a different thread from entering the
+buffered object.
+
+The above implicitly extends to text files, since the :func:`open()` function
+will wrap a buffered object inside a :class:`TextIOWrapper`.  This includes
+standard streams and therefore affects the built-in function :func:`print()` as
+well.
+

Modified: python/branches/pep-3151/Doc/library/itertools.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/itertools.rst	(original)
+++ python/branches/pep-3151/Doc/library/itertools.rst	Sat Feb 26 08:16:32 2011
@@ -46,6 +46,7 @@
 ====================    ============================    =================================================   =============================================================
 Iterator                Arguments                       Results                                             Example
 ====================    ============================    =================================================   =============================================================
+:func:`accumulate`      p                               p0, p0+p1, p0+p1+p2, ...                            ``accumulate([1,2,3,4,5]) --> 1 3 6 10 15``
 :func:`chain`           p, q, ...                       p0, p1, ... plast, q0, q1, ...                      ``chain('ABC', 'DEF') --> A B C D E F``
 :func:`compress`        data, selectors                 (d[0] if s[0]), (d[1] if s[1]), ...                 ``compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F``
 :func:`dropwhile`       pred, seq                       seq[n], seq[n+1], starting when pred fails          ``dropwhile(lambda x: x<5, [1,4,6,4,1]) --> 6 4 1``
@@ -67,7 +68,6 @@
 :func:`permutations`                             p[, r]                     r-length tuples, all possible orderings, no repeated elements
 :func:`combinations`                             p, r                       r-length tuples, in sorted order, no repeated elements
 :func:`combinations_with_replacement`            p, r                       r-length tuples, in sorted order, with repeated elements
-|
 ``product('ABCD', repeat=2)``                                               ``AA AB AC AD BA BB BC BD CA CB CC CD DA DB DC DD``
 ``permutations('ABCD', 2)``                                                 ``AB AC AD BA BC BD CA CB CD DA DB DC``
 ``combinations('ABCD', 2)``                                                 ``AB AC AD BC BD CD``
@@ -84,6 +84,22 @@
 streams of infinite length, so they should only be accessed by functions or
 loops that truncate the stream.
 
+.. function:: accumulate(iterable)
+
+    Make an iterator that returns accumulated sums. Elements may be any addable
+    type including :class:`Decimal` or :class:`Fraction`.  Equivalent to::
+
+        def accumulate(iterable):
+            'Return running totals'
+            # accumulate([1,2,3,4,5]) --> 1 3 6 10 15
+            it = iter(iterable)
+            total = next(it)
+            yield total
+            for element in it:
+                total = total + element
+                yield total
+
+    .. versionadded:: 3.2
 
 .. function:: chain(*iterables)
 
@@ -230,7 +246,7 @@
 
       def count(start=0, step=1):
           # count(10) --> 10 11 12 13 14 ...
-          # count(2.5, 0.5) -> 3.5 3.0 4.5 ...
+          # count(2.5, 0.5) -> 2.5 3.0 3.5 ...
           n = start
           while True:
               yield n
@@ -323,7 +339,7 @@
 
    :func:`groupby` is equivalent to::
 
-      class groupby(object):
+      class groupby:
           # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
           # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
           def __init__(self, iterable, key=None):
@@ -561,8 +577,8 @@
 
 .. _itertools-recipes:
 
-Recipes
--------
+Itertools Recipes
+-----------------
 
 This section shows recipes for creating an extended toolset using the existing
 itertools as building blocks.

Modified: python/branches/pep-3151/Doc/library/json.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/json.rst	(original)
+++ python/branches/pep-3151/Doc/library/json.rst	Sat Feb 26 08:16:32 2011
@@ -118,9 +118,8 @@
    file-like object).
 
    If *skipkeys* is ``True`` (default: ``False``), then dict keys that are not
-   of a basic type (:class:`bytes`, :class:`str`, :class:`int`,
-   :class:`float`, :class:`bool`, ``None``) will be skipped instead of raising a
-   :exc:`TypeError`.
+   of a basic type (:class:`str`, :class:`int`, :class:`float`, :class:`bool`,
+   ``None``) will be skipped instead of raising a :exc:`TypeError`.
 
    The :mod:`json` module always produces :class:`str` objects, not
    :class:`bytes` objects. Therefore, ``fp.write()`` must support :class:`str`
@@ -203,15 +202,11 @@
 
 .. function:: loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
 
-   Deserialize *s* (a :class:`bytes` or :class:`str` instance containing a JSON
-   document) to a Python object.
-
-   If *s* is a :class:`bytes` instance and is encoded with an ASCII based encoding
-   other than UTF-8 (e.g. latin-1), then an appropriate *encoding* name must be
-   specified.  Encodings that are not ASCII based (such as UCS-2) are not
-   allowed and should be decoded to :class:`str` first.
+   Deserialize *s* (a :class:`str` instance containing a JSON document) to a
+   Python object.
 
-   The other arguments have the same meaning as in :func:`load`.
+   The other arguments have the same meaning as in :func:`load`, except
+   *encoding* which is ignored and deprecated.
 
 
 Encoders and decoders

Modified: python/branches/pep-3151/Doc/library/keyword.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/keyword.rst	(original)
+++ python/branches/pep-3151/Doc/library/keyword.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: keyword
    :synopsis: Test whether a string is a keyword in Python.
 
+**Source code:** :source:`Lib/keyword.py`
+
+--------------
 
 This module allows a Python program to determine if a string is a keyword.
 
@@ -18,4 +21,3 @@
    Sequence containing all the keywords defined for the interpreter.  If any
    keywords are defined to only be active when particular :mod:`__future__`
    statements are in effect, these will be included as well.
-

Modified: python/branches/pep-3151/Doc/library/linecache.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/linecache.rst	(original)
+++ python/branches/pep-3151/Doc/library/linecache.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: This module provides random access to individual lines from text files.
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
+**Source code:** :source:`Lib/linecache.py`
+
+--------------
 
 The :mod:`linecache` module allows one to get any line from any file, while
 attempting to optimize internally, using a cache, the common case where many

Modified: python/branches/pep-3151/Doc/library/logging.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/logging.rst	(original)
+++ python/branches/pep-3151/Doc/library/logging.rst	Sat Feb 26 08:16:32 2011
@@ -2,7 +2,7 @@
 ==============================================
 
 .. module:: logging
-   :synopsis: Flexible error logging system for applications.
+   :synopsis: Flexible event logging system for applications.
 
 
 .. moduleauthor:: Vinay Sajip <vinay_sajip at red-dove.com>
@@ -11,770 +11,148 @@
 
 .. index:: pair: Errors; logging
 
-This module defines functions and classes which implement a flexible error
-logging system for applications.
+.. sidebar:: Important
 
-Logging is performed by calling methods on instances of the :class:`Logger`
-class (hereafter called :dfn:`loggers`). Each instance has a name, and they are
-conceptually arranged in a namespace hierarchy using dots (periods) as
-separators. For example, a logger named "scan" is the parent of loggers
-"scan.text", "scan.html" and "scan.pdf". Logger names can be anything you want,
-and indicate the area of an application in which a logged message originates.
-
-Logged messages also have levels of importance associated with them. The default
-levels provided are :const:`DEBUG`, :const:`INFO`, :const:`WARNING`,
-:const:`ERROR` and :const:`CRITICAL`. As a convenience, you indicate the
-importance of a logged message by calling an appropriate method of
-:class:`Logger`. The methods are :meth:`debug`, :meth:`info`, :meth:`warning`,
-:meth:`error` and :meth:`critical`, which mirror the default levels. You are not
-constrained to use these levels: you can specify your own and use a more general
-:class:`Logger` method, :meth:`log`, which takes an explicit level argument.
+   This page contains the API reference information. For tutorial
+   information and discussion of more advanced topics, see
 
+   * :ref:`Basic Tutorial <logging-basic-tutorial>`
+   * :ref:`Advanced Tutorial <logging-advanced-tutorial>`
+   * :ref:`Logging Cookbook <logging-cookbook>`
 
-Logging tutorial
-----------------
+
+This module defines functions and classes which implement a flexible event
+logging system for applications and libraries.
 
 The key benefit of having the logging API provided by a standard library module
 is that all Python modules can participate in logging, so your application log
-can include messages from third-party modules.
-
-It is, of course, possible to log messages with different verbosity levels or to
-different destinations.  Support for writing log messages to files, HTTP
-GET/POST locations, email via SMTP, generic sockets, or OS-specific logging
-mechanisms are all supported by the standard module.  You can also create your
-own log destination class if you have special requirements not met by any of the
-built-in classes.
-
-Simple examples
-^^^^^^^^^^^^^^^
-
-.. sectionauthor:: Doug Hellmann
-.. (see <http://blog.doughellmann.com/2007/05/pymotw-logging.html>)
-
-Most applications are probably going to want to log to a file, so let's start
-with that case. Using the :func:`basicConfig` function, we can set up the
-default handler so that debug messages are written to a file (in the example,
-we assume that you have the appropriate permissions to create a file called
-*example.log* in the current directory)::
-
-   import logging
-   LOG_FILENAME = 'example.log'
-   logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)
-
-   logging.debug('This message should go to the log file')
-
-And now if we open the file and look at what we have, we should find the log
-message::
-
-   DEBUG:root:This message should go to the log file
-
-If you run the script repeatedly, the additional log messages are appended to
-the file.  To create a new file each time, you can pass a *filemode* argument to
-:func:`basicConfig` with a value of ``'w'``.  Rather than managing the file size
-yourself, though, it is simpler to use a :class:`RotatingFileHandler`::
-
-   import glob
-   import logging
-   import logging.handlers
-
-   LOG_FILENAME = 'logging_rotatingfile_example.out'
-
-   # Set up a specific logger with our desired output level
-   my_logger = logging.getLogger('MyLogger')
-   my_logger.setLevel(logging.DEBUG)
-
-   # Add the log message handler to the logger
-   handler = logging.handlers.RotatingFileHandler(
-                 LOG_FILENAME, maxBytes=20, backupCount=5)
-
-   my_logger.addHandler(handler)
-
-   # Log some messages
-   for i in range(20):
-       my_logger.debug('i = %d' % i)
-
-   # See what files are created
-   logfiles = glob.glob('%s*' % LOG_FILENAME)
-
-   for filename in logfiles:
-       print(filename)
-
-The result should be 6 separate files, each with part of the log history for the
-application::
-
-   logging_rotatingfile_example.out
-   logging_rotatingfile_example.out.1
-   logging_rotatingfile_example.out.2
-   logging_rotatingfile_example.out.3
-   logging_rotatingfile_example.out.4
-   logging_rotatingfile_example.out.5
-
-The most current file is always :file:`logging_rotatingfile_example.out`,
-and each time it reaches the size limit it is renamed with the suffix
-``.1``. Each of the existing backup files is renamed to increment the suffix
-(``.1`` becomes ``.2``, etc.)  and the ``.6`` file is erased.
-
-Obviously this example sets the log length much much too small as an extreme
-example.  You would want to set *maxBytes* to an appropriate value.
-
-Another useful feature of the logging API is the ability to produce different
-messages at different log levels.  This allows you to instrument your code with
-debug messages, for example, but turning the log level down so that those debug
-messages are not written for your production system.  The default levels are
-``NOTSET``, ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and ``CRITICAL``.
-
-The logger, handler, and log message call each specify a level.  The log message
-is only emitted if the handler and logger are configured to emit messages of
-that level or lower.  For example, if a message is ``CRITICAL``, and the logger
-is set to ``ERROR``, the message is emitted.  If a message is a ``WARNING``, and
-the logger is set to produce only ``ERROR``\s, the message is not emitted::
-
-   import logging
-   import sys
-
-   LEVELS = {'debug': logging.DEBUG,
-             'info': logging.INFO,
-             'warning': logging.WARNING,
-             'error': logging.ERROR,
-             'critical': logging.CRITICAL}
-
-   if len(sys.argv) > 1:
-       level_name = sys.argv[1]
-       level = LEVELS.get(level_name, logging.NOTSET)
-       logging.basicConfig(level=level)
-
-   logging.debug('This is a debug message')
-   logging.info('This is an info message')
-   logging.warning('This is a warning message')
-   logging.error('This is an error message')
-   logging.critical('This is a critical error message')
-
-Run the script with an argument like 'debug' or 'warning' to see which messages
-show up at different levels::
-
-   $ python logging_level_example.py debug
-   DEBUG:root:This is a debug message
-   INFO:root:This is an info message
-   WARNING:root:This is a warning message
-   ERROR:root:This is an error message
-   CRITICAL:root:This is a critical error message
-
-   $ python logging_level_example.py info
-   INFO:root:This is an info message
-   WARNING:root:This is a warning message
-   ERROR:root:This is an error message
-   CRITICAL:root:This is a critical error message
-
-You will notice that these log messages all have ``root`` embedded in them.  The
-logging module supports a hierarchy of loggers with different names.  An easy
-way to tell where a specific log message comes from is to use a separate logger
-object for each of your modules.  Each new logger "inherits" the configuration
-of its parent, and log messages sent to a logger include the name of that
-logger.  Optionally, each logger can be configured differently, so that messages
-from different modules are handled in different ways.  Let's look at a simple
-example of how to log from different modules so it is easy to trace the source
-of the message::
-
-   import logging
-
-   logging.basicConfig(level=logging.WARNING)
-
-   logger1 = logging.getLogger('package1.module1')
-   logger2 = logging.getLogger('package2.module2')
-
-   logger1.warning('This message comes from one module')
-   logger2.warning('And this message comes from another module')
-
-And the output::
-
-   $ python logging_modules_example.py
-   WARNING:package1.module1:This message comes from one module
-   WARNING:package2.module2:And this message comes from another module
-
-There are many more options for configuring logging, including different log
-message formatting options, having messages delivered to multiple destinations,
-and changing the configuration of a long-running application on the fly using a
-socket interface.  All of these options are covered in depth in the library
-module documentation.
-
-Loggers
-^^^^^^^
-
-The logging library takes a modular approach and offers the several categories
-of components: loggers, handlers, filters, and formatters.  Loggers expose the
-interface that application code directly uses.  Handlers send the log records to
-the appropriate destination. Filters provide a finer grained facility for
-determining which log records to send on to a handler.  Formatters specify the
-layout of the resultant log record.
-
-:class:`Logger` objects have a threefold job.  First, they expose several
-methods to application code so that applications can log messages at runtime.
-Second, logger objects determine which log messages to act upon based upon
-severity (the default filtering facility) or filter objects.  Third, logger
-objects pass along relevant log messages to all interested log handlers.
-
-The most widely used methods on logger objects fall into two categories:
-configuration and message sending.
-
-* :meth:`Logger.setLevel` specifies the lowest-severity log message a logger
-  will handle, where debug is the lowest built-in severity level and critical is
-  the highest built-in severity.  For example, if the severity level is info,
-  the logger will handle only info, warning, error, and critical messages and
-  will ignore debug messages.
-
-* :meth:`Logger.addFilter` and :meth:`Logger.removeFilter` add and remove filter
-  objects from the logger object.  This tutorial does not address filters.
-
-With the logger object configured, the following methods create log messages:
-
-* :meth:`Logger.debug`, :meth:`Logger.info`, :meth:`Logger.warning`,
-  :meth:`Logger.error`, and :meth:`Logger.critical` all create log records with
-  a message and a level that corresponds to their respective method names. The
-  message is actually a format string, which may contain the standard string
-  substitution syntax of :const:`%s`, :const:`%d`, :const:`%f`, and so on.  The
-  rest of their arguments is a list of objects that correspond with the
-  substitution fields in the message.  With regard to :const:`**kwargs`, the
-  logging methods care only about a keyword of :const:`exc_info` and use it to
-  determine whether to log exception information.
-
-* :meth:`Logger.exception` creates a log message similar to
-  :meth:`Logger.error`.  The difference is that :meth:`Logger.exception` dumps a
-  stack trace along with it.  Call this method only from an exception handler.
-
-* :meth:`Logger.log` takes a log level as an explicit argument.  This is a
-  little more verbose for logging messages than using the log level convenience
-  methods listed above, but this is how to log at custom log levels.
-
-:func:`getLogger` returns a reference to a logger instance with the specified
-name if it is provided, or ``root`` if not.  The names are period-separated
-hierarchical structures.  Multiple calls to :func:`getLogger` with the same name
-will return a reference to the same logger object.  Loggers that are further
-down in the hierarchical list are children of loggers higher up in the list.
-For example, given a logger with a name of ``foo``, loggers with names of
-``foo.bar``, ``foo.bar.baz``, and ``foo.bam`` are all descendants of ``foo``.
-Child loggers propagate messages up to the handlers associated with their
-ancestor loggers.  Because of this, it is unnecessary to define and configure
-handlers for all the loggers an application uses. It is sufficient to
-configure handlers for a top-level logger and create child loggers as needed.
-
-
-Handlers
-^^^^^^^^
-
-:class:`Handler` objects are responsible for dispatching the appropriate log
-messages (based on the log messages' severity) to the handler's specified
-destination.  Logger objects can add zero or more handler objects to themselves
-with an :func:`addHandler` method.  As an example scenario, an application may
-want to send all log messages to a log file, all log messages of error or higher
-to stdout, and all messages of critical to an email address.  This scenario
-requires three individual handlers where each handler is responsible for sending
-messages of a specific severity to a specific location.
-
-The standard library includes quite a few handler types; this tutorial uses only
-:class:`StreamHandler` and :class:`FileHandler` in its examples.
-
-There are very few methods in a handler for application developers to concern
-themselves with.  The only handler methods that seem relevant for application
-developers who are using the built-in handler objects (that is, not creating
-custom handlers) are the following configuration methods:
-
-* The :meth:`Handler.setLevel` method, just as in logger objects, specifies the
-  lowest severity that will be dispatched to the appropriate destination.  Why
-  are there two :func:`setLevel` methods?  The level set in the logger
-  determines which severity of messages it will pass to its handlers.  The level
-  set in each handler determines which messages that handler will send on.
-
-* :func:`setFormatter` selects a Formatter object for this handler to use.
-
-* :func:`addFilter` and :func:`removeFilter` respectively configure and
-  deconfigure filter objects on handlers.
-
-Application code should not directly instantiate and use instances of
-:class:`Handler`.  Instead, the :class:`Handler` class is a base class that
-defines the interface that all handlers should have and establishes some
-default behavior that child classes can use (or override).
-
-
-Formatters
-^^^^^^^^^^
-
-Formatter objects configure the final order, structure, and contents of the log
-message.  Unlike the base :class:`logging.Handler` class, application code may
-instantiate formatter classes, although you could likely subclass the formatter
-if your application needs special behavior.  The constructor takes three
-optional arguments -- a message format string, a date format string and a style
-indicator.
-
-.. method:: logging.Formatter.__init__(fmt=None, datefmt=None, style='%')
-
-If there is no message format string, the default is to use the
-raw message.  If there is no date format string, the default date format is::
-
-    %Y-%m-%d %H:%M:%S
-
-with the milliseconds tacked on at the end. The ``style`` is one of `%`, '{'
-or '$'. If one of these is not specified, then '%' will be used.
-
-If the ``style`` is '%', the message format string uses
-``%(<dictionary key>)s`` styled string substitution; the possible keys are
-documented in :ref:`formatter-objects`. If the style is '{', the message format
-string is assumed to be compatible with :meth:`str.format` (using keyword
-arguments), while if the style is '$' then the message format string should
-conform to what is expected by :meth:`string.Template.substitute`.
-
-.. versionchanged:: 3.2
-   Added the ``style`` parameter.
+can include your own messages integrated with messages from third-party
+modules.
 
-The following message format string will log the time in a human-readable
-format, the severity of the message, and the contents of the message, in that
-order::
-
-    "%(asctime)s - %(levelname)s - %(message)s"
-
-Formatters use a user-configurable function to convert the creation time of a
-record to a tuple. By default, :func:`time.localtime` is used; to change this
-for a particular formatter instance, set the ``converter`` attribute of the
-instance to a function with the same signature as :func:`time.localtime` or
-:func:`time.gmtime`. To change it for all formatters, for example if you want
-all logging times to be shown in GMT, set the ``converter`` attribute in the
-Formatter class (to ``time.gmtime`` for GMT display).
-
-
-Configuring Logging
-^^^^^^^^^^^^^^^^^^^
-
-Programmers can configure logging in three ways:
-
-1. Creating loggers, handlers, and formatters explicitly using Python
-   code that calls the configuration methods listed above.
-2. Creating a logging config file and reading it using the :func:`fileConfig`
-   function.
-3. Creating a dictionary of configuration information and passing it
-   to the :func:`dictConfig` function.
-
-The following example configures a very simple logger, a console
-handler, and a simple formatter using Python code::
-
-    import logging
-
-    # create logger
-    logger = logging.getLogger("simple_example")
-    logger.setLevel(logging.DEBUG)
-
-    # create console handler and set level to debug
-    ch = logging.StreamHandler()
-    ch.setLevel(logging.DEBUG)
-
-    # create formatter
-    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
-
-    # add formatter to ch
-    ch.setFormatter(formatter)
-
-    # add ch to logger
-    logger.addHandler(ch)
-
-    # "application" code
-    logger.debug("debug message")
-    logger.info("info message")
-    logger.warn("warn message")
-    logger.error("error message")
-    logger.critical("critical message")
-
-Running this module from the command line produces the following output::
-
-    $ python simple_logging_module.py
-    2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
-    2005-03-19 15:10:26,620 - simple_example - INFO - info message
-    2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
-    2005-03-19 15:10:26,697 - simple_example - ERROR - error message
-    2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
-
-The following Python module creates a logger, handler, and formatter nearly
-identical to those in the example listed above, with the only difference being
-the names of the objects::
-
-    import logging
-    import logging.config
-
-    logging.config.fileConfig("logging.conf")
-
-    # create logger
-    logger = logging.getLogger("simpleExample")
-
-    # "application" code
-    logger.debug("debug message")
-    logger.info("info message")
-    logger.warn("warn message")
-    logger.error("error message")
-    logger.critical("critical message")
-
-Here is the logging.conf file::
-
-    [loggers]
-    keys=root,simpleExample
-
-    [handlers]
-    keys=consoleHandler
-
-    [formatters]
-    keys=simpleFormatter
-
-    [logger_root]
-    level=DEBUG
-    handlers=consoleHandler
-
-    [logger_simpleExample]
-    level=DEBUG
-    handlers=consoleHandler
-    qualname=simpleExample
-    propagate=0
-
-    [handler_consoleHandler]
-    class=StreamHandler
-    level=DEBUG
-    formatter=simpleFormatter
-    args=(sys.stdout,)
-
-    [formatter_simpleFormatter]
-    format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
-    datefmt=
-
-The output is nearly identical to that of the non-config-file-based example::
-
-    $ python simple_logging_config.py
-    2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
-    2005-03-19 15:38:55,979 - simpleExample - INFO - info message
-    2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
-    2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
-    2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
-
-You can see that the config file approach has a few advantages over the Python
-code approach, mainly separation of configuration and code and the ability of
-noncoders to easily modify the logging properties.
-
-Note that the class names referenced in config files need to be either relative
-to the logging module, or absolute values which can be resolved using normal
-import mechanisms. Thus, you could use either
-:class:`handlers.WatchedFileHandler` (relative to the logging module) or
-``mypackage.mymodule.MyHandler`` (for a class defined in package ``mypackage``
-and module ``mymodule``, where ``mypackage`` is available on the Python import
-path).
-
-In Python 3.2, a new means of configuring logging has been introduced, using
-dictionaries to hold configuration information. This provides a superset of the
-functionality of the config-file-based approach outlined above, and is the
-recommended configuration method for new applications and deployments. Because
-a Python dictionary is used to hold configuration information, and since you
-can populate that dictionary using different means, you have more options for
-configuration. For example, you can use a configuration file in JSON format,
-or, if you have access to YAML processing functionality, a file in YAML
-format, to populate the configuration dictionary. Or, of course, you can
-construct the dictionary in Python code, receive it in pickled form over a
-socket, or use whatever approach makes sense for your application.
-
-Here's an example of the same configuration as above, in YAML format for
-the new dictionary-based approach::
-
-    version: 1
-    formatters:
-      simple:
-        format: format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
-    handlers:
-      console:
-        class: logging.StreamHandler
-        level: DEBUG
-        formatter: simple
-        stream: ext://sys.stdout
-    loggers:
-      simpleExample:
-        level: DEBUG
-        handlers: [console]
-        propagate: no
-    root:
-        level: DEBUG
-        handlers: [console]
-
-For more information about logging using a dictionary, see
-:ref:`logging-config-api`.
-
-.. _library-config:
-
-Configuring Logging for a Library
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-When developing a library which uses logging, some consideration needs to be
-given to its configuration. If the using application does not use logging, and
-library code makes logging calls, then a one-off message "No handlers could be
-found for logger X.Y.Z" is printed to the console. This message is intended
-to catch mistakes in logging configuration, but will confuse an application
-developer who is not aware of logging by the library.
-
-In addition to documenting how a library uses logging, a good way to configure
-library logging so that it does not cause a spurious message is to add a
-handler which does nothing. This avoids the message being printed, since a
-handler will be found: it just doesn't produce any output. If the library user
-configures logging for application use, presumably that configuration will add
-some handlers, and if levels are suitably configured then logging calls made
-in library code will send output to those handlers, as normal.
-
-A do-nothing handler can be simply defined as follows::
-
-    import logging
-
-    class NullHandler(logging.Handler):
-        def emit(self, record):
-            pass
-
-An instance of this handler should be added to the top-level logger of the
-logging namespace used by the library. If all logging by a library *foo* is
-done using loggers with names matching "foo.x.y", then the code::
-
-    import logging
-
-    h = NullHandler()
-    logging.getLogger("foo").addHandler(h)
-
-should have the desired effect. If an organisation produces a number of
-libraries, then the logger name specified can be "orgname.foo" rather than
-just "foo".
-
-**PLEASE NOTE:** It is strongly advised that you *do not add any handlers other
-than* :class:`NullHandler` *to your library's loggers*. This is because the
-configuration of handlers is the prerogative of the application developer who
-uses your library. The application developer knows their target audience and
-what handlers are most appropriate for their application: if you add handlers
-"under the hood", you might well interfere with their ability to carry out
-unit tests and deliver logs which suit their requirements.
-
-.. versionadded:: 3.1
-
-The :class:`NullHandler` class was not present in previous versions, but is
-now included, so that it need not be defined in library code.
+The module provides a lot of functionality and flexibility.  If you are
+unfamiliar with logging, the best way to get to grips with it is to see the
+tutorials (see the links on the right).
+
+The basic classes defined by the module, together with their functions, are
+listed below.
+
+* Loggers expose the interface that application code directly uses.
+* Handlers send the log records (created by loggers) to the appropriate
+  destination.
+* Filters provide a finer grained facility for determining which log records
+  to output.
+* Formatters specify the layout of log records in the final output.
 
 
+.. _logger:
 
-Logging Levels
+Logger Objects
 --------------
 
-The numeric values of logging levels are given in the following table. These are
-primarily of interest if you want to define your own levels, and need them to
-have specific values relative to the predefined levels. If you define a level
-with the same numeric value, it overwrites the predefined value; the predefined
-name is lost.
-
-+--------------+---------------+
-| Level        | Numeric value |
-+==============+===============+
-| ``CRITICAL`` | 50            |
-+--------------+---------------+
-| ``ERROR``    | 40            |
-+--------------+---------------+
-| ``WARNING``  | 30            |
-+--------------+---------------+
-| ``INFO``     | 20            |
-+--------------+---------------+
-| ``DEBUG``    | 10            |
-+--------------+---------------+
-| ``NOTSET``   | 0             |
-+--------------+---------------+
-
-Levels can also be associated with loggers, being set either by the developer or
-through loading a saved logging configuration. When a logging method is called
-on a logger, the logger compares its own level with the level associated with
-the method call. If the logger's level is higher than the method call's, no
-logging message is actually generated. This is the basic mechanism controlling
-the verbosity of logging output.
-
-Logging messages are encoded as instances of the :class:`LogRecord` class. When
-a logger decides to actually log an event, a :class:`LogRecord` instance is
-created from the logging message.
-
-Logging messages are subjected to a dispatch mechanism through the use of
-:dfn:`handlers`, which are instances of subclasses of the :class:`Handler`
-class. Handlers are responsible for ensuring that a logged message (in the form
-of a :class:`LogRecord`) ends up in a particular location (or set of locations)
-which is useful for the target audience for that message (such as end users,
-support desk staff, system administrators, developers). Handlers are passed
-:class:`LogRecord` instances intended for particular destinations. Each logger
-can have zero, one or more handlers associated with it (via the
-:meth:`addHandler` method of :class:`Logger`). In addition to any handlers
-directly associated with a logger, *all handlers associated with all ancestors
-of the logger* are called to dispatch the message (unless the *propagate* flag
-for a logger is set to a false value, at which point the passing to ancestor
-handlers stops).
-
-Just as for loggers, handlers can have levels associated with them. A handler's
-level acts as a filter in the same way as a logger's level does. If a handler
-decides to actually dispatch an event, the :meth:`emit` method is used to send
-the message to its destination. Most user-defined subclasses of :class:`Handler`
-will need to override this :meth:`emit`.
-
-.. _custom-levels:
-
-Custom Levels
-^^^^^^^^^^^^^
-
-Defining your own levels is possible, but should not be necessary, as the
-existing levels have been chosen on the basis of practical experience.
-However, if you are convinced that you need custom levels, great care should
-be exercised when doing this, and it is possibly *a very bad idea to define
-custom levels if you are developing a library*. That's because if multiple
-library authors all define their own custom levels, there is a chance that
-the logging output from such multiple libraries used together will be
-difficult for the using developer to control and/or interpret, because a
-given numeric value might mean different things for different libraries.
-
-
-Useful Handlers
----------------
-
-In addition to the base :class:`Handler` class, many useful subclasses are
-provided:
-
-#. :class:`StreamHandler` instances send messages to streams (file-like
-   objects).
-
-#. :class:`FileHandler` instances send messages to disk files.
-
-.. module:: logging.handlers
-
-#. :class:`BaseRotatingHandler` is the base class for handlers that
-   rotate log files at a certain point. It is not meant to be  instantiated
-   directly. Instead, use :class:`RotatingFileHandler` or
-   :class:`TimedRotatingFileHandler`.
-
-#. :class:`RotatingFileHandler` instances send messages to disk
-   files, with support for maximum log file sizes and log file rotation.
-
-#. :class:`TimedRotatingFileHandler` instances send messages to
-   disk files, rotating the log file at certain timed intervals.
-
-#. :class:`SocketHandler` instances send messages to TCP/IP
-   sockets.
-
-#. :class:`DatagramHandler` instances send messages to UDP
-   sockets.
+Loggers have the following attributes and methods. Note that Loggers are never
+instantiated directly, but always through the module-level function
+``logging.getLogger(name)``.
 
-#. :class:`SMTPHandler` instances send messages to a designated
-   email address.
+.. class:: Logger
 
-#. :class:`SysLogHandler` instances send messages to a Unix
-   syslog daemon, possibly on a remote machine.
+.. attribute:: Logger.propagate
 
-#. :class:`NTEventLogHandler` instances send messages to a
-   Windows NT/2000/XP event log.
+   If this evaluates to false, logging messages are not passed by this logger or by
+   its child loggers to the handlers of higher level (ancestor) loggers. The
+   constructor sets this attribute to 1.
 
-#. :class:`MemoryHandler` instances send messages to a buffer
-   in memory, which is flushed whenever specific criteria are met.
 
-#. :class:`HTTPHandler` instances send messages to an HTTP
-   server using either ``GET`` or ``POST`` semantics.
+.. method:: Logger.setLevel(lvl)
 
-#. :class:`WatchedFileHandler` instances watch the file they are
-   logging to. If the file changes, it is closed and reopened using the file
-   name. This handler is only useful on Unix-like systems; Windows does not
-   support the underlying mechanism used.
+   Sets the threshold for this logger to *lvl*. Logging messages which are less
+   severe than *lvl* will be ignored. When a logger is created, the level is set to
+   :const:`NOTSET` (which causes all messages to be processed when the logger is
+   the root logger, or delegation to the parent when the logger is a non-root
+   logger). Note that the root logger is created with level :const:`WARNING`.
 
-#. :class:`QueueHandler` instances send messages to a queue, such as
-   those implemented in the :mod:`queue` or :mod:`multiprocessing` modules.
+   The term 'delegation to the parent' means that if a logger has a level of
+   NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
+   a level other than NOTSET is found, or the root is reached.
 
-.. currentmodule:: logging
+   If an ancestor is found with a level other than NOTSET, then that ancestor's
+   level is treated as the effective level of the logger where the ancestor search
+   began, and is used to determine how a logging event is handled.
 
-#. :class:`NullHandler` instances do nothing with error messages. They are used
-   by library developers who want to use logging, but want to avoid the "No
-   handlers could be found for logger XXX" message which can be displayed if
-   the library user has not configured logging. See :ref:`library-config` for
-   more information.
-
-.. versionadded:: 3.1
-
-The :class:`NullHandler` class was not present in previous versions.
-
-.. versionadded:: 3.2
-
-The :class:`QueueHandler` class was not present in previous versions.
-
-The :class:`NullHandler`, :class:`StreamHandler` and :class:`FileHandler`
-classes are defined in the core logging package. The other handlers are
-defined in a sub- module, :mod:`logging.handlers`. (There is also another
-sub-module, :mod:`logging.config`, for configuration functionality.)
-
-Logged messages are formatted for presentation through instances of the
-:class:`Formatter` class. They are initialized with a format string suitable for
-use with the % operator and a dictionary.
-
-For formatting multiple messages in a batch, instances of
-:class:`BufferingFormatter` can be used. In addition to the format string (which
-is applied to each message in the batch), there is provision for header and
-trailer format strings.
-
-When filtering based on logger level and/or handler level is not enough,
-instances of :class:`Filter` can be added to both :class:`Logger` and
-:class:`Handler` instances (through their :meth:`addFilter` method). Before
-deciding to process a message further, both loggers and handlers consult all
-their filters for permission. If any filter returns a false value, the message
-is not processed further.
-
-The basic :class:`Filter` functionality allows filtering by specific logger
-name. If this feature is used, messages sent to the named logger and its
-children are allowed through the filter, and all others dropped.
+   If the root is reached, and it has a level of NOTSET, then all messages will be
+   processed. Otherwise, the root's level will be used as the effective level.
 
-Module-Level Functions
-----------------------
 
-In addition to the classes described above, there are a number of module- level
-functions.
+.. method:: Logger.isEnabledFor(lvl)
 
+   Indicates if a message of severity *lvl* would be processed by this logger.
+   This method checks first the module-level level set by
+   ``logging.disable(lvl)`` and then the logger's effective level as determined
+   by :meth:`getEffectiveLevel`.
 
-.. function:: getLogger(name=None)
 
-   Return a logger with the specified name or, if name is ``None``, return a
-   logger which is the root logger of the hierarchy. If specified, the name is
-   typically a dot-separated hierarchical name like *"a"*, *"a.b"* or *"a.b.c.d"*.
-   Choice of these names is entirely up to the developer who is using logging.
+.. method:: Logger.getEffectiveLevel()
 
-   All calls to this function with a given name return the same logger instance.
-   This means that logger instances never need to be passed between different parts
-   of an application.
+   Indicates the effective level for this logger. If a value other than
+   :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
+   the hierarchy is traversed towards the root until a value other than
+   :const:`NOTSET` is found, and that value is returned.
 
 
-.. function:: getLoggerClass()
+.. method:: Logger.getChild(suffix)
 
-   Return either the standard :class:`Logger` class, or the last class passed to
-   :func:`setLoggerClass`. This function may be called from within a new class
-   definition, to ensure that installing a customised :class:`Logger` class will
-   not undo customisations already applied by other code. For example::
+   Returns a logger which is a descendant to this logger, as determined by the suffix.
+   Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
+   logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
+   convenience method, useful when the parent logger is named using e.g. ``__name__``
+   rather than a literal string.
 
-      class MyLogger(logging.getLoggerClass()):
-          # ... override behaviour here
+   .. versionadded:: 3.2
 
 
-.. function:: debug(msg, *args, **kwargs)
+.. method:: Logger.debug(msg, *args, **kwargs)
 
-   Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
+   Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
    message format string, and the *args* are the arguments which are merged into
    *msg* using the string formatting operator. (Note that this means that you can
    use keywords in the format string, together with a single dictionary argument.)
 
-   There are two keyword arguments in *kwargs* which are inspected: *exc_info*
+   There are three keyword arguments in *kwargs* which are inspected: *exc_info*
    which, if it does not evaluate as false, causes exception information to be
    added to the logging message. If an exception tuple (in the format returned by
    :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
    is called to get the exception information.
 
-   The other optional keyword argument is *extra* which can be used to pass a
+   The second optional keyword argument is *stack_info*, which defaults to
+   False. If specified as True, stack information is added to the logging
+   message, including the actual logging call. Note that this is not the same
+   stack information as that displayed through specifying *exc_info*: The
+   former is stack frames from the bottom of the stack up to the logging call
+   in the current thread, whereas the latter is information about stack frames
+   which have been unwound, following an exception, while searching for
+   exception handlers.
+
+   You can specify *stack_info* independently of *exc_info*, e.g. to just show
+   how you got to a certain point in your code, even when no exceptions were
+   raised. The stack frames are printed following a header line which says::
+
+       Stack (most recent call last):
+
+   This mimics the `Traceback (most recent call last):` which is used when
+   displaying exception frames.
+
+   The third keyword argument is *extra* which can be used to pass a
    dictionary which is used to populate the __dict__ of the LogRecord created for
    the logging event with user-defined attributes. These custom attributes can then
    be used as you like. For example, they could be incorporated into logged
    messages. For example::
 
-      FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
+      FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
       logging.basicConfig(format=FORMAT)
-      d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
-      logging.warning("Protocol problem: %s", "connection reset", extra=d)
+      d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
+      logger = logging.getLogger('tcpserver')
+      logger.warning('Protocol problem: %s', 'connection reset', extra=d)
 
-   would print something like::
+   would print something like  ::
 
       2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
 
@@ -796,1190 +174,104 @@
    above example). In such circumstances, it is likely that specialized
    :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
 
+   .. versionadded:: 3.2
+      The *stack_info* parameter was added.
 
-.. function:: info(msg, *args, **kwargs)
 
-   Logs a message with level :const:`INFO` on the root logger. The arguments are
-   interpreted as for :func:`debug`.
+.. method:: Logger.info(msg, *args, **kwargs)
 
+   Logs a message with level :const:`INFO` on this logger. The arguments are
+   interpreted as for :meth:`debug`.
 
-.. function:: warning(msg, *args, **kwargs)
 
-   Logs a message with level :const:`WARNING` on the root logger. The arguments are
-   interpreted as for :func:`debug`.
+.. method:: Logger.warning(msg, *args, **kwargs)
 
+   Logs a message with level :const:`WARNING` on this logger. The arguments are
+   interpreted as for :meth:`debug`.
 
-.. function:: error(msg, *args, **kwargs)
 
-   Logs a message with level :const:`ERROR` on the root logger. The arguments are
-   interpreted as for :func:`debug`.
+.. method:: Logger.error(msg, *args, **kwargs)
 
+   Logs a message with level :const:`ERROR` on this logger. The arguments are
+   interpreted as for :meth:`debug`.
 
-.. function:: critical(msg, *args, **kwargs)
 
-   Logs a message with level :const:`CRITICAL` on the root logger. The arguments
-   are interpreted as for :func:`debug`.
+.. method:: Logger.critical(msg, *args, **kwargs)
 
+   Logs a message with level :const:`CRITICAL` on this logger. The arguments are
+   interpreted as for :meth:`debug`.
 
-.. function:: exception(msg, *args)
 
-   Logs a message with level :const:`ERROR` on the root logger. The arguments are
-   interpreted as for :func:`debug`. Exception info is added to the logging
-   message. This function should only be called from an exception handler.
+.. method:: Logger.log(lvl, msg, *args, **kwargs)
 
-.. function:: log(level, msg, *args, **kwargs)
+   Logs a message with integer level *lvl* on this logger. The other arguments are
+   interpreted as for :meth:`debug`.
 
-   Logs a message with level *level* on the root logger. The other arguments are
-   interpreted as for :func:`debug`.
 
-   PLEASE NOTE: The above module-level functions which delegate to the root
-   logger should *not* be used in threads, in versions of Python earlier than
-   2.7.1 and 3.2, unless at least one handler has been added to the root
-   logger *before* the threads are started. These convenience functions call
-   :func:`basicConfig` to ensure that at least one handler is available; in
-   earlier versions of Python, this can (under rare circumstances) lead to
-   handlers being added multiple times to the root logger, which can in turn
-   lead to multiple messages for the same event.
+.. method:: Logger.exception(msg, *args)
 
-.. function:: disable(lvl)
+   Logs a message with level :const:`ERROR` on this logger. The arguments are
+   interpreted as for :meth:`debug`. Exception info is added to the logging
+   message. This method should only be called from an exception handler.
 
-   Provides an overriding level *lvl* for all loggers which takes precedence over
-   the logger's own level. When the need arises to temporarily throttle logging
-   output down across the whole application, this function can be useful. Its
-   effect is to disable all logging calls of severity *lvl* and below, so that
-   if you call it with a value of INFO, then all INFO and DEBUG events would be
-   discarded, whereas those of severity WARNING and above would be processed
-   according to the logger's effective level.
 
+.. method:: Logger.addFilter(filt)
 
-.. function:: addLevelName(lvl, levelName)
+   Adds the specified filter *filt* to this logger.
 
-   Associates level *lvl* with text *levelName* in an internal dictionary, which is
-   used to map numeric levels to a textual representation, for example when a
-   :class:`Formatter` formats a message. This function can also be used to define
-   your own levels. The only constraints are that all levels used must be
-   registered using this function, levels should be positive integers and they
-   should increase in increasing order of severity.
 
-   NOTE: If you are thinking of defining your own levels, please see the section
-   on :ref:`custom-levels`.
+.. method:: Logger.removeFilter(filt)
 
-.. function:: getLevelName(lvl)
+   Removes the specified filter *filt* from this logger.
 
-   Returns the textual representation of logging level *lvl*. If the level is one
-   of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
-   :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
-   have associated levels with names using :func:`addLevelName` then the name you
-   have associated with *lvl* is returned. If a numeric value corresponding to one
-   of the defined levels is passed in, the corresponding string representation is
-   returned. Otherwise, the string "Level %s" % lvl is returned.
 
+.. method:: Logger.filter(record)
 
-.. function:: makeLogRecord(attrdict)
+   Applies this logger's filters to the record and returns a true value if the
+   record is to be processed.
 
-   Creates and returns a new :class:`LogRecord` instance whose attributes are
-   defined by *attrdict*. This function is useful for taking a pickled
-   :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
-   it as a :class:`LogRecord` instance at the receiving end.
 
+.. method:: Logger.addHandler(hdlr)
 
-.. function:: basicConfig(**kwargs)
+   Adds the specified handler *hdlr* to this logger.
 
-   Does basic configuration for the logging system by creating a
-   :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
-   root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
-   :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
-   if no handlers are defined for the root logger.
 
-   This function does nothing if the root logger already has handlers
-   configured for it.
+.. method:: Logger.removeHandler(hdlr)
 
-   PLEASE NOTE: This function should be called from the main thread
-   before other threads are started. In versions of Python prior to
-   2.7.1 and 3.2, if this function is called from multiple threads,
-   it is possible (in rare circumstances) that a handler will be added
-   to the root logger more than once, leading to unexpected results
-   such as messages being duplicated in the log.
+   Removes the specified handler *hdlr* from this logger.
 
-   The following keyword arguments are supported.
 
-   +--------------+---------------------------------------------+
-   | Format       | Description                                 |
-   +==============+=============================================+
-   | ``filename`` | Specifies that a FileHandler be created,    |
-   |              | using the specified filename, rather than a |
-   |              | StreamHandler.                              |
-   +--------------+---------------------------------------------+
-   | ``filemode`` | Specifies the mode to open the file, if     |
-   |              | filename is specified (if filemode is       |
-   |              | unspecified, it defaults to 'a').           |
-   +--------------+---------------------------------------------+
-   | ``format``   | Use the specified format string for the     |
-   |              | handler.                                    |
-   +--------------+---------------------------------------------+
-   | ``datefmt``  | Use the specified date/time format.         |
-   +--------------+---------------------------------------------+
-   | ``style``    | If ``format`` is specified, use this style  |
-   |              | for the format string. One of '%', '{' or   |
-   |              | '$' for %-formatting, :meth:`str.format` or |
-   |              | :class:`string.Template` respectively, and  |
-   |              | defaulting to '%' if not specified.         |
-   +--------------+---------------------------------------------+
-   | ``level``    | Set the root logger level to the specified  |
-   |              | level.                                      |
-   +--------------+---------------------------------------------+
-   | ``stream``   | Use the specified stream to initialize the  |
-   |              | StreamHandler. Note that this argument is   |
-   |              | incompatible with 'filename' - if both are  |
-   |              | present, 'stream' is ignored.               |
-   +--------------+---------------------------------------------+
+.. method:: Logger.findCaller(stack_info=False)
 
-   .. versionchanged:: 3.2
-      The ``style`` argument was added.
+   Finds the caller's source filename and line number. Returns the filename, line
+   number, function name and stack information as a 4-element tuple. The stack
+   information is returned as *None* unless *stack_info* is *True*.
 
 
-.. function:: shutdown()
+.. method:: Logger.handle(record)
 
-   Informs the logging system to perform an orderly shutdown by flushing and
-   closing all handlers. This should be called at application exit and no
-   further use of the logging system should be made after this call.
+   Handles a record by passing it to all handlers associated with this logger and
+   its ancestors (until a false value of *propagate* is found). This method is used
+   for unpickled records received from a socket, as well as those created locally.
+   Logger-level filtering is applied using :meth:`~Logger.filter`.
 
 
-.. function:: setLoggerClass(klass)
+.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)
 
-   Tells the logging system to use the class *klass* when instantiating a logger.
-   The class should define :meth:`__init__` such that only a name argument is
-   required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
-   function is typically called before any loggers are instantiated by applications
-   which need to use custom logger behavior.
+   This is a factory method which can be overridden in subclasses to create
+   specialized :class:`LogRecord` instances.
 
+.. method:: Logger.hasHandlers()
 
-.. seealso::
+   Checks to see if this logger has any handlers configured. This is done by
+   looking for handlers in this logger and its parents in the logger hierarchy.
+   Returns True if a handler was found, else False. The method stops searching
+   up the hierarchy whenever a logger with the 'propagate' attribute set to
+   False is found - that will be the last logger which is checked for the
+   existence of handlers.
 
-   :pep:`282` - A Logging System
-      The proposal which described this feature for inclusion in the Python standard
-      library.
+   .. versionadded:: 3.2
 
-   `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
-      This is the original source for the :mod:`logging` package.  The version of the
-      package available from this site is suitable for use with Python 1.5.2, 2.1.x
-      and 2.2.x, which do not include the :mod:`logging` package in the standard
-      library.
-
-.. _logger:
-
-Logger Objects
---------------
-
-Loggers have the following attributes and methods. Note that Loggers are never
-instantiated directly, but always through the module-level function
-``logging.getLogger(name)``.
-
-.. class:: Logger
-
-.. attribute:: Logger.propagate
-
-   If this evaluates to false, logging messages are not passed by this logger or by
-   its child loggers to the handlers of higher level (ancestor) loggers. The
-   constructor sets this attribute to 1.
-
-
-.. method:: Logger.setLevel(lvl)
-
-   Sets the threshold for this logger to *lvl*. Logging messages which are less
-   severe than *lvl* will be ignored. When a logger is created, the level is set to
-   :const:`NOTSET` (which causes all messages to be processed when the logger is
-   the root logger, or delegation to the parent when the logger is a non-root
-   logger). Note that the root logger is created with level :const:`WARNING`.
-
-   The term "delegation to the parent" means that if a logger has a level of
-   NOTSET, its chain of ancestor loggers is traversed until either an ancestor with
-   a level other than NOTSET is found, or the root is reached.
-
-   If an ancestor is found with a level other than NOTSET, then that ancestor's
-   level is treated as the effective level of the logger where the ancestor search
-   began, and is used to determine how a logging event is handled.
-
-   If the root is reached, and it has a level of NOTSET, then all messages will be
-   processed. Otherwise, the root's level will be used as the effective level.
-
-
-.. method:: Logger.isEnabledFor(lvl)
-
-   Indicates if a message of severity *lvl* would be processed by this logger.
-   This method checks first the module-level level set by
-   ``logging.disable(lvl)`` and then the logger's effective level as determined
-   by :meth:`getEffectiveLevel`.
-
-
-.. method:: Logger.getEffectiveLevel()
-
-   Indicates the effective level for this logger. If a value other than
-   :const:`NOTSET` has been set using :meth:`setLevel`, it is returned. Otherwise,
-   the hierarchy is traversed towards the root until a value other than
-   :const:`NOTSET` is found, and that value is returned.
-
-
-.. method:: Logger.getChild(suffix)
-
-   Returns a logger which is a descendant to this logger, as determined by the suffix.
-   Thus, ``logging.getLogger('abc').getChild('def.ghi')`` would return the same
-   logger as would be returned by ``logging.getLogger('abc.def.ghi')``. This is a
-   convenience method, useful when the parent logger is named using e.g. ``__name__``
-   rather than a literal string.
-
-   .. versionadded:: 3.2
-
-
-.. method:: Logger.debug(msg, *args, **kwargs)
-
-   Logs a message with level :const:`DEBUG` on this logger. The *msg* is the
-   message format string, and the *args* are the arguments which are merged into
-   *msg* using the string formatting operator. (Note that this means that you can
-   use keywords in the format string, together with a single dictionary argument.)
-
-   There are two keyword arguments in *kwargs* which are inspected: *exc_info*
-   which, if it does not evaluate as false, causes exception information to be
-   added to the logging message. If an exception tuple (in the format returned by
-   :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
-   is called to get the exception information.
-
-   The other optional keyword argument is *extra* which can be used to pass a
-   dictionary which is used to populate the __dict__ of the LogRecord created for
-   the logging event with user-defined attributes. These custom attributes can then
-   be used as you like. For example, they could be incorporated into logged
-   messages. For example::
-
-      FORMAT = "%(asctime)-15s %(clientip)s %(user)-8s %(message)s"
-      logging.basicConfig(format=FORMAT)
-      d = { 'clientip' : '192.168.0.1', 'user' : 'fbloggs' }
-      logger = logging.getLogger("tcpserver")
-      logger.warning("Protocol problem: %s", "connection reset", extra=d)
-
-   would print something like  ::
-
-      2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
-
-   The keys in the dictionary passed in *extra* should not clash with the keys used
-   by the logging system. (See the :class:`Formatter` documentation for more
-   information on which keys are used by the logging system.)
-
-   If you choose to use these attributes in logged messages, you need to exercise
-   some care. In the above example, for instance, the :class:`Formatter` has been
-   set up with a format string which expects 'clientip' and 'user' in the attribute
-   dictionary of the LogRecord. If these are missing, the message will not be
-   logged because a string formatting exception will occur. So in this case, you
-   always need to pass the *extra* dictionary with these keys.
-
-   While this might be annoying, this feature is intended for use in specialized
-   circumstances, such as multi-threaded servers where the same code executes in
-   many contexts, and interesting conditions which arise are dependent on this
-   context (such as remote client IP address and authenticated user name, in the
-   above example). In such circumstances, it is likely that specialized
-   :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
-
-
-.. method:: Logger.info(msg, *args, **kwargs)
-
-   Logs a message with level :const:`INFO` on this logger. The arguments are
-   interpreted as for :meth:`debug`.
-
-
-.. method:: Logger.warning(msg, *args, **kwargs)
-
-   Logs a message with level :const:`WARNING` on this logger. The arguments are
-   interpreted as for :meth:`debug`.
-
-
-.. method:: Logger.error(msg, *args, **kwargs)
-
-   Logs a message with level :const:`ERROR` on this logger. The arguments are
-   interpreted as for :meth:`debug`.
-
-
-.. method:: Logger.critical(msg, *args, **kwargs)
-
-   Logs a message with level :const:`CRITICAL` on this logger. The arguments are
-   interpreted as for :meth:`debug`.
-
-
-.. method:: Logger.log(lvl, msg, *args, **kwargs)
-
-   Logs a message with integer level *lvl* on this logger. The other arguments are
-   interpreted as for :meth:`debug`.
-
-
-.. method:: Logger.exception(msg, *args)
-
-   Logs a message with level :const:`ERROR` on this logger. The arguments are
-   interpreted as for :meth:`debug`. Exception info is added to the logging
-   message. This method should only be called from an exception handler.
-
-
-.. method:: Logger.addFilter(filt)
-
-   Adds the specified filter *filt* to this logger.
-
-
-.. method:: Logger.removeFilter(filt)
-
-   Removes the specified filter *filt* from this logger.
-
-
-.. method:: Logger.filter(record)
-
-   Applies this logger's filters to the record and returns a true value if the
-   record is to be processed.
-
-
-.. method:: Logger.addHandler(hdlr)
-
-   Adds the specified handler *hdlr* to this logger.
-
-
-.. method:: Logger.removeHandler(hdlr)
-
-   Removes the specified handler *hdlr* from this logger.
-
-
-.. method:: Logger.findCaller()
-
-   Finds the caller's source filename and line number. Returns the filename, line
-   number and function name as a 3-element tuple.
-
-
-.. method:: Logger.handle(record)
-
-   Handles a record by passing it to all handlers associated with this logger and
-   its ancestors (until a false value of *propagate* is found). This method is used
-   for unpickled records received from a socket, as well as those created locally.
-   Logger-level filtering is applied using :meth:`~Logger.filter`.
-
-
-.. method:: Logger.makeRecord(name, lvl, fn, lno, msg, args, exc_info, func=None, extra=None)
-
-   This is a factory method which can be overridden in subclasses to create
-   specialized :class:`LogRecord` instances.
-
-.. method:: Logger.hasHandlers()
-
-   Checks to see if this logger has any handlers configured. This is done by
-   looking for handlers in this logger and its parents in the logger hierarchy.
-   Returns True if a handler was found, else False. The method stops searching
-   up the hierarchy whenever a logger with the "propagate" attribute set to
-   False is found - that will be the last logger which is checked for the
-   existence of handlers.
-
-.. versionadded:: 3.2
-
-The :meth:`hasHandlers` method was not present in previous versions.
-
-.. _minimal-example:
-
-Basic example
--------------
-
-The :mod:`logging` package provides a lot of flexibility, and its configuration
-can appear daunting.  This section demonstrates that simple use of the logging
-package is possible.
-
-The simplest example shows logging to the console::
-
-   import logging
-
-   logging.debug('A debug message')
-   logging.info('Some information')
-   logging.warning('A shot across the bows')
-
-If you run the above script, you'll see this::
-
-   WARNING:root:A shot across the bows
-
-Because no particular logger was specified, the system used the root logger. The
-debug and info messages didn't appear because by default, the root logger is
-configured to only handle messages with a severity of WARNING or above. The
-message format is also a configuration default, as is the output destination of
-the messages - ``sys.stderr``. The severity level, the message format and
-destination can be easily changed, as shown in the example below::
-
-   import logging
-
-   logging.basicConfig(level=logging.DEBUG,
-                       format='%(asctime)s %(levelname)s %(message)s',
-                       filename='myapp.log',
-                       filemode='w')
-   logging.debug('A debug message')
-   logging.info('Some information')
-   logging.warning('A shot across the bows')
-
-The :meth:`basicConfig` method is used to change the configuration defaults,
-which results in output (written to ``myapp.log``) which should look
-something like the following::
-
-   2004-07-02 13:00:08,743 DEBUG A debug message
-   2004-07-02 13:00:08,743 INFO Some information
-   2004-07-02 13:00:08,743 WARNING A shot across the bows
-
-This time, all messages with a severity of DEBUG or above were handled, and the
-format of the messages was also changed, and output went to the specified file
-rather than the console.
-
-.. XXX logging should probably be updated for new string formatting!
-
-Formatting uses the old Python string formatting - see section
-:ref:`old-string-formatting`. The format string takes the following common
-specifiers. For a complete list of specifiers, consult the :class:`Formatter`
-documentation.
-
-+-------------------+-----------------------------------------------+
-| Format            | Description                                   |
-+===================+===============================================+
-| ``%(name)s``      | Name of the logger (logging channel).         |
-+-------------------+-----------------------------------------------+
-| ``%(levelname)s`` | Text logging level for the message            |
-|                   | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,      |
-|                   | ``'ERROR'``, ``'CRITICAL'``).                 |
-+-------------------+-----------------------------------------------+
-| ``%(asctime)s``   | Human-readable time when the                  |
-|                   | :class:`LogRecord` was created.  By default   |
-|                   | this is of the form "2003-07-08 16:49:45,896" |
-|                   | (the numbers after the comma are millisecond  |
-|                   | portion of the time).                         |
-+-------------------+-----------------------------------------------+
-| ``%(message)s``   | The logged message.                           |
-+-------------------+-----------------------------------------------+
-
-To change the date/time format, you can pass an additional keyword parameter,
-*datefmt*, as in the following::
-
-   import logging
-
-   logging.basicConfig(level=logging.DEBUG,
-                       format='%(asctime)s %(levelname)-8s %(message)s',
-                       datefmt='%a, %d %b %Y %H:%M:%S',
-                       filename='/temp/myapp.log',
-                       filemode='w')
-   logging.debug('A debug message')
-   logging.info('Some information')
-   logging.warning('A shot across the bows')
-
-which would result in output like ::
-
-   Fri, 02 Jul 2004 13:06:18 DEBUG    A debug message
-   Fri, 02 Jul 2004 13:06:18 INFO     Some information
-   Fri, 02 Jul 2004 13:06:18 WARNING  A shot across the bows
-
-The date format string follows the requirements of :func:`strftime` - see the
-documentation for the :mod:`time` module.
-
-If, instead of sending logging output to the console or a file, you'd rather use
-a file-like object which you have created separately, you can pass it to
-:func:`basicConfig` using the *stream* keyword argument. Note that if both
-*stream* and *filename* keyword arguments are passed, the *stream* argument is
-ignored.
-
-Of course, you can put variable information in your output. To do this, simply
-have the message be a format string and pass in additional arguments containing
-the variable information, as in the following example::
-
-   import logging
-
-   logging.basicConfig(level=logging.DEBUG,
-                       format='%(asctime)s %(levelname)-8s %(message)s',
-                       datefmt='%a, %d %b %Y %H:%M:%S',
-                       filename='/temp/myapp.log',
-                       filemode='w')
-   logging.error('Pack my box with %d dozen %s', 5, 'liquor jugs')
-
-which would result in ::
-
-   Wed, 21 Jul 2004 15:35:16 ERROR    Pack my box with 5 dozen liquor jugs
-
-
-.. _multiple-destinations:
-
-Logging to multiple destinations
---------------------------------
-
-Let's say you want to log to console and file with different message formats and
-in differing circumstances. Say you want to log messages with levels of DEBUG
-and higher to file, and those messages at level INFO and higher to the console.
-Let's also assume that the file should contain timestamps, but the console
-messages should not. Here's how you can achieve this::
-
-   import logging
-
-   # set up logging to file - see previous section for more details
-   logging.basicConfig(level=logging.DEBUG,
-                       format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
-                       datefmt='%m-%d %H:%M',
-                       filename='/temp/myapp.log',
-                       filemode='w')
-   # define a Handler which writes INFO messages or higher to the sys.stderr
-   console = logging.StreamHandler()
-   console.setLevel(logging.INFO)
-   # set a format which is simpler for console use
-   formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
-   # tell the handler to use this format
-   console.setFormatter(formatter)
-   # add the handler to the root logger
-   logging.getLogger('').addHandler(console)
-
-   # Now, we can log to the root logger, or any other logger. First the root...
-   logging.info('Jackdaws love my big sphinx of quartz.')
-
-   # Now, define a couple of other loggers which might represent areas in your
-   # application:
-
-   logger1 = logging.getLogger('myapp.area1')
-   logger2 = logging.getLogger('myapp.area2')
-
-   logger1.debug('Quick zephyrs blow, vexing daft Jim.')
-   logger1.info('How quickly daft jumping zebras vex.')
-   logger2.warning('Jail zesty vixen who grabbed pay from quack.')
-   logger2.error('The five boxing wizards jump quickly.')
-
-When you run this, on the console you will see ::
-
-   root        : INFO     Jackdaws love my big sphinx of quartz.
-   myapp.area1 : INFO     How quickly daft jumping zebras vex.
-   myapp.area2 : WARNING  Jail zesty vixen who grabbed pay from quack.
-   myapp.area2 : ERROR    The five boxing wizards jump quickly.
-
-and in the file you will see something like ::
-
-   10-22 22:19 root         INFO     Jackdaws love my big sphinx of quartz.
-   10-22 22:19 myapp.area1  DEBUG    Quick zephyrs blow, vexing daft Jim.
-   10-22 22:19 myapp.area1  INFO     How quickly daft jumping zebras vex.
-   10-22 22:19 myapp.area2  WARNING  Jail zesty vixen who grabbed pay from quack.
-   10-22 22:19 myapp.area2  ERROR    The five boxing wizards jump quickly.
-
-As you can see, the DEBUG message only shows up in the file. The other messages
-are sent to both destinations.
-
-This example uses console and file handlers, but you can use any number and
-combination of handlers you choose.
-
-.. _logging-exceptions:
-
-Exceptions raised during logging
---------------------------------
-
-The logging package is designed to swallow exceptions which occur while logging
-in production. This is so that errors which occur while handling logging events
-- such as logging misconfiguration, network or other similar errors - do not
-cause the application using logging to terminate prematurely.
-
-:class:`SystemExit` and :class:`KeyboardInterrupt` exceptions are never
-swallowed. Other exceptions which occur during the :meth:`emit` method of a
-:class:`Handler` subclass are passed to its :meth:`handleError` method.
-
-The default implementation of :meth:`handleError` in :class:`Handler` checks
-to see if a module-level variable, :data:`raiseExceptions`, is set. If set, a
-traceback is printed to :data:`sys.stderr`. If not set, the exception is swallowed.
-
-**Note:** The default value of :data:`raiseExceptions` is ``True``. This is because
-during development, you typically want to be notified of any exceptions that
-occur. It's advised that you set :data:`raiseExceptions` to ``False`` for production
-usage.
-
-.. _context-info:
-
-Adding contextual information to your logging output
-----------------------------------------------------
-
-Sometimes you want logging output to contain contextual information in
-addition to the parameters passed to the logging call. For example, in a
-networked application, it may be desirable to log client-specific information
-in the log (e.g. remote client's username, or IP address). Although you could
-use the *extra* parameter to achieve this, it's not always convenient to pass
-the information in this way. While it might be tempting to create
-:class:`Logger` instances on a per-connection basis, this is not a good idea
-because these instances are not garbage collected. While this is not a problem
-in practice, when the number of :class:`Logger` instances is dependent on the
-level of granularity you want to use in logging an application, it could
-be hard to manage if the number of :class:`Logger` instances becomes
-effectively unbounded.
-
-
-Using LoggerAdapters to impart contextual information
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-An easy way in which you can pass contextual information to be output along
-with logging event information is to use the :class:`LoggerAdapter` class.
-This class is designed to look like a :class:`Logger`, so that you can call
-:meth:`debug`, :meth:`info`, :meth:`warning`, :meth:`error`,
-:meth:`exception`, :meth:`critical` and :meth:`log`. These methods have the
-same signatures as their counterparts in :class:`Logger`, so you can use the
-two types of instances interchangeably.
-
-When you create an instance of :class:`LoggerAdapter`, you pass it a
-:class:`Logger` instance and a dict-like object which contains your contextual
-information. When you call one of the logging methods on an instance of
-:class:`LoggerAdapter`, it delegates the call to the underlying instance of
-:class:`Logger` passed to its constructor, and arranges to pass the contextual
-information in the delegated call. Here's a snippet from the code of
-:class:`LoggerAdapter`::
-
-    def debug(self, msg, *args, **kwargs):
-        """
-        Delegate a debug call to the underlying logger, after adding
-        contextual information from this adapter instance.
-        """
-        msg, kwargs = self.process(msg, kwargs)
-        self.logger.debug(msg, *args, **kwargs)
-
-The :meth:`process` method of :class:`LoggerAdapter` is where the contextual
-information is added to the logging output. It's passed the message and
-keyword arguments of the logging call, and it passes back (potentially)
-modified versions of these to use in the call to the underlying logger. The
-default implementation of this method leaves the message alone, but inserts
-an "extra" key in the keyword argument whose value is the dict-like object
-passed to the constructor. Of course, if you had passed an "extra" keyword
-argument in the call to the adapter, it will be silently overwritten.
-
-The advantage of using "extra" is that the values in the dict-like object are
-merged into the :class:`LogRecord` instance's __dict__, allowing you to use
-customized strings with your :class:`Formatter` instances which know about
-the keys of the dict-like object. If you need a different method, e.g. if you
-want to prepend or append the contextual information to the message string,
-you just need to subclass :class:`LoggerAdapter` and override :meth:`process`
-to do what you need. Here's an example script which uses this class, which
-also illustrates what dict-like behaviour is needed from an arbitrary
-"dict-like" object for use in the constructor::
-
-   import logging
-
-   class ConnInfo:
-       """
-       An example class which shows how an arbitrary class can be used as
-       the 'extra' context information repository passed to a LoggerAdapter.
-       """
-
-       def __getitem__(self, name):
-           """
-           To allow this instance to look like a dict.
-           """
-           from random import choice
-           if name == "ip":
-               result = choice(["127.0.0.1", "192.168.0.1"])
-           elif name == "user":
-               result = choice(["jim", "fred", "sheila"])
-           else:
-               result = self.__dict__.get(name, "?")
-           return result
-
-       def __iter__(self):
-           """
-           To allow iteration over keys, which will be merged into
-           the LogRecord dict before formatting and output.
-           """
-           keys = ["ip", "user"]
-           keys.extend(self.__dict__.keys())
-           return keys.__iter__()
-
-   if __name__ == "__main__":
-       from random import choice
-       levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
-       a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
-                                  { "ip" : "123.231.231.123", "user" : "sheila" })
-       logging.basicConfig(level=logging.DEBUG,
-                           format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
-       a1.debug("A debug message")
-       a1.info("An info message with %s", "some parameters")
-       a2 = logging.LoggerAdapter(logging.getLogger("d.e.f"), ConnInfo())
-       for x in range(10):
-           lvl = choice(levels)
-           lvlname = logging.getLevelName(lvl)
-           a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
-
-When this script is run, the output should look something like this::
-
-   2008-01-18 14:49:54,023 a.b.c DEBUG    IP: 123.231.231.123 User: sheila   A debug message
-   2008-01-18 14:49:54,023 a.b.c INFO     IP: 123.231.231.123 User: sheila   An info message with some parameters
-   2008-01-18 14:49:54,023 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
-   2008-01-18 14:49:54,033 d.e.f INFO     IP: 192.168.0.1     User: jim      A message at INFO level with 2 parameters
-   2008-01-18 14:49:54,033 d.e.f WARNING  IP: 192.168.0.1     User: sheila   A message at WARNING level with 2 parameters
-   2008-01-18 14:49:54,033 d.e.f ERROR    IP: 127.0.0.1       User: fred     A message at ERROR level with 2 parameters
-   2008-01-18 14:49:54,033 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
-   2008-01-18 14:49:54,033 d.e.f WARNING  IP: 192.168.0.1     User: sheila   A message at WARNING level with 2 parameters
-   2008-01-18 14:49:54,033 d.e.f WARNING  IP: 192.168.0.1     User: jim      A message at WARNING level with 2 parameters
-   2008-01-18 14:49:54,033 d.e.f INFO     IP: 192.168.0.1     User: fred     A message at INFO level with 2 parameters
-   2008-01-18 14:49:54,033 d.e.f WARNING  IP: 192.168.0.1     User: sheila   A message at WARNING level with 2 parameters
-   2008-01-18 14:49:54,033 d.e.f WARNING  IP: 127.0.0.1       User: jim      A message at WARNING level with 2 parameters
-
-
-.. _filters-contextual:
-
-Using Filters to impart contextual information
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-You can also add contextual information to log output using a user-defined
-:class:`Filter`. ``Filter`` instances are allowed to modify the ``LogRecords``
-passed to them, including adding additional attributes which can then be output
-using a suitable format string, or if needed a custom :class:`Formatter`.
-
-For example in a web application, the request being processed (or at least,
-the interesting parts of it) can be stored in a threadlocal
-(:class:`threading.local`) variable, and then accessed from a ``Filter`` to
-add, say, information from the request - say, the remote IP address and remote
-user's username - to the ``LogRecord``, using the attribute names 'ip' and
-'user' as in the ``LoggerAdapter`` example above. In that case, the same format
-string can be used to get similar output to that shown above. Here's an example
-script::
-
-    import logging
-    from random import choice
-
-    class ContextFilter(logging.Filter):
-        """
-        This is a filter which injects contextual information into the log.
-
-        Rather than use actual contextual information, we just use random
-        data in this demo.
-        """
-
-        USERS = ['jim', 'fred', 'sheila']
-        IPS = ['123.231.231.123', '127.0.0.1', '192.168.0.1']
-
-        def filter(self, record):
-
-            record.ip = choice(ContextFilter.IPS)
-            record.user = choice(ContextFilter.USERS)
-            return True
-
-    if __name__ == "__main__":
-       levels = (logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL)
-       a1 = logging.LoggerAdapter(logging.getLogger("a.b.c"),
-                                  { "ip" : "123.231.231.123", "user" : "sheila" })
-       logging.basicConfig(level=logging.DEBUG,
-                           format="%(asctime)-15s %(name)-5s %(levelname)-8s IP: %(ip)-15s User: %(user)-8s %(message)s")
-       a1 = logging.getLogger("a.b.c")
-       a2 = logging.getLogger("d.e.f")
-
-       f = ContextFilter()
-       a1.addFilter(f)
-       a2.addFilter(f)
-       a1.debug("A debug message")
-       a1.info("An info message with %s", "some parameters")
-       for x in range(10):
-           lvl = choice(levels)
-           lvlname = logging.getLevelName(lvl)
-           a2.log(lvl, "A message at %s level with %d %s", lvlname, 2, "parameters")
-
-which, when run, produces something like::
-
-    2010-09-06 22:38:15,292 a.b.c DEBUG    IP: 123.231.231.123 User: fred     A debug message
-    2010-09-06 22:38:15,300 a.b.c INFO     IP: 192.168.0.1     User: sheila   An info message with some parameters
-    2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
-    2010-09-06 22:38:15,300 d.e.f ERROR    IP: 127.0.0.1       User: jim      A message at ERROR level with 2 parameters
-    2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 127.0.0.1       User: sheila   A message at DEBUG level with 2 parameters
-    2010-09-06 22:38:15,300 d.e.f ERROR    IP: 123.231.231.123 User: fred     A message at ERROR level with 2 parameters
-    2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 192.168.0.1     User: jim      A message at CRITICAL level with 2 parameters
-    2010-09-06 22:38:15,300 d.e.f CRITICAL IP: 127.0.0.1       User: sheila   A message at CRITICAL level with 2 parameters
-    2010-09-06 22:38:15,300 d.e.f DEBUG    IP: 192.168.0.1     User: jim      A message at DEBUG level with 2 parameters
-    2010-09-06 22:38:15,301 d.e.f ERROR    IP: 127.0.0.1       User: sheila   A message at ERROR level with 2 parameters
-    2010-09-06 22:38:15,301 d.e.f DEBUG    IP: 123.231.231.123 User: fred     A message at DEBUG level with 2 parameters
-    2010-09-06 22:38:15,301 d.e.f INFO     IP: 123.231.231.123 User: fred     A message at INFO level with 2 parameters
-
-
-.. _multiple-processes:
-
-Logging to a single file from multiple processes
-------------------------------------------------
-
-Although logging is thread-safe, and logging to a single file from multiple
-threads in a single process *is* supported, logging to a single file from
-*multiple processes* is *not* supported, because there is no standard way to
-serialize access to a single file across multiple processes in Python. If you
-need to log to a single file from multiple processes, one way of doing this is
-to have all the processes log to a :class:`SocketHandler`, and have a separate
-process which implements a socket server which reads from the socket and logs
-to file. (If you prefer, you can dedicate one thread in one of the existing
-processes to perform this function.) The following section documents this
-approach in more detail and includes a working socket receiver which can be
-used as a starting point for you to adapt in your own applications.
-
-If you are using a recent version of Python which includes the
-:mod:`multiprocessing` module, you could write your own handler which uses the
-:class:`Lock` class from this module to serialize access to the file from
-your processes. The existing :class:`FileHandler` and subclasses do not make
-use of :mod:`multiprocessing` at present, though they may do so in the future.
-Note that at present, the :mod:`multiprocessing` module does not provide
-working lock functionality on all platforms (see
-http://bugs.python.org/issue3770).
-
-.. currentmodule:: logging.handlers
-
-Alternatively, you can use a ``Queue`` and a :class:`QueueHandler` to send
-all logging events to one of the processes in your multi-process application.
-The following example script demonstrates how you can do this; in the example
-a separate listener process listens for events sent by other processes and logs
-them according to its own logging configuration. Although the example only
-demonstrates one way of doing it (for example, you may want to use a listener
-thread rather than a separate listener process - the implementation would be
-analogous) it does allow for completely different logging configurations for
-the listener and the other processes in your application, and can be used as
-the basis for code meeting your own specific requirements::
-
-    # You'll need these imports in your own code
-    import logging
-    import logging.handlers
-    import multiprocessing
-
-    # Next two import lines for this demo only
-    from random import choice, random
-    import time
-
-    #
-    # Because you'll want to define the logging configurations for listener and workers, the
-    # listener and worker process functions take a configurer parameter which is a callable
-    # for configuring logging for that process. These functions are also passed the queue,
-    # which they use for communication.
-    #
-    # In practice, you can configure the listener however you want, but note that in this
-    # simple example, the listener does not apply level or filter logic to received records.
-    # In practice, you would probably want to do ths logic in the worker processes, to avoid
-    # sending events which would be filtered out between processes.
-    #
-    # The size of the rotated files is made small so you can see the results easily.
-    def listener_configurer():
-        root = logging.getLogger()
-        h = logging.handlers.RotatingFileHandler('/tmp/mptest.log', 'a', 300, 10)
-        f = logging.Formatter('%(asctime)s %(processName)-10s %(name)s %(levelname)-8s %(message)s')
-        h.setFormatter(f)
-        root.addHandler(h)
-
-    # This is the listener process top-level loop: wait for logging events
-    # (LogRecords)on the queue and handle them, quit when you get a None for a
-    # LogRecord.
-    def listener_process(queue, configurer):
-        configurer()
-        while True:
-            try:
-                record = queue.get()
-                if record is None: # We send this as a sentinel to tell the listener to quit.
-                    break
-                logger = logging.getLogger(record.name)
-                logger.handle(record) # No level or filter logic applied - just do it!
-            except (KeyboardInterrupt, SystemExit):
-                raise
-            except:
-                import sys, traceback
-                print >> sys.stderr, 'Whoops! Problem:'
-                traceback.print_exc(file=sys.stderr)
-
-    # Arrays used for random selections in this demo
-
-    LEVELS = [logging.DEBUG, logging.INFO, logging.WARNING,
-              logging.ERROR, logging.CRITICAL]
-
-    LOGGERS = ['a.b.c', 'd.e.f']
-
-    MESSAGES = [
-        'Random message #1',
-        'Random message #2',
-        'Random message #3',
-    ]
-
-    # The worker configuration is done at the start of the worker process run.
-    # Note that on Windows you can't rely on fork semantics, so each process
-    # will run the logging configuration code when it starts.
-    def worker_configurer(queue):
-        h = logging.handlers.QueueHandler(queue) # Just the one handler needed
-        root = logging.getLogger()
-        root.addHandler(h)
-        root.setLevel(logging.DEBUG) # send all messages, for demo; no other level or filter logic applied.
-
-    # This is the worker process top-level loop, which just logs ten events with
-    # random intervening delays before terminating.
-    # The print messages are just so you know it's doing something!
-    def worker_process(queue, configurer):
-        configurer(queue)
-        name = multiprocessing.current_process().name
-        print('Worker started: %s' % name)
-        for i in range(10):
-            time.sleep(random())
-            logger = logging.getLogger(choice(LOGGERS))
-            level = choice(LEVELS)
-            message = choice(MESSAGES)
-            logger.log(level, message)
-        print('Worker finished: %s' % name)
-
-    # Here's where the demo gets orchestrated. Create the queue, create and start
-    # the listener, create ten workers and start them, wait for them to finish,
-    # then send a None to the queue to tell the listener to finish.
-    def main():
-        queue = multiprocessing.Queue(-1)
-        listener = multiprocessing.Process(target=listener_process,
-                                           args=(queue, listener_configurer))
-        listener.start()
-        workers = []
-        for i in range(10):
-            worker = multiprocessing.Process(target=worker_process,
-                                           args=(queue, worker_configurer))
-            workers.append(worker)
-            worker.start()
-        for w in workers:
-            w.join()
-        queue.put_nowait(None)
-        listener.join()
-
-    if __name__ == '__main__':
-        main()
-
-
-.. currentmodule:: logging
-
-
-.. _network-logging:
-
-Sending and receiving logging events across a network
------------------------------------------------------
-
-Let's say you want to send logging events across a network, and handle them at
-the receiving end. A simple way of doing this is attaching a
-:class:`SocketHandler` instance to the root logger at the sending end::
-
-   import logging, logging.handlers
-
-   rootLogger = logging.getLogger('')
-   rootLogger.setLevel(logging.DEBUG)
-   socketHandler = logging.handlers.SocketHandler('localhost',
-                       logging.handlers.DEFAULT_TCP_LOGGING_PORT)
-   # don't bother with a formatter, since a socket handler sends the event as
-   # an unformatted pickle
-   rootLogger.addHandler(socketHandler)
-
-   # Now, we can log to the root logger, or any other logger. First the root...
-   logging.info('Jackdaws love my big sphinx of quartz.')
-
-   # Now, define a couple of other loggers which might represent areas in your
-   # application:
-
-   logger1 = logging.getLogger('myapp.area1')
-   logger2 = logging.getLogger('myapp.area2')
-
-   logger1.debug('Quick zephyrs blow, vexing daft Jim.')
-   logger1.info('How quickly daft jumping zebras vex.')
-   logger2.warning('Jail zesty vixen who grabbed pay from quack.')
-   logger2.error('The five boxing wizards jump quickly.')
-
-At the receiving end, you can set up a receiver using the :mod:`socketserver`
-module. Here is a basic working example::
-
-   import pickle
-   import logging
-   import logging.handlers
-   import socketserver
-   import struct
-
-
-   class LogRecordStreamHandler(socketserver.StreamRequestHandler):
-       """Handler for a streaming logging request.
-
-       This basically logs the record using whatever logging policy is
-       configured locally.
-       """
-
-       def handle(self):
-           """
-           Handle multiple requests - each expected to be a 4-byte length,
-           followed by the LogRecord in pickle format. Logs the record
-           according to whatever policy is configured locally.
-           """
-           while True:
-               chunk = self.connection.recv(4)
-               if len(chunk) < 4:
-                   break
-               slen = struct.unpack(">L", chunk)[0]
-               chunk = self.connection.recv(slen)
-               while len(chunk) < slen:
-                   chunk = chunk + self.connection.recv(slen - len(chunk))
-               obj = self.unPickle(chunk)
-               record = logging.makeLogRecord(obj)
-               self.handleLogRecord(record)
-
-       def unPickle(self, data):
-           return pickle.loads(data)
-
-       def handleLogRecord(self, record):
-           # if a name is specified, we use the named logger rather than the one
-           # implied by the record.
-           if self.server.logname is not None:
-               name = self.server.logname
-           else:
-               name = record.name
-           logger = logging.getLogger(name)
-           # N.B. EVERY record gets logged. This is because Logger.handle
-           # is normally called AFTER logger-level filtering. If you want
-           # to do filtering, do it at the client end to save wasting
-           # cycles and network bandwidth!
-           logger.handle(record)
-
-   class LogRecordSocketReceiver(socketserver.ThreadingTCPServer):
-       """simple TCP socket-based logging receiver suitable for testing.
-       """
-
-       allow_reuse_address = 1
-
-       def __init__(self, host='localhost',
-                    port=logging.handlers.DEFAULT_TCP_LOGGING_PORT,
-                    handler=LogRecordStreamHandler):
-           socketserver.ThreadingTCPServer.__init__(self, (host, port), handler)
-           self.abort = 0
-           self.timeout = 1
-           self.logname = None
-
-       def serve_until_stopped(self):
-           import select
-           abort = 0
-           while not abort:
-               rd, wr, ex = select.select([self.socket.fileno()],
-                                          [], [],
-                                          self.timeout)
-               if rd:
-                   self.handle_request()
-               abort = self.abort
-
-   def main():
-       logging.basicConfig(
-           format="%(relativeCreated)5d %(name)-15s %(levelname)-8s %(message)s")
-       tcpserver = LogRecordSocketReceiver()
-       print("About to start TCP server...")
-       tcpserver.serve_until_stopped()
-
-   if __name__ == "__main__":
-       main()
-
-First run the server, and then the client. On the client side, nothing is
-printed on the console; on the server side, you should see something like::
-
-   About to start TCP server...
-      59 root            INFO     Jackdaws love my big sphinx of quartz.
-      59 myapp.area1     DEBUG    Quick zephyrs blow, vexing daft Jim.
-      69 myapp.area1     INFO     How quickly daft jumping zebras vex.
-      69 myapp.area2     WARNING  Jail zesty vixen who grabbed pay from quack.
-      69 myapp.area2     ERROR    The five boxing wizards jump quickly.
-
-Note that there are some security issues with pickle in some scenarios. If
-these affect you, you can use an alternative serialization scheme by overriding
-the :meth:`makePickle` method and implementing your alternative there, as
-well as adapting the above script to use your alternative serialization.
-
-.. _arbitrary-object-messages:
-
-Using arbitrary objects as messages
------------------------------------
-
-In the preceding sections and examples, it has been assumed that the message
-passed when logging the event is a string. However, this is not the only
-possibility. You can pass an arbitrary object as a message, and its
-:meth:`__str__` method will be called when the logging system needs to convert
-it to a string representation. In fact, if you want to, you can avoid
-computing a string representation altogether - for example, the
-:class:`SocketHandler` emits an event by pickling it and sending it over the
-wire.
-
-Dealing with handlers that block
---------------------------------
-
-.. currentmodule:: logging.handlers
-
-Sometimes you have to get your logging handlers to do their work without
-blocking the thread you’re logging from. This is common in Web applications,
-though of course it also occurs in other scenarios.
-
-A common culprit which demonstrates sluggish behaviour is the
-:class:`SMTPHandler`: sending emails can take a long time, for a
-number of reasons outside the developer’s control (for example, a poorly
-performing mail or network infrastructure). But almost any network-based
-handler can block: Even a :class:`SocketHandler` operation may do a
-DNS query under the hood which is too slow (and this query can be deep in the
-socket library code, below the Python layer, and outside your control).
-
-One solution is to use a two-part approach. For the first part, attach only a
-:class:`QueueHandler` to those loggers which are accessed from
-performance-critical threads. They simply write to their queue, which can be
-sized to a large enough capacity or initialized with no upper bound to their
-size. The write to the queue will typically be accepted quickly, though you
-will probably need to catch the :ref:`queue.Full` exception as a precaution
-in your code. If you are a library developer who has performance-critical
-threads in their code, be sure to document this (together with a suggestion to
-attach only ``QueueHandlers`` to your loggers) for the benefit of other
-developers who will use your code.
-
-The second part of the solution is :class:`QueueListener`, which has been
-designed as the counterpart to :class:`QueueHandler`.  A
-:class:`QueueListener` is very simple: it’s passed a queue and some handlers,
-and it fires up an internal thread which listens to its queue for LogRecords
-sent from ``QueueHandlers`` (or any other source of ``LogRecords``, for that
-matter). The ``LogRecords`` are removed from the queue and passed to the
-handlers for processing.
-
-The advantage of having a separate :class:`QueueListener` class is that you
-can use the same instance to service multiple ``QueueHandlers``. This is more
-resource-friendly than, say, having threaded versions of the existing handler
-classes, which would eat up one thread per handler for no particular benefit.
-
-An example of using these two classes follows (imports omitted)::
-
-    que = queue.Queue(-1) # no limit on size
-    queue_handler = QueueHandler(que)
-    handler = logging.StreamHandler()
-    listener = QueueListener(que, handler)
-    root = logging.getLogger()
-    root.addHandler(queue_handler)
-    formatter = logging.Formatter('%(threadName)s: %(message)s')
-    handler.setFormatter(formatter)
-    listener.start()
-    # The log output will display the thread which generated
-    # the event (the main thread) rather than the internal
-    # thread which monitors the internal queue. This is what
-    # you want to happen.
-    root.warning('Look out!')
-    listener.stop()
-
-which, when run, will produce::
-
-    MainThread: Look out!
-
-
-Optimization
-------------
-
-Formatting of message arguments is deferred until it cannot be avoided.
-However, computing the arguments passed to the logging method can also be
-expensive, and you may want to avoid doing it if the logger will just throw
-away your event. To decide what to do, you can call the :meth:`isEnabledFor`
-method which takes a level argument and returns true if the event would be
-created by the Logger for that level of call. You can write code like this::
-
-    if logger.isEnabledFor(logging.DEBUG):
-        logger.debug("Message with %s, %s", expensive_func1(),
-                                            expensive_func2())
-
-so that if the logger's threshold is set above ``DEBUG``, the calls to
-:func:`expensive_func1` and :func:`expensive_func2` are never made.
-
-There are other optimizations which can be made for specific applications which
-need more precise control over what logging information is collected. Here's a
-list of things you can do to avoid processing during logging which you don't
-need:
-
-+-----------------------------------------------+----------------------------------------+
-| What you don't want to collect                | How to avoid collecting it             |
-+===============================================+========================================+
-| Information about where calls were made from. | Set ``logging._srcfile`` to ``None``.  |
-+-----------------------------------------------+----------------------------------------+
-| Threading information.                        | Set ``logging.logThreads`` to ``0``.   |
-+-----------------------------------------------+----------------------------------------+
-| Process information.                          | Set ``logging.logProcesses`` to ``0``. |
-+-----------------------------------------------+----------------------------------------+
-
-Also note that the core logging module only includes the basic handlers. If
-you don't import :mod:`logging.handlers` and :mod:`logging.config`, they won't
-take up any memory.
 
 .. _handler:
 
@@ -2087,1156 +379,653 @@
    is intended to be implemented by subclasses and so raises a
    :exc:`NotImplementedError`.
 
+For a list of handlers included as standard, see :mod:`logging.handlers`.
 
-.. _stream-handler:
-
-StreamHandler
-^^^^^^^^^^^^^
-
-The :class:`StreamHandler` class, located in the core :mod:`logging` package,
-sends logging output to streams such as *sys.stdout*, *sys.stderr* or any
-file-like object (or, more precisely, any object which supports :meth:`write`
-and :meth:`flush` methods).
+.. _formatter-objects:
 
+Formatter Objects
+-----------------
 
 .. currentmodule:: logging
 
-.. class:: StreamHandler(stream=None)
-
-   Returns a new instance of the :class:`StreamHandler` class. If *stream* is
-   specified, the instance will use it for logging output; otherwise, *sys.stderr*
-   will be used.
+:class:`Formatter` objects have the following attributes and methods. They are
+responsible for converting a :class:`LogRecord` to (usually) a string which can
+be interpreted by either a human or an external system. The base
+:class:`Formatter` allows a formatting string to be specified. If none is
+supplied, the default value of ``'%(message)s'`` is used.
 
+A Formatter can be initialized with a format string which makes use of knowledge
+of the :class:`LogRecord` attributes - such as the default value mentioned above
+making use of the fact that the user's message and arguments are pre-formatted
+into a :class:`LogRecord`'s *message* attribute.  This format string contains
+standard Python %-style mapping keys. See section :ref:`old-string-formatting`
+for more information on string formatting.
 
-   .. method:: emit(record)
+The useful mapping keys in a :class:`LogRecord` are given in the section on
+:ref:`logrecord-attributes`.
 
-      If a formatter is specified, it is used to format the record. The record
-      is then written to the stream with a trailing newline. If exception
-      information is present, it is formatted using
-      :func:`traceback.print_exception` and appended to the stream.
 
+.. class:: Formatter(fmt=None, datefmt=None)
 
-   .. method:: flush()
+   Returns a new instance of the :class:`Formatter` class.  The instance is
+   initialized with a format string for the message as a whole, as well as a
+   format string for the date/time portion of a message.  If no *fmt* is
+   specified, ``'%(message)s'`` is used.  If no *datefmt* is specified, the
+   ISO8601 date format is used.
 
-      Flushes the stream by calling its :meth:`flush` method. Note that the
-      :meth:`close` method is inherited from :class:`Handler` and so does
-      no output, so an explicit :meth:`flush` call may be needed at times.
+   .. method:: format(record)
 
-.. versionchanged:: 3.2
-   The ``StreamHandler`` class now has a ``terminator`` attribute, default
-   value ``"\n"``, which is used as the terminator when writing a formatted
-   record to a stream. If you don't want this newline termination, you can
-   set the handler instance's ``terminator`` attribute to the empty string.
+      The record's attribute dictionary is used as the operand to a string
+      formatting operation. Returns the resulting string. Before formatting the
+      dictionary, a couple of preparatory steps are carried out. The *message*
+      attribute of the record is computed using *msg* % *args*. If the
+      formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
+      to format the event time. If there is exception information, it is
+      formatted using :meth:`formatException` and appended to the message. Note
+      that the formatted exception information is cached in attribute
+      *exc_text*. This is useful because the exception information can be
+      pickled and sent across the wire, but you should be careful if you have
+      more than one :class:`Formatter` subclass which customizes the formatting
+      of exception information. In this case, you will have to clear the cached
+      value after a formatter has done its formatting, so that the next
+      formatter to handle the event doesn't use the cached value but
+      recalculates it afresh.
 
-.. _file-handler:
+      If stack information is available, it's appended after the exception
+      information, using :meth:`formatStack` to transform it if necessary.
 
-FileHandler
-^^^^^^^^^^^
 
-The :class:`FileHandler` class, located in the core :mod:`logging` package,
-sends logging output to a disk file.  It inherits the output functionality from
-:class:`StreamHandler`.
+   .. method:: formatTime(record, datefmt=None)
 
+      This method should be called from :meth:`format` by a formatter which
+      wants to make use of a formatted time. This method can be overridden in
+      formatters to provide for any specific requirement, but the basic behavior
+      is as follows: if *datefmt* (a string) is specified, it is used with
+      :func:`time.strftime` to format the creation time of the
+      record. Otherwise, the ISO8601 format is used.  The resulting string is
+      returned.
 
-.. class:: FileHandler(filename, mode='a', encoding=None, delay=False)
 
-   Returns a new instance of the :class:`FileHandler` class. The specified file is
-   opened and used as the stream for logging. If *mode* is not specified,
-   :const:`'a'` is used.  If *encoding* is not *None*, it is used to open the file
-   with that encoding.  If *delay* is true, then file opening is deferred until the
-   first call to :meth:`emit`. By default, the file grows indefinitely.
+   .. method:: formatException(exc_info)
 
+      Formats the specified exception information (a standard exception tuple as
+      returned by :func:`sys.exc_info`) as a string. This default implementation
+      just uses :func:`traceback.print_exception`. The resulting string is
+      returned.
 
-   .. method:: close()
+   .. method:: formatStack(stack_info)
 
-      Closes the file.
+      Formats the specified stack information (a string as returned by
+      :func:`traceback.print_stack`, but with the last newline removed) as a
+      string. This default implementation just returns the input value.
 
+.. _filter:
 
-   .. method:: emit(record)
+Filter Objects
+--------------
 
-      Outputs the record to the file.
+``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
+filtering than is provided by levels. The base filter class only allows events
+which are below a certain point in the logger hierarchy. For example, a filter
+initialized with 'A.B' will allow events logged by loggers 'A.B', 'A.B.C',
+'A.B.C.D', 'A.B.D' etc. but not 'A.BB', 'B.A.B' etc. If initialized with the
+empty string, all events are passed.
 
-.. _null-handler:
 
-NullHandler
-^^^^^^^^^^^
+.. class:: Filter(name='')
 
-.. versionadded:: 3.1
+   Returns an instance of the :class:`Filter` class. If *name* is specified, it
+   names a logger which, together with its children, will have its events allowed
+   through the filter. If *name* is the empty string, allows every event.
 
-The :class:`NullHandler` class, located in the core :mod:`logging` package,
-does not do any formatting or output. It is essentially a "no-op" handler
-for use by library developers.
 
+   .. method:: filter(record)
 
-.. class:: NullHandler()
+      Is the specified record to be logged? Returns zero for no, nonzero for
+      yes. If deemed appropriate, the record may be modified in-place by this
+      method.
 
-   Returns a new instance of the :class:`NullHandler` class.
+Note that filters attached to handlers are consulted whenever an event is
+emitted by the handler, whereas filters attached to loggers are consulted
+whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
+etc.) This means that events which have been generated by descendant loggers
+will not be filtered by a logger's filter setting, unless the filter has also
+been applied to those descendant loggers.
 
+You don't actually need to subclass ``Filter``: you can pass any instance
+which has a ``filter`` method with the same semantics.
 
-   .. method:: emit(record)
+.. versionchanged:: 3.2
+   You don't need to create specialized ``Filter`` classes, or use other
+   classes with a ``filter`` method: you can use a function (or other
+   callable) as a filter. The filtering logic will check to see if the filter
+   object has a ``filter`` attribute: if it does, it's assumed to be a
+   ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
+   assumed to be a callable and called with the record as the single
+   parameter. The returned value should conform to that returned by
+   :meth:`~Filter.filter`.
 
-      This method does nothing.
+Although filters are used primarily to filter records based on more
+sophisticated criteria than levels, they get to see every record which is
+processed by the handler or logger they're attached to: this can be useful if
+you want to do things like counting how many records were processed by a
+particular logger or handler, or adding, changing or removing attributes in
+the LogRecord being processed. Obviously changing the LogRecord needs to be
+done with some care, but it does allow the injection of contextual information
+into logs (see :ref:`filters-contextual`).
 
-   .. method:: handle(record)
+.. _log-record:
 
-      This method does nothing.
+LogRecord Objects
+-----------------
 
-   .. method:: createLock()
+:class:`LogRecord` instances are created automatically by the :class:`Logger`
+every time something is logged, and can be created manually via
+:func:`makeLogRecord` (for example, from a pickled event received over the
+wire).
 
-      This method returns ``None`` for the lock, since there is no
-      underlying I/O to which access needs to be serialized.
 
+.. class:: LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)
 
-See :ref:`library-config` for more information on how to use
-:class:`NullHandler`.
+   Contains all the information pertinent to the event being logged.
 
-.. _watched-file-handler:
+   The primary information is passed in :attr:`msg` and :attr:`args`, which
+   are combined using ``msg % args`` to create the :attr:`message` field of the
+   record.
 
-WatchedFileHandler
-^^^^^^^^^^^^^^^^^^
+   :param name:  The name of the logger used to log the event represented by
+                 this LogRecord.
+   :param level: The numeric level of the logging event (one of DEBUG, INFO etc.)
+   :param pathname: The full pathname of the source file where the logging call
+                    was made.
+   :param lineno: The line number in the source file where the logging call was
+                  made.
+   :param msg: The event description message, possibly a format string with
+               placeholders for variable data.
+   :param args: Variable data to merge into the *msg* argument to obtain the
+                event description.
+   :param exc_info: An exception tuple with the current exception information,
+                    or *None* if no exception information is available.
+   :param func: The name of the function or method from which the logging call
+                was invoked.
+   :param sinfo: A text string representing stack information from the base of
+                 the stack in the current thread, up to the logging call.
 
-.. currentmodule:: logging.handlers
+   .. method:: getMessage()
 
-The :class:`WatchedFileHandler` class, located in the :mod:`logging.handlers`
-module, is a :class:`FileHandler` which watches the file it is logging to. If
-the file changes, it is closed and reopened using the file name.
+      Returns the message for this :class:`LogRecord` instance after merging any
+      user-supplied arguments with the message. If the user-supplied message
+      argument to the logging call is not a string, :func:`str` is called on it to
+      convert it to a string. This allows use of user-defined classes as
+      messages, whose ``__str__`` method can return the actual format string to
+      be used.
 
-A file change can happen because of usage of programs such as *newsyslog* and
-*logrotate* which perform log file rotation. This handler, intended for use
-under Unix/Linux, watches the file to see if it has changed since the last emit.
-(A file is deemed to have changed if its device or inode have changed.) If the
-file has changed, the old file stream is closed, and the file opened to get a
-new stream.
+   .. versionchanged:: 3.2
+      The creation of a ``LogRecord`` has been made more configurable by
+      providing a factory which is used to create the record. The factory can be
+      set using :func:`getLogRecordFactory` and :func:`setLogRecordFactory`
+      (see this for the factory's signature).
+
+   This functionality can be used to inject your own values into a
+   LogRecord at creation time. You can use the following pattern::
+
+      old_factory = logging.getLogRecordFactory()
+
+      def record_factory(*args, **kwargs):
+          record = old_factory(*args, **kwargs)
+          record.custom_attribute = 0xdecafbad
+          return record
+
+      logging.setLogRecordFactory(record_factory)
+
+   With this pattern, multiple factories could be chained, and as long
+   as they don't overwrite each other's attributes or unintentionally
+   overwrite the standard attributes listed above, there should be no
+   surprises.
+
+
+.. _logrecord-attributes:
+
+LogRecord attributes
+--------------------
+
+The LogRecord has a number of attributes, most of which are derived from the
+parameters to the constructor. (Note that the names do not always correspond
+exactly between the LogRecord constructor parameters and the LogRecord
+attributes.) These attributes can be used to merge data from the record into
+the format string. The following table lists (in alphabetical order) the
+attribute names, their meanings and the corresponding placeholder in a %-style
+format string.
+
+If you are using {}-formatting (:func:`str.format`), you can use
+``{attrname}`` as the placeholder in the format string. If you are using
+$-formatting (:class:`string.Template`), use the form ``${attrname}``. In
+both cases, of course, replace ``attrname`` with the actual attribute name
+you want to use.
+
+In the case of {}-formatting, you can specify formatting flags by placing them
+after the attribute name, separated from it with a colon. For example: a
+placeholder of ``{msecs:03d}`` would format a millisecond value of ``4`` as
+``004``. Refer to the :meth:`str.format` documentation for full details on
+the options available to you.
+
++----------------+-------------------------+-----------------------------------------------+
+| Attribute name | Format                  | Description                                   |
++================+=========================+===============================================+
+| args           | You shouldn't need to   | The tuple of arguments merged into ``msg`` to |
+|                | format this yourself.   | produce ``message``.                          |
++----------------+-------------------------+-----------------------------------------------+
+| asctime        | ``%(asctime)s``         | Human-readable time when the                  |
+|                |                         | :class:`LogRecord` was created.  By default   |
+|                |                         | this is of the form '2003-07-08 16:49:45,896' |
+|                |                         | (the numbers after the comma are millisecond  |
+|                |                         | portion of the time).                         |
++----------------+-------------------------+-----------------------------------------------+
+| created        | ``%(created)f``         | Time when the :class:`LogRecord` was created  |
+|                |                         | (as returned by :func:`time.time`).           |
++----------------+-------------------------+-----------------------------------------------+
+| exc_info       | You shouldn't need to   | Exception tuple (à la ``sys.exc_info``) or,   |
+|                | format this yourself.   | if no exception has occurred, *None*.         |
++----------------+-------------------------+-----------------------------------------------+
+| filename       | ``%(filename)s``        | Filename portion of ``pathname``.             |
++----------------+-------------------------+-----------------------------------------------+
+| funcName       | ``%(funcName)s``        | Name of function containing the logging call. |
++----------------+-------------------------+-----------------------------------------------+
+| levelname      | ``%(levelname)s``       | Text logging level for the message            |
+|                |                         | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,      |
+|                |                         | ``'ERROR'``, ``'CRITICAL'``).                 |
++----------------+-------------------------+-----------------------------------------------+
+| levelno        | ``%(levelno)s``         | Numeric logging level for the message         |
+|                |                         | (:const:`DEBUG`, :const:`INFO`,               |
+|                |                         | :const:`WARNING`, :const:`ERROR`,             |
+|                |                         | :const:`CRITICAL`).                           |
++----------------+-------------------------+-----------------------------------------------+
+| lineno         | ``%(lineno)d``          | Source line number where the logging call was |
+|                |                         | issued (if available).                        |
++----------------+-------------------------+-----------------------------------------------+
+| module         | ``%(module)s``          | Module (name portion of ``filename``).        |
++----------------+-------------------------+-----------------------------------------------+
+| msecs          | ``%(msecs)d``           | Millisecond portion of the time when the      |
+|                |                         | :class:`LogRecord` was created.               |
++----------------+-------------------------+-----------------------------------------------+
+| message        | ``%(message)s``         | The logged message, computed as ``msg %       |
+|                |                         | args``. This is set when                      |
+|                |                         | :meth:`Formatter.format` is invoked.          |
++----------------+-------------------------+-----------------------------------------------+
+| msg            | You shouldn't need to   | The format string passed in the original      |
+|                | format this yourself.   | logging call. Merged with ``args`` to         |
+|                |                         | produce ``message``, or an arbitrary object   |
+|                |                         | (see :ref:`arbitrary-object-messages`).       |
++----------------+-------------------------+-----------------------------------------------+
+| name           | ``%(name)s``            | Name of the logger used to log the call.      |
++----------------+-------------------------+-----------------------------------------------+
+| pathname       | ``%(pathname)s``        | Full pathname of the source file where the    |
+|                |                         | logging call was issued (if available).       |
++----------------+-------------------------+-----------------------------------------------+
+| process        | ``%(process)d``         | Process ID (if available).                    |
++----------------+-------------------------+-----------------------------------------------+
+| processName    | ``%(processName)s``     | Process name (if available).                  |
++----------------+-------------------------+-----------------------------------------------+
+| relativeCreated| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was   |
+|                |                         | created, relative to the time the logging     |
+|                |                         | module was loaded.                            |
++----------------+-------------------------+-----------------------------------------------+
+| stack_info     | You shouldn't need to   | Stack frame information (where available)     |
+|                | format this yourself.   | from the bottom of the stack in the current   |
+|                |                         | thread, up to and including the stack frame   |
+|                |                         | of the logging call which resulted in the     |
+|                |                         | creation of this record.                      |
++----------------+-------------------------+-----------------------------------------------+
+| thread         | ``%(thread)d``          | Thread ID (if available).                     |
++----------------+-------------------------+-----------------------------------------------+
+| threadName     | ``%(threadName)s``      | Thread name (if available).                   |
++----------------+-------------------------+-----------------------------------------------+
 
-This handler is not appropriate for use under Windows, because under Windows
-open log files cannot be moved or renamed - logging opens the files with
-exclusive locks - and so there is no need for such a handler. Furthermore,
-*ST_INO* is not supported under Windows; :func:`stat` always returns zero for
-this value.
 
+.. _logger-adapter:
 
-.. class:: WatchedFileHandler(filename[,mode[, encoding[, delay]]])
+LoggerAdapter Objects
+---------------------
 
-   Returns a new instance of the :class:`WatchedFileHandler` class. The specified
-   file is opened and used as the stream for logging. If *mode* is not specified,
-   :const:`'a'` is used.  If *encoding* is not *None*, it is used to open the file
-   with that encoding.  If *delay* is true, then file opening is deferred until the
-   first call to :meth:`emit`.  By default, the file grows indefinitely.
+:class:`LoggerAdapter` instances are used to conveniently pass contextual
+information into logging calls. For a usage example , see the section on
+:ref:`adding contextual information to your logging output <context-info>`.
 
 
-   .. method:: emit(record)
+.. class:: LoggerAdapter(logger, extra)
 
-      Outputs the record to the file, but first checks to see if the file has
-      changed.  If it has, the existing stream is flushed and closed and the
-      file opened again, before outputting the record to the file.
+   Returns an instance of :class:`LoggerAdapter` initialized with an
+   underlying :class:`Logger` instance and a dict-like object.
 
-.. _rotating-file-handler:
+   .. method:: process(msg, kwargs)
 
-RotatingFileHandler
-^^^^^^^^^^^^^^^^^^^
+      Modifies the message and/or keyword arguments passed to a logging call in
+      order to insert contextual information. This implementation takes the object
+      passed as *extra* to the constructor and adds it to *kwargs* using key
+      'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
+      (possibly modified) versions of the arguments passed in.
 
-The :class:`RotatingFileHandler` class, located in the :mod:`logging.handlers`
-module, supports rotation of disk log files.
+In addition to the above, :class:`LoggerAdapter` supports the following
+methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
+:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
+:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
+:meth:`hasHandlers`. These methods have the same signatures as their
+counterparts in :class:`Logger`, so you can use the two types of instances
+interchangeably.
 
+.. versionchanged:: 3.2
+   The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
+   :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`.  These
+   methods delegate to the underlying logger.
 
-.. class:: RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
 
-   Returns a new instance of the :class:`RotatingFileHandler` class. The specified
-   file is opened and used as the stream for logging. If *mode* is not specified,
-   ``'a'`` is used.  If *encoding* is not *None*, it is used to open the file
-   with that encoding.  If *delay* is true, then file opening is deferred until the
-   first call to :meth:`emit`.  By default, the file grows indefinitely.
+Thread Safety
+-------------
 
-   You can use the *maxBytes* and *backupCount* values to allow the file to
-   :dfn:`rollover` at a predetermined size. When the size is about to be exceeded,
-   the file is closed and a new file is silently opened for output. Rollover occurs
-   whenever the current log file is nearly *maxBytes* in length; if *maxBytes* is
-   zero, rollover never occurs.  If *backupCount* is non-zero, the system will save
-   old log files by appending the extensions ".1", ".2" etc., to the filename. For
-   example, with a *backupCount* of 5 and a base file name of :file:`app.log`, you
-   would get :file:`app.log`, :file:`app.log.1`, :file:`app.log.2`, up to
-   :file:`app.log.5`. The file being written to is always :file:`app.log`.  When
-   this file is filled, it is closed and renamed to :file:`app.log.1`, and if files
-   :file:`app.log.1`, :file:`app.log.2`, etc.  exist, then they are renamed to
-   :file:`app.log.2`, :file:`app.log.3` etc.  respectively.
+The logging module is intended to be thread-safe without any special work
+needing to be done by its clients. It achieves this though using threading
+locks; there is one lock to serialize access to the module's shared data, and
+each handler also creates a lock to serialize access to its underlying I/O.
 
+If you are implementing asynchronous signal handlers using the :mod:`signal`
+module, you may not be able to use logging from within such handlers. This is
+because lock implementations in the :mod:`threading` module are not always
+re-entrant, and so cannot be invoked from such signal handlers.
 
-   .. method:: doRollover()
 
-      Does a rollover, as described above.
+Module-Level Functions
+----------------------
 
+In addition to the classes described above, there are a number of module- level
+functions.
 
-   .. method:: emit(record)
 
-      Outputs the record to the file, catering for rollover as described
-      previously.
+.. function:: getLogger(name=None)
 
-.. _timed-rotating-file-handler:
+   Return a logger with the specified name or, if name is ``None``, return a
+   logger which is the root logger of the hierarchy. If specified, the name is
+   typically a dot-separated hierarchical name like *'a'*, *'a.b'* or *'a.b.c.d'*.
+   Choice of these names is entirely up to the developer who is using logging.
 
-TimedRotatingFileHandler
-^^^^^^^^^^^^^^^^^^^^^^^^
+   All calls to this function with a given name return the same logger instance.
+   This means that logger instances never need to be passed between different parts
+   of an application.
 
-The :class:`TimedRotatingFileHandler` class, located in the
-:mod:`logging.handlers` module, supports rotation of disk log files at certain
-timed intervals.
 
+.. function:: getLoggerClass()
 
-.. class:: TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
+   Return either the standard :class:`Logger` class, or the last class passed to
+   :func:`setLoggerClass`. This function may be called from within a new class
+   definition, to ensure that installing a customised :class:`Logger` class will
+   not undo customisations already applied by other code. For example::
 
-   Returns a new instance of the :class:`TimedRotatingFileHandler` class. The
-   specified file is opened and used as the stream for logging. On rotating it also
-   sets the filename suffix. Rotating happens based on the product of *when* and
-   *interval*.
+      class MyLogger(logging.getLoggerClass()):
+          # ... override behaviour here
 
-   You can use the *when* to specify the type of *interval*. The list of possible
-   values is below.  Note that they are not case sensitive.
 
-   +----------------+-----------------------+
-   | Value          | Type of interval      |
-   +================+=======================+
-   | ``'S'``        | Seconds               |
-   +----------------+-----------------------+
-   | ``'M'``        | Minutes               |
-   +----------------+-----------------------+
-   | ``'H'``        | Hours                 |
-   +----------------+-----------------------+
-   | ``'D'``        | Days                  |
-   +----------------+-----------------------+
-   | ``'W'``        | Week day (0=Monday)   |
-   +----------------+-----------------------+
-   | ``'midnight'`` | Roll over at midnight |
-   +----------------+-----------------------+
+.. function:: getLogRecordFactory()
 
-   The system will save old log files by appending extensions to the filename.
-   The extensions are date-and-time based, using the strftime format
-   ``%Y-%m-%d_%H-%M-%S`` or a leading portion thereof, depending on the
-   rollover interval.
+   Return a callable which is used to create a :class:`LogRecord`.
 
-   When computing the next rollover time for the first time (when the handler
-   is created), the last modification time of an existing log file, or else
-   the current time, is used to compute when the next rotation will occur.
+   .. versionadded:: 3.2
+      This function has been provided, along with :func:`setLogRecordFactory`,
+      to allow developers more control over how the :class:`LogRecord`
+      representing a logging event is constructed.
 
-   If the *utc* argument is true, times in UTC will be used; otherwise
-   local time is used.
+   See :func:`setLogRecordFactory` for more information about the how the
+   factory is called.
 
-   If *backupCount* is nonzero, at most *backupCount* files
-   will be kept, and if more would be created when rollover occurs, the oldest
-   one is deleted. The deletion logic uses the interval to determine which
-   files to delete, so changing the interval may leave old files lying around.
+.. function:: debug(msg, *args, **kwargs)
 
-   If *delay* is true, then file opening is deferred until the first call to
-   :meth:`emit`.
+   Logs a message with level :const:`DEBUG` on the root logger. The *msg* is the
+   message format string, and the *args* are the arguments which are merged into
+   *msg* using the string formatting operator. (Note that this means that you can
+   use keywords in the format string, together with a single dictionary argument.)
 
+   There are three keyword arguments in *kwargs* which are inspected: *exc_info*
+   which, if it does not evaluate as false, causes exception information to be
+   added to the logging message. If an exception tuple (in the format returned by
+   :func:`sys.exc_info`) is provided, it is used; otherwise, :func:`sys.exc_info`
+   is called to get the exception information.
 
-   .. method:: doRollover()
+   The second optional keyword argument is *stack_info*, which defaults to
+   False. If specified as True, stack information is added to the logging
+   message, including the actual logging call. Note that this is not the same
+   stack information as that displayed through specifying *exc_info*: The
+   former is stack frames from the bottom of the stack up to the logging call
+   in the current thread, whereas the latter is information about stack frames
+   which have been unwound, following an exception, while searching for
+   exception handlers.
+
+   You can specify *stack_info* independently of *exc_info*, e.g. to just show
+   how you got to a certain point in your code, even when no exceptions were
+   raised. The stack frames are printed following a header line which says::
 
-      Does a rollover, as described above.
+       Stack (most recent call last):
 
+   This mimics the `Traceback (most recent call last):` which is used when
+   displaying exception frames.
 
-   .. method:: emit(record)
+   The third optional keyword argument is *extra* which can be used to pass a
+   dictionary which is used to populate the __dict__ of the LogRecord created for
+   the logging event with user-defined attributes. These custom attributes can then
+   be used as you like. For example, they could be incorporated into logged
+   messages. For example::
 
-      Outputs the record to the file, catering for rollover as described above.
+      FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
+      logging.basicConfig(format=FORMAT)
+      d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
+      logging.warning('Protocol problem: %s', 'connection reset', extra=d)
 
+   would print something like::
 
-.. _socket-handler:
+      2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset
 
-SocketHandler
-^^^^^^^^^^^^^
+   The keys in the dictionary passed in *extra* should not clash with the keys used
+   by the logging system. (See the :class:`Formatter` documentation for more
+   information on which keys are used by the logging system.)
 
-The :class:`SocketHandler` class, located in the :mod:`logging.handlers` module,
-sends logging output to a network socket. The base class uses a TCP socket.
+   If you choose to use these attributes in logged messages, you need to exercise
+   some care. In the above example, for instance, the :class:`Formatter` has been
+   set up with a format string which expects 'clientip' and 'user' in the attribute
+   dictionary of the LogRecord. If these are missing, the message will not be
+   logged because a string formatting exception will occur. So in this case, you
+   always need to pass the *extra* dictionary with these keys.
 
+   While this might be annoying, this feature is intended for use in specialized
+   circumstances, such as multi-threaded servers where the same code executes in
+   many contexts, and interesting conditions which arise are dependent on this
+   context (such as remote client IP address and authenticated user name, in the
+   above example). In such circumstances, it is likely that specialized
+   :class:`Formatter`\ s would be used with particular :class:`Handler`\ s.
 
-.. class:: SocketHandler(host, port)
+   .. versionadded:: 3.2
+      The *stack_info* parameter was added.
 
-   Returns a new instance of the :class:`SocketHandler` class intended to
-   communicate with a remote machine whose address is given by *host* and *port*.
+.. function:: info(msg, *args, **kwargs)
 
+   Logs a message with level :const:`INFO` on the root logger. The arguments are
+   interpreted as for :func:`debug`.
 
-   .. method:: close()
 
-      Closes the socket.
+.. function:: warning(msg, *args, **kwargs)
 
+   Logs a message with level :const:`WARNING` on the root logger. The arguments are
+   interpreted as for :func:`debug`.
 
-   .. method:: 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
-      packet. If the connection was previously lost, re-establishes the
-      connection. To unpickle the record at the receiving end into a
-      :class:`LogRecord`, use the :func:`makeLogRecord` function.
+.. function:: error(msg, *args, **kwargs)
 
+   Logs a message with level :const:`ERROR` on the root logger. The arguments are
+   interpreted as for :func:`debug`.
 
-   .. method:: handleError()
 
-      Handles an error which has occurred during :meth:`emit`. The most likely
-      cause is a lost connection. Closes the socket so that we can retry on the
-      next event.
+.. function:: critical(msg, *args, **kwargs)
 
+   Logs a message with level :const:`CRITICAL` on the root logger. The arguments
+   are interpreted as for :func:`debug`.
 
-   .. method:: makeSocket()
 
-      This is a factory method which allows subclasses to define the precise
-      type of socket they want. The default implementation creates a TCP socket
-      (:const:`socket.SOCK_STREAM`).
+.. function:: exception(msg, *args)
 
+   Logs a message with level :const:`ERROR` on the root logger. The arguments are
+   interpreted as for :func:`debug`. Exception info is added to the logging
+   message. This function should only be called from an exception handler.
 
-   .. method:: makePickle(record)
+.. function:: log(level, msg, *args, **kwargs)
 
-      Pickles the record's attribute dictionary in binary format with a length
-      prefix, and returns it ready for transmission across the socket.
+   Logs a message with level *level* on the root logger. The other arguments are
+   interpreted as for :func:`debug`.
 
-      Note that pickles aren't completely secure. If you are concerned about
-      security, you may want to override this method to implement a more secure
-      mechanism. For example, you can sign pickles using HMAC and then verify
-      them on the receiving end, or alternatively you can disable unpickling of
-      global objects on the receiving end.
+   PLEASE NOTE: The above module-level functions which delegate to the root
+   logger should *not* be used in threads, in versions of Python earlier than
+   2.7.1 and 3.2, unless at least one handler has been added to the root
+   logger *before* the threads are started. These convenience functions call
+   :func:`basicConfig` to ensure that at least one handler is available; in
+   earlier versions of Python, this can (under rare circumstances) lead to
+   handlers being added multiple times to the root logger, which can in turn
+   lead to multiple messages for the same event.
 
-   .. method:: send(packet)
+.. function:: disable(lvl)
 
-      Send a pickled string *packet* to the socket. This function allows for
-      partial sends which can happen when the network is busy.
+   Provides an overriding level *lvl* for all loggers which takes precedence over
+   the logger's own level. When the need arises to temporarily throttle logging
+   output down across the whole application, this function can be useful. Its
+   effect is to disable all logging calls of severity *lvl* and below, so that
+   if you call it with a value of INFO, then all INFO and DEBUG events would be
+   discarded, whereas those of severity WARNING and above would be processed
+   according to the logger's effective level.
 
 
-.. _datagram-handler:
+.. function:: addLevelName(lvl, levelName)
 
-DatagramHandler
-^^^^^^^^^^^^^^^
+   Associates level *lvl* with text *levelName* in an internal dictionary, which is
+   used to map numeric levels to a textual representation, for example when a
+   :class:`Formatter` formats a message. This function can also be used to define
+   your own levels. The only constraints are that all levels used must be
+   registered using this function, levels should be positive integers and they
+   should increase in increasing order of severity.
 
-The :class:`DatagramHandler` class, located in the :mod:`logging.handlers`
-module, inherits from :class:`SocketHandler` to support sending logging messages
-over UDP sockets.
+   NOTE: If you are thinking of defining your own levels, please see the section
+   on :ref:`custom-levels`.
 
+.. function:: getLevelName(lvl)
 
-.. class:: DatagramHandler(host, port)
+   Returns the textual representation of logging level *lvl*. If the level is one
+   of the predefined levels :const:`CRITICAL`, :const:`ERROR`, :const:`WARNING`,
+   :const:`INFO` or :const:`DEBUG` then you get the corresponding string. If you
+   have associated levels with names using :func:`addLevelName` then the name you
+   have associated with *lvl* is returned. If a numeric value corresponding to one
+   of the defined levels is passed in, the corresponding string representation is
+   returned. Otherwise, the string 'Level %s' % lvl is returned.
 
-   Returns a new instance of the :class:`DatagramHandler` class intended to
-   communicate with a remote machine whose address is given by *host* and *port*.
 
+.. function:: makeLogRecord(attrdict)
 
-   .. method:: emit()
+   Creates and returns a new :class:`LogRecord` instance whose attributes are
+   defined by *attrdict*. This function is useful for taking a pickled
+   :class:`LogRecord` attribute dictionary, sent over a socket, and reconstituting
+   it as a :class:`LogRecord` instance at the receiving end.
 
-      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
-      packet. To unpickle the record at the receiving end into a
-      :class:`LogRecord`, use the :func:`makeLogRecord` function.
 
+.. function:: basicConfig(**kwargs)
 
-   .. method:: makeSocket()
+   Does basic configuration for the logging system by creating a
+   :class:`StreamHandler` with a default :class:`Formatter` and adding it to the
+   root logger. The functions :func:`debug`, :func:`info`, :func:`warning`,
+   :func:`error` and :func:`critical` will call :func:`basicConfig` automatically
+   if no handlers are defined for the root logger.
 
-      The factory method of :class:`SocketHandler` is here overridden to create
-      a UDP socket (:const:`socket.SOCK_DGRAM`).
+   This function does nothing if the root logger already has handlers
+   configured for it.
 
+   PLEASE NOTE: This function should be called from the main thread
+   before other threads are started. In versions of Python prior to
+   2.7.1 and 3.2, if this function is called from multiple threads,
+   it is possible (in rare circumstances) that a handler will be added
+   to the root logger more than once, leading to unexpected results
+   such as messages being duplicated in the log.
 
-   .. method:: send(s)
+   The following keyword arguments are supported.
 
-      Send a pickled string to a socket.
+   +--------------+---------------------------------------------+
+   | Format       | Description                                 |
+   +==============+=============================================+
+   | ``filename`` | Specifies that a FileHandler be created,    |
+   |              | using the specified filename, rather than a |
+   |              | StreamHandler.                              |
+   +--------------+---------------------------------------------+
+   | ``filemode`` | Specifies the mode to open the file, if     |
+   |              | filename is specified (if filemode is       |
+   |              | unspecified, it defaults to 'a').           |
+   +--------------+---------------------------------------------+
+   | ``format``   | Use the specified format string for the     |
+   |              | handler.                                    |
+   +--------------+---------------------------------------------+
+   | ``datefmt``  | Use the specified date/time format.         |
+   +--------------+---------------------------------------------+
+   | ``style``    | If ``format`` is specified, use this style  |
+   |              | for the format string. One of '%', '{' or   |
+   |              | '$' for %-formatting, :meth:`str.format` or |
+   |              | :class:`string.Template` respectively, and  |
+   |              | defaulting to '%' if not specified.         |
+   +--------------+---------------------------------------------+
+   | ``level``    | Set the root logger level to the specified  |
+   |              | level.                                      |
+   +--------------+---------------------------------------------+
+   | ``stream``   | Use the specified stream to initialize the  |
+   |              | StreamHandler. Note that this argument is   |
+   |              | incompatible with 'filename' - if both are  |
+   |              | present, 'stream' is ignored.               |
+   +--------------+---------------------------------------------+
 
+   .. versionchanged:: 3.2
+      The ``style`` argument was added.
 
-.. _syslog-handler:
 
-SysLogHandler
-^^^^^^^^^^^^^
+.. function:: shutdown()
 
-The :class:`SysLogHandler` class, located in the :mod:`logging.handlers` module,
-supports sending logging messages to a remote or local Unix syslog.
+   Informs the logging system to perform an orderly shutdown by flushing and
+   closing all handlers. This should be called at application exit and no
+   further use of the logging system should be made after this call.
 
 
-.. class:: SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
+.. function:: setLoggerClass(klass)
 
-   Returns a new instance of the :class:`SysLogHandler` class intended to
-   communicate with a remote Unix machine whose address is given by *address* in
-   the form of a ``(host, port)`` tuple.  If *address* is not specified,
-   ``('localhost', 514)`` is used.  The address is used to open a socket.  An
-   alternative to providing a ``(host, 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 *facility* is not specified,
-   :const:`LOG_USER` is used. The type of socket opened depends on the
-   *socktype* argument, which defaults to :const:`socket.SOCK_DGRAM` and thus
-   opens a UDP socket. To open a TCP socket (for use with the newer syslog
-   daemons such as rsyslog), specify a value of :const:`socket.SOCK_STREAM`.
+   Tells the logging system to use the class *klass* when instantiating a logger.
+   The class should define :meth:`__init__` such that only a name argument is
+   required, and the :meth:`__init__` should call :meth:`Logger.__init__`. This
+   function is typically called before any loggers are instantiated by applications
+   which need to use custom logger behavior.
 
-   Note that if your server is not listening on UDP port 514,
-   :class:`SysLogHandler` may appear not to work. In that case, check what
-   address you should be using for a domain socket - it's system dependent.
-   For example, on Linux it's usually "/dev/log" but on OS/X it's
-   "/var/run/syslog". You'll need to check your platform and use the
-   appropriate address (you may need to do this check at runtime if your
-   application needs to run on several platforms). On Windows, you pretty
-   much have to use the UDP option.
 
-   .. versionchanged:: 3.2
-      *socktype* was added.
+.. function:: setLogRecordFactory(factory)
 
+   Set a callable which is used to create a :class:`LogRecord`.
 
-   .. method:: close()
+   :param factory: The factory callable to be used to instantiate a log record.
 
-      Closes the socket to the remote host.
-
-
-   .. method:: emit(record)
-
-      The record is formatted, and then sent to the syslog server. If exception
-      information is present, it is *not* sent to the server.
-
-
-   .. method:: encodePriority(facility, priority)
-
-      Encodes the facility and priority into an integer. You can pass in strings
-      or integers - if strings are passed, internal mapping dictionaries are
-      used to convert them to integers.
-
-      The symbolic ``LOG_`` values are defined in :class:`SysLogHandler` and
-      mirror the values defined in the ``sys/syslog.h`` header file.
-
-      **Priorities**
-
-      +--------------------------+---------------+
-      | Name (string)            | Symbolic value|
-      +==========================+===============+
-      | ``alert``                | LOG_ALERT     |
-      +--------------------------+---------------+
-      | ``crit`` or ``critical`` | LOG_CRIT      |
-      +--------------------------+---------------+
-      | ``debug``                | LOG_DEBUG     |
-      +--------------------------+---------------+
-      | ``emerg`` or ``panic``   | LOG_EMERG     |
-      +--------------------------+---------------+
-      | ``err`` or ``error``     | LOG_ERR       |
-      +--------------------------+---------------+
-      | ``info``                 | LOG_INFO      |
-      +--------------------------+---------------+
-      | ``notice``               | LOG_NOTICE    |
-      +--------------------------+---------------+
-      | ``warn`` or ``warning``  | LOG_WARNING   |
-      +--------------------------+---------------+
-
-      **Facilities**
-
-      +---------------+---------------+
-      | Name (string) | Symbolic value|
-      +===============+===============+
-      | ``auth``      | LOG_AUTH      |
-      +---------------+---------------+
-      | ``authpriv``  | LOG_AUTHPRIV  |
-      +---------------+---------------+
-      | ``cron``      | LOG_CRON      |
-      +---------------+---------------+
-      | ``daemon``    | LOG_DAEMON    |
-      +---------------+---------------+
-      | ``ftp``       | LOG_FTP       |
-      +---------------+---------------+
-      | ``kern``      | LOG_KERN      |
-      +---------------+---------------+
-      | ``lpr``       | LOG_LPR       |
-      +---------------+---------------+
-      | ``mail``      | LOG_MAIL      |
-      +---------------+---------------+
-      | ``news``      | LOG_NEWS      |
-      +---------------+---------------+
-      | ``syslog``    | LOG_SYSLOG    |
-      +---------------+---------------+
-      | ``user``      | LOG_USER      |
-      +---------------+---------------+
-      | ``uucp``      | LOG_UUCP      |
-      +---------------+---------------+
-      | ``local0``    | LOG_LOCAL0    |
-      +---------------+---------------+
-      | ``local1``    | LOG_LOCAL1    |
-      +---------------+---------------+
-      | ``local2``    | LOG_LOCAL2    |
-      +---------------+---------------+
-      | ``local3``    | LOG_LOCAL3    |
-      +---------------+---------------+
-      | ``local4``    | LOG_LOCAL4    |
-      +---------------+---------------+
-      | ``local5``    | LOG_LOCAL5    |
-      +---------------+---------------+
-      | ``local6``    | LOG_LOCAL6    |
-      +---------------+---------------+
-      | ``local7``    | LOG_LOCAL7    |
-      +---------------+---------------+
-
-   .. method:: mapPriority(levelname)
-
-      Maps a logging level name to a syslog priority name.
-      You may need to override this if you are using custom levels, or
-      if the default algorithm is not suitable for your needs. The
-      default algorithm maps ``DEBUG``, ``INFO``, ``WARNING``, ``ERROR`` and
-      ``CRITICAL`` to the equivalent syslog names, and all other level
-      names to "warning".
-
-.. _nt-eventlog-handler:
-
-NTEventLogHandler
-^^^^^^^^^^^^^^^^^
-
-The :class:`NTEventLogHandler` class, located in the :mod:`logging.handlers`
-module, supports sending logging messages to a local Windows NT, Windows 2000 or
-Windows XP event log. Before you can use it, you need Mark Hammond's Win32
-extensions for Python installed.
-
-
-.. class:: NTEventLogHandler(appname, dllname=None, logtype='Application')
-
-   Returns a new instance of the :class:`NTEventLogHandler` class. The *appname* is
-   used to define the application name as it appears in the event log. An
-   appropriate registry entry is created using this name. The *dllname* should give
-   the fully qualified pathname of a .dll or .exe which contains message
-   definitions to hold in the log (if not specified, ``'win32service.pyd'`` is used
-   - this is installed with the Win32 extensions and contains some basic
-   placeholder message definitions. Note that use of these placeholders will make
-   your event logs big, as the entire message source is held in the log. If you
-   want slimmer logs, you have to pass in the name of your own .dll or .exe which
-   contains the message definitions you want to use in the event log). The
-   *logtype* is one of ``'Application'``, ``'System'`` or ``'Security'``, and
-   defaults to ``'Application'``.
-
-
-   .. method:: close()
-
-      At this point, you can remove the application name from the registry as a
-      source of event log entries. However, if you do this, you will not be able
-      to see the events as you intended in the Event Log Viewer - it needs to be
-      able to access the registry to get the .dll name. The current version does
-      not do this.
-
-
-   .. method:: emit(record)
-
-      Determines the message ID, event category and event type, and then logs
-      the message in the NT event log.
-
-
-   .. method:: getEventCategory(record)
-
-      Returns the event category for the record. Override this if you want to
-      specify your own categories. This version returns 0.
-
-
-   .. method:: getEventType(record)
-
-      Returns the event type for the record. Override this if you want to
-      specify your own types. This version does a mapping using the handler's
-      typemap attribute, which is set up in :meth:`__init__` to a dictionary
-      which contains mappings for :const:`DEBUG`, :const:`INFO`,
-      :const:`WARNING`, :const:`ERROR` and :const:`CRITICAL`. If you are using
-      your own levels, you will either need to override this method or place a
-      suitable dictionary in the handler's *typemap* attribute.
-
-
-   .. method:: getMessageID(record)
-
-      Returns the message ID for the record. If you are using your own messages,
-      you could do this by having the *msg* passed to the logger being an ID
-      rather than a format string. Then, in here, you could use a dictionary
-      lookup to get the message ID. This version returns 1, which is the base
-      message ID in :file:`win32service.pyd`.
-
-.. _smtp-handler:
-
-SMTPHandler
-^^^^^^^^^^^
-
-The :class:`SMTPHandler` class, located in the :mod:`logging.handlers` module,
-supports sending logging messages to an email address via SMTP.
-
-
-.. class:: SMTPHandler(mailhost, fromaddr, toaddrs, subject, credentials=None)
-
-   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
-   *toaddrs* should be a list of strings. To specify a non-standard SMTP port, use
-   the (host, port) tuple format for the *mailhost* argument. If you use a string,
-   the standard SMTP port is used. If your SMTP server requires authentication, you
-   can specify a (username, password) tuple for the *credentials* argument.
-
-
-   .. method:: emit(record)
-
-      Formats the record and sends it to the specified addressees.
-
-
-   .. method:: getSubject(record)
-
-      If you want to specify a subject line which is record-dependent, override
-      this method.
-
-.. _memory-handler:
-
-MemoryHandler
-^^^^^^^^^^^^^
-
-The :class:`MemoryHandler` class, located in the :mod:`logging.handlers` module,
-supports buffering of logging records in memory, periodically flushing them to a
-:dfn:`target` handler. Flushing occurs whenever the buffer is full, or when an
-event of a certain severity or greater is seen.
-
-:class:`MemoryHandler` is a subclass of the more general
-:class:`BufferingHandler`, which is an abstract class. This buffers logging
-records in memory. Whenever each record is added to the buffer, a check is made
-by calling :meth:`shouldFlush` to see if the buffer should be flushed.  If it
-should, then :meth:`flush` is expected to do the needful.
-
-
-.. class:: BufferingHandler(capacity)
-
-   Initializes the handler with a buffer of the specified capacity.
-
-
-   .. method:: emit(record)
-
-      Appends the record to the buffer. If :meth:`shouldFlush` returns true,
-      calls :meth:`flush` to process the buffer.
-
-
-   .. method:: flush()
-
-      You can override this to implement custom flushing behavior. This version
-      just zaps the buffer to empty.
-
-
-   .. method:: shouldFlush(record)
-
-      Returns true if the buffer is up to capacity. This method can be
-      overridden to implement custom flushing strategies.
-
-
-.. class:: MemoryHandler(capacity, flushLevel=ERROR, target=None)
-
-   Returns a new instance of the :class:`MemoryHandler` class. The instance is
-   initialized with a buffer size of *capacity*. If *flushLevel* is not specified,
-   :const:`ERROR` is used. If no *target* is specified, the target will need to be
-   set using :meth:`setTarget` before this handler does anything useful.
-
-
-   .. method:: close()
-
-      Calls :meth:`flush`, sets the target to :const:`None` and clears the
-      buffer.
-
-
-   .. method:: flush()
-
-      For a :class:`MemoryHandler`, flushing means just sending the buffered
-      records to the target, if there is one. The buffer is also cleared when
-      this happens. Override if you want different behavior.
-
-
-   .. method:: setTarget(target)
-
-      Sets the target handler for this handler.
-
-
-   .. method:: shouldFlush(record)
-
-      Checks for buffer full or a record at the *flushLevel* or higher.
-
-
-.. _http-handler:
-
-HTTPHandler
-^^^^^^^^^^^
-
-The :class:`HTTPHandler` class, located in the :mod:`logging.handlers` module,
-supports sending logging messages to a Web server, using either ``GET`` or
-``POST`` semantics.
-
-
-.. class:: HTTPHandler(host, url, method='GET', secure=False, credentials=None)
-
-   Returns a new instance of the :class:`HTTPHandler` class. The *host* can be
-   of the form ``host:port``, should you need to use a specific port number.
-   If no *method* is specified, ``GET`` is used. If *secure* is True, an HTTPS
-   connection will be used. If *credentials* is specified, it should be a
-   2-tuple consisting of userid and password, which will be placed in an HTTP
-   'Authorization' header using Basic authentication. If you specify
-   credentials, you should also specify secure=True so that your userid and
-   password are not passed in cleartext across the wire.
-
-
-   .. method:: emit(record)
-
-      Sends the record to the Web server as a percent-encoded dictionary.
-
-
-.. _queue-handler:
-
-
-QueueHandler
-^^^^^^^^^^^^
-
-The :class:`QueueHandler` class, located in the :mod:`logging.handlers` module,
-supports sending logging messages to a queue, such as those implemented in the
-:mod:`queue` or :mod:`multiprocessing` modules.
-
-Along with the :class:`QueueListener` class, :class:`QueueHandler` can be used
-to let handlers do their work on a separate thread from the one which does the
-logging. This is important in Web applications and also other service
-applications where threads servicing clients need to respond as quickly as
-possible, while any potentially slow operations (such as sending an email via
-:class:`SMTPHandler`) are done on a separate thread.
-
-.. class:: QueueHandler(queue)
-
-   Returns a new instance of the :class:`QueueHandler` class. The instance is
-   initialized with the queue to send messages to. The queue can be any queue-
-   like object; it's used as-is by the :meth:`enqueue` method, which needs
-   to know how to send messages to it.
-
-
-   .. method:: emit(record)
-
-      Enqueues the result of preparing the LogRecord.
-
-   .. method:: prepare(record)
-
-      Prepares a record for queuing. The object returned by this
-      method is enqueued.
-
-      The base implementation formats the record to merge the message
-      and arguments, and removes unpickleable items from the record
-      in-place.
-
-      You might want to override this method if you want to convert
-      the record to a dict or JSON string, or send a modified copy
-      of the record while leaving the original intact.
-
-   .. method:: enqueue(record)
-
-      Enqueues the record on the queue using ``put_nowait()``; you may
-      want to override this if you want to use blocking behaviour, or a
-      timeout, or a customised queue implementation.
-
-
-.. versionadded:: 3.2
-
-The :class:`QueueHandler` class was not present in previous versions.
-
-.. queue-listener:
-
-QueueListener
-^^^^^^^^^^^^^
-
-The :class:`QueueListener` class, located in the :mod:`logging.handlers`
-module, supports receiving logging messages from a queue, such as those
-implemented in the :mod:`queue` or :mod:`multiprocessing` modules. The
-messages are received from a queue in an internal thread and passed, on
-the same thread, to one or more handlers for processing.
-
-Along with the :class:`QueueHandler` class, :class:`QueueListener` can be used
-to let handlers do their work on a separate thread from the one which does the
-logging. This is important in Web applications and also other service
-applications where threads servicing clients need to respond as quickly as
-possible, while any potentially slow operations (such as sending an email via
-:class:`SMTPHandler`) are done on a separate thread.
-
-.. class:: QueueListener(queue, *handlers)
-
-   Returns a new instance of the :class:`QueueListener` class. The instance is
-   initialized with the queue to send messages to and a list of handlers which
-   will handle entries placed on the queue. The queue can be any queue-
-   like object; it's passed as-is to the :meth:`dequeue` method, which needs
-   to know how to get messages from it.
-
-   .. method:: dequeue(block)
-
-      Dequeues a record and return it, optionally blocking.
-
-      The base implementation uses ``get()``. You may want to override this
-      method if you want to use timeouts or work with custom queue
-      implementations.
-
-   .. method:: prepare(record)
-
-      Prepare a record for handling.
-
-      This implementation just returns the passed-in record. You may want to
-      override this method if you need to do any custom marshalling or
-      manipulation of the record before passing it to the handlers.
-
-   .. method:: handle(record)
-
-      Handle a record.
-
-      This just loops through the handlers offering them the record
-      to handle. The actual object passed to the handlers is that which
-      is returned from :meth:`prepare`.
-
-   .. method:: start()
-
-      Starts the listener.
-
-      This starts up a background thread to monitor the queue for
-      LogRecords to process.
-
-   .. method:: stop()
-
-      Stops the listener.
-
-      This asks the thread to terminate, and then waits for it to do so.
-      Note that if you don't call this before your application exits, there
-      may be some records still left on the queue, which won't be processed.
-
-.. versionadded:: 3.2
-
-The :class:`QueueListener` class was not present in previous versions.
-
-.. _zeromq-handlers:
-
-Subclassing QueueHandler
-^^^^^^^^^^^^^^^^^^^^^^^^
-
-You can use a :class:`QueueHandler` subclass to send messages to other kinds
-of queues, for example a ZeroMQ "publish" socket. In the example below,the
-socket is created separately and passed to the handler (as its 'queue')::
-
-    import zmq # using pyzmq, the Python binding for ZeroMQ
-    import json # for serializing records portably
-
-    ctx = zmq.Context()
-    sock = zmq.Socket(ctx, zmq.PUB) # or zmq.PUSH, or other suitable value
-    sock.bind('tcp://*:5556') # or wherever
-
-    class ZeroMQSocketHandler(QueueHandler):
-        def enqueue(self, record):
-            data = json.dumps(record.__dict__)
-            self.queue.send(data)
-
-    handler = ZeroMQSocketHandler(sock)
-
-
-Of course there are other ways of organizing this, for example passing in the
-data needed by the handler to create the socket::
-
-    class ZeroMQSocketHandler(QueueHandler):
-        def __init__(self, uri, socktype=zmq.PUB, ctx=None):
-            self.ctx = ctx or zmq.Context()
-            socket = zmq.Socket(self.ctx, socktype)
-            socket.bind(uri)
-            QueueHandler.__init__(self, socket)
-
-        def enqueue(self, record):
-            data = json.dumps(record.__dict__)
-            self.queue.send(data)
-
-        def close(self):
-            self.queue.close()
-
-Subclassing QueueListener
-^^^^^^^^^^^^^^^^^^^^^^^^^
-
-You can also subclass :class:`QueueListener` to get messages from other kinds
-of queues, for example a ZeroMQ "subscribe" socket. Here's an example::
-
-    class ZeroMQSocketListener(QueueListener):
-        def __init__(self, uri, *handlers, **kwargs):
-            self.ctx = kwargs.get('ctx') or zmq.Context()
-            socket = zmq.Socket(self.ctx, zmq.SUB)
-            socket.setsockopt(zmq.SUBSCRIBE, '') # subscribe to everything
-            socket.connect(uri)
-
-        def dequeue(self):
-            msg = self.queue.recv()
-            return logging.makeLogRecord(json.loads(msg))
-
-.. _formatter-objects:
-
-Formatter Objects
------------------
-
-.. currentmodule:: logging
-
-:class:`Formatter`\ s have the following attributes and methods. They are
-responsible for converting a :class:`LogRecord` to (usually) a string which can
-be interpreted by either a human or an external system. The base
-:class:`Formatter` allows a formatting string to be specified. If none is
-supplied, the default value of ``'%(message)s'`` is used.
-
-A Formatter can be initialized with a format string which makes use of knowledge
-of the :class:`LogRecord` attributes - such as the default value mentioned above
-making use of the fact that the user's message and arguments are pre-formatted
-into a :class:`LogRecord`'s *message* attribute.  This format string contains
-standard Python %-style mapping keys. See section :ref:`old-string-formatting`
-for more information on string formatting.
-
-Currently, the useful mapping keys in a :class:`LogRecord` are:
-
-+-------------------------+-----------------------------------------------+
-| Format                  | Description                                   |
-+=========================+===============================================+
-| ``%(name)s``            | Name of the logger (logging channel).         |
-+-------------------------+-----------------------------------------------+
-| ``%(levelno)s``         | Numeric logging level for the message         |
-|                         | (:const:`DEBUG`, :const:`INFO`,               |
-|                         | :const:`WARNING`, :const:`ERROR`,             |
-|                         | :const:`CRITICAL`).                           |
-+-------------------------+-----------------------------------------------+
-| ``%(levelname)s``       | Text logging level for the message            |
-|                         | (``'DEBUG'``, ``'INFO'``, ``'WARNING'``,      |
-|                         | ``'ERROR'``, ``'CRITICAL'``).                 |
-+-------------------------+-----------------------------------------------+
-| ``%(pathname)s``        | Full pathname of the source file where the    |
-|                         | logging call was issued (if available).       |
-+-------------------------+-----------------------------------------------+
-| ``%(filename)s``        | Filename portion of pathname.                 |
-+-------------------------+-----------------------------------------------+
-| ``%(module)s``          | Module (name portion of filename).            |
-+-------------------------+-----------------------------------------------+
-| ``%(funcName)s``        | Name of function containing the logging call. |
-+-------------------------+-----------------------------------------------+
-| ``%(lineno)d``          | Source line number where the logging call was |
-|                         | issued (if available).                        |
-+-------------------------+-----------------------------------------------+
-| ``%(created)f``         | Time when the :class:`LogRecord` was created  |
-|                         | (as returned by :func:`time.time`).           |
-+-------------------------+-----------------------------------------------+
-| ``%(relativeCreated)d`` | Time in milliseconds when the LogRecord was   |
-|                         | created, relative to the time the logging     |
-|                         | module was loaded.                            |
-+-------------------------+-----------------------------------------------+
-| ``%(asctime)s``         | Human-readable time when the                  |
-|                         | :class:`LogRecord` was created.  By default   |
-|                         | this is of the form "2003-07-08 16:49:45,896" |
-|                         | (the numbers after the comma are millisecond  |
-|                         | portion of the time).                         |
-+-------------------------+-----------------------------------------------+
-| ``%(msecs)d``           | Millisecond portion of the time when the      |
-|                         | :class:`LogRecord` was created.               |
-+-------------------------+-----------------------------------------------+
-| ``%(thread)d``          | Thread ID (if available).                     |
-+-------------------------+-----------------------------------------------+
-| ``%(threadName)s``      | Thread name (if available).                   |
-+-------------------------+-----------------------------------------------+
-| ``%(process)d``         | Process ID (if available).                    |
-+-------------------------+-----------------------------------------------+
-| ``%(processName)s``     | Process name (if available).                  |
-+-------------------------+-----------------------------------------------+
-| ``%(message)s``         | The logged message, computed as ``msg %       |
-|                         | args``.                                       |
-+-------------------------+-----------------------------------------------+
-
-
-.. class:: Formatter(fmt=None, datefmt=None)
-
-   Returns a new instance of the :class:`Formatter` class.  The instance is
-   initialized with a format string for the message as a whole, as well as a
-   format string for the date/time portion of a message.  If no *fmt* is
-   specified, ``'%(message)s'`` is used.  If no *datefmt* is specified, the
-   ISO8601 date format is used.
-
-   .. method:: format(record)
-
-      The record's attribute dictionary is used as the operand to a string
-      formatting operation. Returns the resulting string. Before formatting the
-      dictionary, a couple of preparatory steps are carried out. The *message*
-      attribute of the record is computed using *msg* % *args*. If the
-      formatting string contains ``'(asctime)'``, :meth:`formatTime` is called
-      to format the event time. If there is exception information, it is
-      formatted using :meth:`formatException` and appended to the message. Note
-      that the formatted exception information is cached in attribute
-      *exc_text*. This is useful because the exception information can be
-      pickled and sent across the wire, but you should be careful if you have
-      more than one :class:`Formatter` subclass which customizes the formatting
-      of exception information. In this case, you will have to clear the cached
-      value after a formatter has done its formatting, so that the next
-      formatter to handle the event doesn't use the cached value but
-      recalculates it afresh.
-
-
-   .. method:: formatTime(record, datefmt=None)
-
-      This method should be called from :meth:`format` by a formatter which
-      wants to make use of a formatted time. This method can be overridden in
-      formatters to provide for any specific requirement, but the basic behavior
-      is as follows: if *datefmt* (a string) is specified, it is used with
-      :func:`time.strftime` to format the creation time of the
-      record. Otherwise, the ISO8601 format is used.  The resulting string is
-      returned.
-
-
-   .. method:: formatException(exc_info)
-
-      Formats the specified exception information (a standard exception tuple as
-      returned by :func:`sys.exc_info`) as a string. This default implementation
-      just uses :func:`traceback.print_exception`. The resulting string is
-      returned.
-
-.. _filter:
-
-Filter Objects
---------------
-
-``Filters`` can be used by ``Handlers`` and ``Loggers`` for more sophisticated
-filtering than is provided by levels. The base filter class only allows events
-which are below a certain point in the logger hierarchy. For example, a filter
-initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C",
-"A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the
-empty string, all events are passed.
-
-
-.. class:: Filter(name='')
-
-   Returns an instance of the :class:`Filter` class. If *name* is specified, it
-   names a logger which, together with its children, will have its events allowed
-   through the filter. If *name* is the empty string, allows every event.
-
-
-   .. method:: filter(record)
-
-      Is the specified record to be logged? Returns zero for no, nonzero for
-      yes. If deemed appropriate, the record may be modified in-place by this
-      method.
-
-Note that filters attached to handlers are consulted whenever an event is
-emitted by the handler, whereas filters attached to loggers are consulted
-whenever an event is logged to the handler (using :meth:`debug`, :meth:`info`,
-etc.) This means that events which have been generated by descendant loggers
-will not be filtered by a logger's filter setting, unless the filter has also
-been applied to those descendant loggers.
-
-You don't actually need to subclass ``Filter``: you can pass any instance
-which has a ``filter`` method with the same semantics.
-
-.. versionchanged:: 3.2
-   You don't need to create specialized ``Filter`` classes, or use other
-   classes with a ``filter`` method: you can use a function (or other
-   callable) as a filter. The filtering logic will check to see if the filter
-   object has a ``filter`` attribute: if it does, it's assumed to be a
-   ``Filter`` and its :meth:`~Filter.filter` method is called. Otherwise, it's
-   assumed to be a callable and called with the record as the single
-   parameter. The returned value should conform to that returned by
-   :meth:`~Filter.filter`.
-
-Other uses for filters
-^^^^^^^^^^^^^^^^^^^^^^
-
-Although filters are used primarily to filter records based on more
-sophisticated criteria than levels, they get to see every record which is
-processed by the handler or logger they're attached to: this can be useful if
-you want to do things like counting how many records were processed by a
-particular logger or handler, or adding, changing or removing attributes in
-the LogRecord being processed. Obviously changing the LogRecord needs to be
-done with some care, but it does allow the injection of contextual information
-into logs (see :ref:`filters-contextual`).
-
-.. _log-record:
-
-LogRecord Objects
------------------
-
-:class:`LogRecord` instances are created automatically by the :class:`Logger`
-every time something is logged, and can be created manually via
-:func:`makeLogRecord` (for example, from a pickled event received over the
-wire).
-
-
-.. class:: LogRecord(name, lvl, pathname, lineno, msg, args, exc_info, func=None)
-
-   Contains all the information pertinent to the event being logged.
-
-   The primary information is passed in :attr:`msg` and :attr:`args`, which
-   are combined using ``msg % args`` to create the :attr:`message` field of the
-   record.
-
-   .. attribute:: args
-
-      Tuple of arguments to be used in formatting :attr:`msg`.
-
-   .. attribute:: exc_info
-
-      Exception tuple (à la :func:`sys.exc_info`) or ``None`` if no exception
-      information is available.
-
-   .. attribute:: func
-
-      Name of the function of origin (i.e. in which the logging call was made).
-
-   .. attribute:: lineno
-
-      Line number in the source file of origin.
-
-   .. attribute:: lvl
-
-      Numeric logging level.
-
-   .. attribute:: message
-
-      Bound to the result of :meth:`getMessage` when
-      :meth:`Formatter.format(record)<Formatter.format>` is invoked.
-
-   .. attribute:: msg
-
-      User-supplied :ref:`format string<string-formatting>` or arbitrary object
-      (see :ref:`arbitrary-object-messages`) used in :meth:`getMessage`.
-
-   .. attribute:: name
-
-      Name of the logger that emitted the record.
-
-   .. attribute:: pathname
-
-      Absolute pathname of the source file of origin.
-
-   .. method:: getMessage()
-
-      Returns the message for this :class:`LogRecord` instance after merging any
-      user-supplied arguments with the message. If the user-supplied message
-      argument to the logging call is not a string, :func:`str` is called on it to
-      convert it to a string. This allows use of user-defined classes as
-      messages, whose ``__str__`` method can return the actual format string to
-      be used.
-
-.. _logger-adapter:
-
-LoggerAdapter Objects
----------------------
-
-:class:`LoggerAdapter` instances are used to conveniently pass contextual
-information into logging calls. For a usage example , see the section on
-`adding contextual information to your logging output`__.
-
-__ context-info_
-
-.. class:: LoggerAdapter(logger, extra)
-
-  Returns an instance of :class:`LoggerAdapter` initialized with an
-  underlying :class:`Logger` instance and a dict-like object.
-
-  .. method:: process(msg, kwargs)
-
-    Modifies the message and/or keyword arguments passed to a logging call in
-    order to insert contextual information. This implementation takes the object
-    passed as *extra* to the constructor and adds it to *kwargs* using key
-    'extra'. The return value is a (*msg*, *kwargs*) tuple which has the
-    (possibly modified) versions of the arguments passed in.
-
-In addition to the above, :class:`LoggerAdapter` supports the following
-methods of :class:`Logger`, i.e. :meth:`debug`, :meth:`info`, :meth:`warning`,
-:meth:`error`, :meth:`exception`, :meth:`critical`, :meth:`log`,
-:meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel`,
-:meth:`hasHandlers`. These methods have the same signatures as their
-counterparts in :class:`Logger`, so you can use the two types of instances
-interchangeably.
-
-.. versionchanged:: 3.2
-   The :meth:`isEnabledFor`, :meth:`getEffectiveLevel`, :meth:`setLevel` and
-   :meth:`hasHandlers` methods were added to :class:`LoggerAdapter`.  These
-   methods delegate to the underlying logger.
-
-
-Thread Safety
--------------
-
-The logging module is intended to be thread-safe without any special work
-needing to be done by its clients. It achieves this though using threading
-locks; there is one lock to serialize access to the module's shared data, and
-each handler also creates a lock to serialize access to its underlying I/O.
-
-If you are implementing asynchronous signal handlers using the :mod:`signal`
-module, you may not be able to use logging from within such handlers. This is
-because lock implementations in the :mod:`threading` module are not always
-re-entrant, and so cannot be invoked from such signal handlers.
+   .. versionadded:: 3.2
+      This function has been provided, along with :func:`getLogRecordFactory`, to
+      allow developers more control over how the :class:`LogRecord` representing
+      a logging event is constructed.
+
+   The factory has the following signature:
+
+   ``factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)``
+
+      :name: The logger name.
+      :level: The logging level (numeric).
+      :fn: The full pathname of the file where the logging call was made.
+      :lno: The line number in the file where the logging call was made.
+      :msg: The logging message.
+      :args: The arguments for the logging message.
+      :exc_info: An exception tuple, or None.
+      :func: The name of the function or method which invoked the logging
+             call.
+      :sinfo: A stack traceback such as is provided by
+              :func:`traceback.print_stack`, showing the call hierarchy.
+      :kwargs: Additional keyword arguments.
 
 
 Integration with the warnings module
@@ -3253,842 +1042,28 @@
    If *capture* is ``True``, warnings issued by the :mod:`warnings` module will
    be redirected to the logging system. Specifically, a warning will be
    formatted using :func:`warnings.formatwarning` and the resulting string
-   logged to a logger named "py.warnings" with a severity of `WARNING`.
+   logged to a logger named 'py.warnings' with a severity of `WARNING`.
 
    If *capture* is ``False``, the redirection of warnings to the logging system
    will stop, and warnings will be redirected to their original destinations
    (i.e. those in effect before `captureWarnings(True)` was called).
 
 
-Configuration
--------------
-
-
-.. _logging-config-api:
-
-Configuration functions
-^^^^^^^^^^^^^^^^^^^^^^^
-
-The following functions configure the logging module. They are located in the
-:mod:`logging.config` module.  Their use is optional --- you can configure the
-logging module using these functions or by making calls to the main API (defined
-in :mod:`logging` itself) and defining handlers which are declared either in
-:mod:`logging` or :mod:`logging.handlers`.
-
-.. function:: dictConfig(config)
-
-    Takes the logging configuration from a dictionary.  The contents of
-    this dictionary are described in :ref:`logging-config-dictschema`
-    below.
-
-    If an error is encountered during configuration, this function will
-    raise a :exc:`ValueError`, :exc:`TypeError`, :exc:`AttributeError`
-    or :exc:`ImportError` with a suitably descriptive message.  The
-    following is a (possibly incomplete) list of conditions which will
-    raise an error:
-
-    * A ``level`` which is not a string or which is a string not
-      corresponding to an actual logging level.
-    * A ``propagate`` value which is not a boolean.
-    * An id which does not have a corresponding destination.
-    * A non-existent handler id found during an incremental call.
-    * An invalid logger name.
-    * Inability to resolve to an internal or external object.
-
-    Parsing is performed by the :class:`DictConfigurator` class, whose
-    constructor is passed the dictionary used for configuration, and
-    has a :meth:`configure` method.  The :mod:`logging.config` module
-    has a callable attribute :attr:`dictConfigClass`
-    which is initially set to :class:`DictConfigurator`.
-    You can replace the value of :attr:`dictConfigClass` with a
-    suitable implementation of your own.
-
-    :func:`dictConfig` calls :attr:`dictConfigClass` passing
-    the specified dictionary, and then calls the :meth:`configure` method on
-    the returned object to put the configuration into effect::
-
-          def dictConfig(config):
-              dictConfigClass(config).configure()
-
-    For example, a subclass of :class:`DictConfigurator` could call
-    ``DictConfigurator.__init__()`` in its own :meth:`__init__()`, then
-    set up custom prefixes which would be usable in the subsequent
-    :meth:`configure` call. :attr:`dictConfigClass` would be bound to
-    this new subclass, and then :func:`dictConfig` could be called exactly as
-    in the default, uncustomized state.
-
-.. function:: fileConfig(fname[, defaults])
-
-   Reads the logging configuration from a :mod:`configparser`\-format file named
-   *fname*. This function can be called several times from an application,
-   allowing an end user to select from various pre-canned
-   configurations (if the developer provides a mechanism to present the choices
-   and load the chosen configuration). Defaults to be passed to the ConfigParser
-   can be specified in the *defaults* argument.
-
-
-.. function:: listen(port=DEFAULT_LOGGING_CONFIG_PORT)
-
-   Starts up a socket server on the specified port, and listens for new
-   configurations. If no port is specified, the module's default
-   :const:`DEFAULT_LOGGING_CONFIG_PORT` is used. Logging configurations will be
-   sent as a file suitable for processing by :func:`fileConfig`. Returns a
-   :class:`Thread` instance on which you can call :meth:`start` to start the
-   server, and which you can :meth:`join` when appropriate. To stop the server,
-   call :func:`stopListening`.
-
-   To send a configuration to the socket, read in the configuration file and
-   send it to the socket as a string of bytes preceded by a four-byte length
-   string packed in binary using ``struct.pack('>L', n)``.
-
-
-.. function:: stopListening()
-
-   Stops the listening server which was created with a call to :func:`listen`.
-   This is typically called before calling :meth:`join` on the return value from
-   :func:`listen`.
-
-
-.. _logging-config-dictschema:
-
-Configuration dictionary schema
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-Describing a logging configuration requires listing the various
-objects to create and the connections between them; for example, you
-may create a handler named "console" and then say that the logger
-named "startup" will send its messages to the "console" handler.
-These objects aren't limited to those provided by the :mod:`logging`
-module because you might write your own formatter or handler class.
-The parameters to these classes may also need to include external
-objects such as ``sys.stderr``.  The syntax for describing these
-objects and connections is defined in :ref:`logging-config-dict-connections`
-below.
-
-Dictionary Schema Details
-"""""""""""""""""""""""""
-
-The dictionary passed to :func:`dictConfig` must contain the following
-keys:
-
-* *version* - to be set to an integer value representing the schema
-  version.  The only valid value at present is 1, but having this key
-  allows the schema to evolve while still preserving backwards
-  compatibility.
-
-All other keys are optional, but if present they will be interpreted
-as described below.  In all cases below where a 'configuring dict' is
-mentioned, it will be checked for the special ``'()'`` key to see if a
-custom instantiation is required.  If so, the mechanism described in
-:ref:`logging-config-dict-userdef` below is used to create an instance;
-otherwise, the context is used to determine what to instantiate.
-
-* *formatters* - the corresponding value will be a dict in which each
-  key is a formatter id and each value is a dict describing how to
-  configure the corresponding Formatter instance.
-
-  The configuring dict is searched for keys ``format`` and ``datefmt``
-  (with defaults of ``None``) and these are used to construct a
-  :class:`logging.Formatter` instance.
-
-* *filters* - the corresponding value will be a dict in which each key
-  is a filter id and each value is a dict describing how to configure
-  the corresponding Filter instance.
-
-  The configuring dict is searched for the key ``name`` (defaulting to the
-  empty string) and this is used to construct a :class:`logging.Filter`
-  instance.
-
-* *handlers* - the corresponding value will be a dict in which each
-  key is a handler id and each value is a dict describing how to
-  configure the corresponding Handler instance.
-
-  The configuring dict is searched for the following keys:
-
-  * ``class`` (mandatory).  This is the fully qualified name of the
-    handler class.
-
-  * ``level`` (optional).  The level of the handler.
-
-  * ``formatter`` (optional).  The id of the formatter for this
-    handler.
-
-  * ``filters`` (optional).  A list of ids of the filters for this
-    handler.
-
-  All *other* keys are passed through as keyword arguments to the
-  handler's constructor.  For example, given the snippet::
-
-      handlers:
-        console:
-          class : logging.StreamHandler
-          formatter: brief
-          level   : INFO
-          filters: [allow_foo]
-          stream  : ext://sys.stdout
-        file:
-          class : logging.handlers.RotatingFileHandler
-          formatter: precise
-          filename: logconfig.log
-          maxBytes: 1024
-          backupCount: 3
-
-  the handler with id ``console`` is instantiated as a
-  :class:`logging.StreamHandler`, using ``sys.stdout`` as the underlying
-  stream.  The handler with id ``file`` is instantiated as a
-  :class:`logging.handlers.RotatingFileHandler` with the keyword arguments
-  ``filename='logconfig.log', maxBytes=1024, backupCount=3``.
-
-* *loggers* - the corresponding value will be a dict in which each key
-  is a logger name and each value is a dict describing how to
-  configure the corresponding Logger instance.
-
-  The configuring dict is searched for the following keys:
-
-  * ``level`` (optional).  The level of the logger.
-
-  * ``propagate`` (optional).  The propagation setting of the logger.
-
-  * ``filters`` (optional).  A list of ids of the filters for this
-    logger.
-
-  * ``handlers`` (optional).  A list of ids of the handlers for this
-    logger.
-
-  The specified loggers will be configured according to the level,
-  propagation, filters and handlers specified.
-
-* *root* - this will be the configuration for the root logger.
-  Processing of the configuration will be as for any logger, except
-  that the ``propagate`` setting will not be applicable.
-
-* *incremental* - whether the configuration is to be interpreted as
-  incremental to the existing configuration.  This value defaults to
-  ``False``, which means that the specified configuration replaces the
-  existing configuration with the same semantics as used by the
-  existing :func:`fileConfig` API.
-
-  If the specified value is ``True``, the configuration is processed
-  as described in the section on :ref:`logging-config-dict-incremental`.
-
-* *disable_existing_loggers* - whether any existing loggers are to be
-  disabled. This setting mirrors the parameter of the same name in
-  :func:`fileConfig`. If absent, this parameter defaults to ``True``.
-  This value is ignored if *incremental* is ``True``.
-
-.. _logging-config-dict-incremental:
-
-Incremental Configuration
-"""""""""""""""""""""""""
-
-It is difficult to provide complete flexibility for incremental
-configuration.  For example, because objects such as filters
-and formatters are anonymous, once a configuration is set up, it is
-not possible to refer to such anonymous objects when augmenting a
-configuration.
-
-Furthermore, there is not a compelling case for arbitrarily altering
-the object graph of loggers, handlers, filters, formatters at
-run-time, once a configuration is set up; the verbosity of loggers and
-handlers can be controlled just by setting levels (and, in the case of
-loggers, propagation flags).  Changing the object graph arbitrarily in
-a safe way is problematic in a multi-threaded environment; while not
-impossible, the benefits are not worth the complexity it adds to the
-implementation.
-
-Thus, when the ``incremental`` key of a configuration dict is present
-and is ``True``, the system will completely ignore any ``formatters`` and
-``filters`` entries, and process only the ``level``
-settings in the ``handlers`` entries, and the ``level`` and
-``propagate`` settings in the ``loggers`` and ``root`` entries.
-
-Using a value in the configuration dict lets configurations to be sent
-over the wire as pickled dicts to a socket listener. Thus, the logging
-verbosity of a long-running application can be altered over time with
-no need to stop and restart the application.
-
-.. _logging-config-dict-connections:
-
-Object connections
-""""""""""""""""""
-
-The schema describes a set of logging objects - loggers,
-handlers, formatters, filters - which are connected to each other in
-an object graph.  Thus, the schema needs to represent connections
-between the objects.  For example, say that, once configured, a
-particular logger has attached to it a particular handler.  For the
-purposes of this discussion, we can say that the logger represents the
-source, and the handler the destination, of a connection between the
-two.  Of course in the configured objects this is represented by the
-logger holding a reference to the handler.  In the configuration dict,
-this is done by giving each destination object an id which identifies
-it unambiguously, and then using the id in the source object's
-configuration to indicate that a connection exists between the source
-and the destination object with that id.
-
-So, for example, consider the following YAML snippet::
-
-    formatters:
-      brief:
-        # configuration for formatter with id 'brief' goes here
-      precise:
-        # configuration for formatter with id 'precise' goes here
-    handlers:
-      h1: #This is an id
-       # configuration of handler with id 'h1' goes here
-       formatter: brief
-      h2: #This is another id
-       # configuration of handler with id 'h2' goes here
-       formatter: precise
-    loggers:
-      foo.bar.baz:
-        # other configuration for logger 'foo.bar.baz'
-        handlers: [h1, h2]
-
-(Note: YAML used here because it's a little more readable than the
-equivalent Python source form for the dictionary.)
-
-The ids for loggers are the logger names which would be used
-programmatically to obtain a reference to those loggers, e.g.
-``foo.bar.baz``.  The ids for Formatters and Filters can be any string
-value (such as ``brief``, ``precise`` above) and they are transient,
-in that they are only meaningful for processing the configuration
-dictionary and used to determine connections between objects, and are
-not persisted anywhere when the configuration call is complete.
-
-The above snippet indicates that logger named ``foo.bar.baz`` should
-have two handlers attached to it, which are described by the handler
-ids ``h1`` and ``h2``. The formatter for ``h1`` is that described by id
-``brief``, and the formatter for ``h2`` is that described by id
-``precise``.
-
-
-.. _logging-config-dict-userdef:
-
-User-defined objects
-""""""""""""""""""""
-
-The schema supports user-defined objects for handlers, filters and
-formatters.  (Loggers do not need to have different types for
-different instances, so there is no support in this configuration
-schema for user-defined logger classes.)
-
-Objects to be configured are described by dictionaries
-which detail their configuration.  In some places, the logging system
-will be able to infer from the context how an object is to be
-instantiated, but when a user-defined object is to be instantiated,
-the system will not know how to do this.  In order to provide complete
-flexibility for user-defined object instantiation, the user needs
-to provide a 'factory' - a callable which is called with a
-configuration dictionary and which returns the instantiated object.
-This is signalled by an absolute import path to the factory being
-made available under the special key ``'()'``.  Here's a concrete
-example::
-
-    formatters:
-      brief:
-        format: '%(message)s'
-      default:
-        format: '%(asctime)s %(levelname)-8s %(name)-15s %(message)s'
-        datefmt: '%Y-%m-%d %H:%M:%S'
-      custom:
-          (): my.package.customFormatterFactory
-          bar: baz
-          spam: 99.9
-          answer: 42
-
-The above YAML snippet defines three formatters.  The first, with id
-``brief``, is a standard :class:`logging.Formatter` instance with the
-specified format string.  The second, with id ``default``, has a
-longer format and also defines the time format explicitly, and will
-result in a :class:`logging.Formatter` initialized with those two format
-strings.  Shown in Python source form, the ``brief`` and ``default``
-formatters have configuration sub-dictionaries::
-
-    {
-      'format' : '%(message)s'
-    }
-
-and::
-
-    {
-      'format' : '%(asctime)s %(levelname)-8s %(name)-15s %(message)s',
-      'datefmt' : '%Y-%m-%d %H:%M:%S'
-    }
-
-respectively, and as these dictionaries do not contain the special key
-``'()'``, the instantiation is inferred from the context: as a result,
-standard :class:`logging.Formatter` instances are created.  The
-configuration sub-dictionary for the third formatter, with id
-``custom``, is::
-
-  {
-    '()' : 'my.package.customFormatterFactory',
-    'bar' : 'baz',
-    'spam' : 99.9,
-    'answer' : 42
-  }
-
-and this contains the special key ``'()'``, which means that
-user-defined instantiation is wanted.  In this case, the specified
-factory callable will be used. If it is an actual callable it will be
-used directly - otherwise, if you specify a string (as in the example)
-the actual callable will be located using normal import mechanisms.
-The callable will be called with the **remaining** items in the
-configuration sub-dictionary as keyword arguments.  In the above
-example, the formatter with id ``custom`` will be assumed to be
-returned by the call::
-
-    my.package.customFormatterFactory(bar='baz', spam=99.9, answer=42)
-
-The key ``'()'`` has been used as the special key because it is not a
-valid keyword parameter name, and so will not clash with the names of
-the keyword arguments used in the call.  The ``'()'`` also serves as a
-mnemonic that the corresponding value is a callable.
-
-
-.. _logging-config-dict-externalobj:
-
-Access to external objects
-""""""""""""""""""""""""""
-
-There are times where a configuration needs to refer to objects
-external to the configuration, for example ``sys.stderr``.  If the
-configuration dict is constructed using Python code, this is
-straightforward, but a problem arises when the configuration is
-provided via a text file (e.g. JSON, YAML).  In a text file, there is
-no standard way to distinguish ``sys.stderr`` from the literal string
-``'sys.stderr'``.  To facilitate this distinction, the configuration
-system looks for certain special prefixes in string values and
-treat them specially.  For example, if the literal string
-``'ext://sys.stderr'`` is provided as a value in the configuration,
-then the ``ext://`` will be stripped off and the remainder of the
-value processed using normal import mechanisms.
-
-The handling of such prefixes is done in a way analogous to protocol
-handling: there is a generic mechanism to look for prefixes which
-match the regular expression ``^(?P<prefix>[a-z]+)://(?P<suffix>.*)$``
-whereby, if the ``prefix`` is recognised, the ``suffix`` is processed
-in a prefix-dependent manner and the result of the processing replaces
-the string value.  If the prefix is not recognised, then the string
-value will be left as-is.
-
-
-.. _logging-config-dict-internalobj:
-
-Access to internal objects
-""""""""""""""""""""""""""
-
-As well as external objects, there is sometimes also a need to refer
-to objects in the configuration.  This will be done implicitly by the
-configuration system for things that it knows about.  For example, the
-string value ``'DEBUG'`` for a ``level`` in a logger or handler will
-automatically be converted to the value ``logging.DEBUG``, and the
-``handlers``, ``filters`` and ``formatter`` entries will take an
-object id and resolve to the appropriate destination object.
-
-However, a more generic mechanism is needed for user-defined
-objects which are not known to the :mod:`logging` module.  For
-example, consider :class:`logging.handlers.MemoryHandler`, which takes
-a ``target`` argument which is another handler to delegate to. Since
-the system already knows about this class, then in the configuration,
-the given ``target`` just needs to be the object id of the relevant
-target handler, and the system will resolve to the handler from the
-id.  If, however, a user defines a ``my.package.MyHandler`` which has
-an ``alternate`` handler, the configuration system would not know that
-the ``alternate`` referred to a handler.  To cater for this, a generic
-resolution system allows the user to specify::
-
-    handlers:
-      file:
-        # configuration of file handler goes here
-
-      custom:
-        (): my.package.MyHandler
-        alternate: cfg://handlers.file
-
-The literal string ``'cfg://handlers.file'`` will be resolved in an
-analogous way to strings with the ``ext://`` prefix, but looking
-in the configuration itself rather than the import namespace.  The
-mechanism allows access by dot or by index, in a similar way to
-that provided by ``str.format``.  Thus, given the following snippet::
-
-    handlers:
-      email:
-        class: logging.handlers.SMTPHandler
-        mailhost: localhost
-        fromaddr: my_app at domain.tld
-        toaddrs:
-          - support_team at domain.tld
-          - dev_team at domain.tld
-        subject: Houston, we have a problem.
-
-in the configuration, the string ``'cfg://handlers'`` would resolve to
-the dict with key ``handlers``, the string ``'cfg://handlers.email``
-would resolve to the dict with key ``email`` in the ``handlers`` dict,
-and so on.  The string ``'cfg://handlers.email.toaddrs[1]`` would
-resolve to ``'dev_team.domain.tld'`` and the string
-``'cfg://handlers.email.toaddrs[0]'`` would resolve to the value
-``'support_team at domain.tld'``. The ``subject`` value could be accessed
-using either ``'cfg://handlers.email.subject'`` or, equivalently,
-``'cfg://handlers.email[subject]'``.  The latter form only needs to be
-used if the key contains spaces or non-alphanumeric characters.  If an
-index value consists only of decimal digits, access will be attempted
-using the corresponding integer value, falling back to the string
-value if needed.
-
-Given a string ``cfg://handlers.myhandler.mykey.123``, this will
-resolve to ``config_dict['handlers']['myhandler']['mykey']['123']``.
-If the string is specified as ``cfg://handlers.myhandler.mykey[123]``,
-the system will attempt to retrieve the value from
-``config_dict['handlers']['myhandler']['mykey'][123]``, and fall back
-to ``config_dict['handlers']['myhandler']['mykey']['123']`` if that
-fails.
-
-.. _logging-config-fileformat:
-
-Configuration file format
-^^^^^^^^^^^^^^^^^^^^^^^^^
-
-The configuration file format understood by :func:`fileConfig` is based on
-:mod:`configparser` functionality. The file must contain sections called
-``[loggers]``, ``[handlers]`` and ``[formatters]`` which identify by name the
-entities of each type which are defined in the file. For each such entity, there
-is a separate section which identifies how that entity is configured.  Thus, for
-a logger named ``log01`` in the ``[loggers]`` section, the relevant
-configuration details are held in a section ``[logger_log01]``. Similarly, a
-handler called ``hand01`` in the ``[handlers]`` section will have its
-configuration held in a section called ``[handler_hand01]``, while a formatter
-called ``form01`` in the ``[formatters]`` section will have its configuration
-specified in a section called ``[formatter_form01]``. The root logger
-configuration must be specified in a section called ``[logger_root]``.
-
-Examples of these sections in the file are given below. ::
-
-   [loggers]
-   keys=root,log02,log03,log04,log05,log06,log07
-
-   [handlers]
-   keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
-
-   [formatters]
-   keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
-
-The root logger must specify a level and a list of handlers. An example of a
-root logger section is given below. ::
-
-   [logger_root]
-   level=NOTSET
-   handlers=hand01
-
-The ``level`` entry can be one of ``DEBUG, INFO, WARNING, ERROR, CRITICAL`` or
-``NOTSET``. For the root logger only, ``NOTSET`` means that all messages will be
-logged. Level values are :func:`eval`\ uated in the context of the ``logging``
-package's namespace.
-
-The ``handlers`` entry is a comma-separated list of handler names, which must
-appear in the ``[handlers]`` section. These names must appear in the
-``[handlers]`` section and have corresponding sections in the configuration
-file.
-
-For loggers other than the root logger, some additional information is required.
-This is illustrated by the following example. ::
-
-   [logger_parser]
-   level=DEBUG
-   handlers=hand01
-   propagate=1
-   qualname=compiler.parser
-
-The ``level`` and ``handlers`` entries are interpreted as for the root logger,
-except that if a non-root logger's level is specified as ``NOTSET``, the system
-consults loggers higher up the hierarchy to determine the effective level of the
-logger. The ``propagate`` entry is set to 1 to indicate that messages must
-propagate to handlers higher up the logger hierarchy from this logger, or 0 to
-indicate that messages are **not** propagated to handlers up the hierarchy. The
-``qualname`` entry is the hierarchical channel name of the logger, that is to
-say the name used by the application to get the logger.
-
-Sections which specify handler configuration are exemplified by the following.
-::
-
-   [handler_hand01]
-   class=StreamHandler
-   level=NOTSET
-   formatter=form01
-   args=(sys.stdout,)
-
-The ``class`` entry indicates the handler's class (as determined by :func:`eval`
-in the ``logging`` package's namespace). The ``level`` is interpreted as for
-loggers, and ``NOTSET`` is taken to mean "log everything".
-
-The ``formatter`` entry indicates the key name of the formatter for this
-handler. If blank, a default formatter (``logging._defaultFormatter``) is used.
-If a name is specified, it must appear in the ``[formatters]`` section and have
-a corresponding section in the configuration file.
-
-The ``args`` entry, when :func:`eval`\ uated in the context of the ``logging``
-package's namespace, is the list of arguments to the constructor for the handler
-class. Refer to the constructors for the relevant handlers, or to the examples
-below, to see how typical entries are constructed. ::
-
-   [handler_hand02]
-   class=FileHandler
-   level=DEBUG
-   formatter=form02
-   args=('python.log', 'w')
-
-   [handler_hand03]
-   class=handlers.SocketHandler
-   level=INFO
-   formatter=form03
-   args=('localhost', handlers.DEFAULT_TCP_LOGGING_PORT)
-
-   [handler_hand04]
-   class=handlers.DatagramHandler
-   level=WARN
-   formatter=form04
-   args=('localhost', handlers.DEFAULT_UDP_LOGGING_PORT)
-
-   [handler_hand05]
-   class=handlers.SysLogHandler
-   level=ERROR
-   formatter=form05
-   args=(('localhost', handlers.SYSLOG_UDP_PORT), handlers.SysLogHandler.LOG_USER)
-
-   [handler_hand06]
-   class=handlers.NTEventLogHandler
-   level=CRITICAL
-   formatter=form06
-   args=('Python Application', '', 'Application')
-
-   [handler_hand07]
-   class=handlers.SMTPHandler
-   level=WARN
-   formatter=form07
-   args=('localhost', 'from at abc', ['user1 at abc', 'user2 at xyz'], 'Logger Subject')
-
-   [handler_hand08]
-   class=handlers.MemoryHandler
-   level=NOTSET
-   formatter=form08
-   target=
-   args=(10, ERROR)
-
-   [handler_hand09]
-   class=handlers.HTTPHandler
-   level=NOTSET
-   formatter=form09
-   args=('localhost:9022', '/log', 'GET')
-
-Sections which specify formatter configuration are typified by the following. ::
-
-   [formatter_form01]
-   format=F1 %(asctime)s %(levelname)s %(message)s
-   datefmt=
-   class=logging.Formatter
-
-The ``format`` entry is the overall format string, and the ``datefmt`` entry is
-the :func:`strftime`\ -compatible date/time format string.  If empty, the
-package substitutes ISO8601 format date/times, which is almost equivalent to
-specifying the date format string ``"%Y-%m-%d %H:%M:%S"``.  The ISO8601 format
-also specifies milliseconds, which are appended to the result of using the above
-format string, with a comma separator.  An example time in ISO8601 format is
-``2003-01-23 00:29:50,411``.
-
-The ``class`` entry is optional.  It indicates the name of the formatter's class
-(as a dotted module and class name.)  This option is useful for instantiating a
-:class:`Formatter` subclass.  Subclasses of :class:`Formatter` can present
-exception tracebacks in an expanded or condensed format.
-
-
-Configuration server example
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-Here is an example of a module using the logging configuration server::
-
-    import logging
-    import logging.config
-    import time
-    import os
-
-    # read initial config file
-    logging.config.fileConfig("logging.conf")
-
-    # create and start listener on port 9999
-    t = logging.config.listen(9999)
-    t.start()
-
-    logger = logging.getLogger("simpleExample")
-
-    try:
-        # loop through logging calls to see the difference
-        # new configurations make, until Ctrl+C is pressed
-        while True:
-            logger.debug("debug message")
-            logger.info("info message")
-            logger.warn("warn message")
-            logger.error("error message")
-            logger.critical("critical message")
-            time.sleep(5)
-    except KeyboardInterrupt:
-        # cleanup
-        logging.config.stopListening()
-        t.join()
-
-And here is a script that takes a filename and sends that file to the server,
-properly preceded with the binary-encoded length, as the new logging
-configuration::
-
-    #!/usr/bin/env python
-    import socket, sys, struct
-
-    data_to_send = open(sys.argv[1], "r").read()
-
-    HOST = 'localhost'
-    PORT = 9999
-    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-    print("connecting...")
-    s.connect((HOST, PORT))
-    print("sending config...")
-    s.send(struct.pack(">L", len(data_to_send)))
-    s.send(data_to_send)
-    s.close()
-    print("complete")
+.. seealso::
 
+   Module :mod:`logging.config`
+      Configuration API for the logging module.
 
-More examples
--------------
+   Module :mod:`logging.handlers`
+      Useful handlers included with the logging module.
 
-Multiple handlers and formatters
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+   :pep:`282` - A Logging System
+      The proposal which described this feature for inclusion in the Python standard
+      library.
 
-Loggers are plain Python objects.  The :func:`addHandler` method has no minimum
-or maximum quota for the number of handlers you may add.  Sometimes it will be
-beneficial for an application to log all messages of all severities to a text
-file while simultaneously logging errors or above to the console.  To set this
-up, simply configure the appropriate handlers.  The logging calls in the
-application code will remain unchanged.  Here is a slight modification to the
-previous simple module-based configuration example::
-
-    import logging
-
-    logger = logging.getLogger("simple_example")
-    logger.setLevel(logging.DEBUG)
-    # create file handler which logs even debug messages
-    fh = logging.FileHandler("spam.log")
-    fh.setLevel(logging.DEBUG)
-    # create console handler with a higher log level
-    ch = logging.StreamHandler()
-    ch.setLevel(logging.ERROR)
-    # create formatter and add it to the handlers
-    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
-    ch.setFormatter(formatter)
-    fh.setFormatter(formatter)
-    # add the handlers to logger
-    logger.addHandler(ch)
-    logger.addHandler(fh)
-
-    # "application" code
-    logger.debug("debug message")
-    logger.info("info message")
-    logger.warn("warn message")
-    logger.error("error message")
-    logger.critical("critical message")
-
-Notice that the "application" code does not care about multiple handlers.  All
-that changed was the addition and configuration of a new handler named *fh*.
-
-The ability to create new handlers with higher- or lower-severity filters can be
-very helpful when writing and testing an application.  Instead of using many
-``print`` statements for debugging, use ``logger.debug``: Unlike the print
-statements, which you will have to delete or comment out later, the logger.debug
-statements can remain intact in the source code and remain dormant until you
-need them again.  At that time, the only change that needs to happen is to
-modify the severity level of the logger and/or handler to debug.
-
-
-Using logging in multiple modules
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-
-It was mentioned above that multiple calls to
-``logging.getLogger('someLogger')`` return a reference to the same logger
-object.  This is true not only within the same module, but also across modules
-as long as it is in the same Python interpreter process.  It is true for
-references to the same object; additionally, application code can define and
-configure a parent logger in one module and create (but not configure) a child
-logger in a separate module, and all logger calls to the child will pass up to
-the parent.  Here is a main module::
-
-    import logging
-    import auxiliary_module
-
-    # create logger with "spam_application"
-    logger = logging.getLogger("spam_application")
-    logger.setLevel(logging.DEBUG)
-    # create file handler which logs even debug messages
-    fh = logging.FileHandler("spam.log")
-    fh.setLevel(logging.DEBUG)
-    # create console handler with a higher log level
-    ch = logging.StreamHandler()
-    ch.setLevel(logging.ERROR)
-    # create formatter and add it to the handlers
-    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
-    fh.setFormatter(formatter)
-    ch.setFormatter(formatter)
-    # add the handlers to the logger
-    logger.addHandler(fh)
-    logger.addHandler(ch)
-
-    logger.info("creating an instance of auxiliary_module.Auxiliary")
-    a = auxiliary_module.Auxiliary()
-    logger.info("created an instance of auxiliary_module.Auxiliary")
-    logger.info("calling auxiliary_module.Auxiliary.do_something")
-    a.do_something()
-    logger.info("finished auxiliary_module.Auxiliary.do_something")
-    logger.info("calling auxiliary_module.some_function()")
-    auxiliary_module.some_function()
-    logger.info("done with auxiliary_module.some_function()")
-
-Here is the auxiliary module::
-
-    import logging
-
-    # create logger
-    module_logger = logging.getLogger("spam_application.auxiliary")
-
-    class Auxiliary:
-        def __init__(self):
-            self.logger = logging.getLogger("spam_application.auxiliary.Auxiliary")
-            self.logger.info("creating an instance of Auxiliary")
-        def do_something(self):
-            self.logger.info("doing something")
-            a = 1 + 1
-            self.logger.info("done doing something")
-
-    def some_function():
-        module_logger.info("received a call to \"some_function\"")
-
-The output looks like this::
-
-    2005-03-23 23:47:11,663 - spam_application - INFO -
-       creating an instance of auxiliary_module.Auxiliary
-    2005-03-23 23:47:11,665 - spam_application.auxiliary.Auxiliary - INFO -
-       creating an instance of Auxiliary
-    2005-03-23 23:47:11,665 - spam_application - INFO -
-       created an instance of auxiliary_module.Auxiliary
-    2005-03-23 23:47:11,668 - spam_application - INFO -
-       calling auxiliary_module.Auxiliary.do_something
-    2005-03-23 23:47:11,668 - spam_application.auxiliary.Auxiliary - INFO -
-       doing something
-    2005-03-23 23:47:11,669 - spam_application.auxiliary.Auxiliary - INFO -
-       done doing something
-    2005-03-23 23:47:11,670 - spam_application - INFO -
-       finished auxiliary_module.Auxiliary.do_something
-    2005-03-23 23:47:11,671 - spam_application - INFO -
-       calling auxiliary_module.some_function()
-    2005-03-23 23:47:11,672 - spam_application.auxiliary - INFO -
-       received a call to "some_function"
-    2005-03-23 23:47:11,673 - spam_application - INFO -
-       done with auxiliary_module.some_function()
+   `Original Python logging package <http://www.red-dove.com/python_logging.html>`_
+      This is the original source for the :mod:`logging` package.  The version of the
+      package available from this site is suitable for use with Python 1.5.2, 2.1.x
+      and 2.2.x, which do not include the :mod:`logging` package in the standard
+      library.
 

Modified: python/branches/pep-3151/Doc/library/mailbox.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/mailbox.rst	(original)
+++ python/branches/pep-3151/Doc/library/mailbox.rst	Sat Feb 26 08:16:32 2011
@@ -81,13 +81,16 @@
       it.
 
       Parameter *message* may be a :class:`Message` instance, an
-      :class:`email.Message.Message` instance, a string, or a file-like object
-      (which should be open in text mode). If *message* is an instance of the
+      :class:`email.Message.Message` instance, a string, a byte string, or a
+      file-like object (which should be open in binary mode). If *message* is
+      an instance of the
       appropriate format-specific :class:`Message` subclass (e.g., if it's an
       :class:`mboxMessage` instance and this is an :class:`mbox` instance), its
       format-specific information is used. Otherwise, reasonable defaults for
       format-specific information are used.
 
+      .. versionchanged:: 3.2 support for binary input
+
 
    .. method:: remove(key)
                __delitem__(key)
@@ -108,8 +111,9 @@
       :exc:`KeyError` exception if no message already corresponds to *key*.
 
       As with :meth:`add`, parameter *message* may be a :class:`Message`
-      instance, an :class:`email.Message.Message` instance, a string, or a
-      file-like object (which should be open in text mode). If *message* is an
+      instance, an :class:`email.Message.Message` instance, a string, a byte
+      string, or a file-like object (which should be open in binary mode). If
+      *message* is an
       instance of the appropriate format-specific :class:`Message` subclass
       (e.g., if it's an :class:`mboxMessage` instance and this is an
       :class:`mbox` instance), its format-specific information is
@@ -171,10 +175,20 @@
       raise a :exc:`KeyError` exception if no such message exists.
 
 
+   .. method:: get_bytes(key)
+
+      Return a byte representation of the message corresponding to *key*, or
+      raise a :exc:`KeyError` exception if no such message exists.
+
+      .. versionadded:: 3.2
+
+
    .. method:: get_string(key)
 
       Return a string representation of the message corresponding to *key*, or
-      raise a :exc:`KeyError` exception if no such message exists.
+      raise a :exc:`KeyError` exception if no such message exists.  The
+      message is processed through :class:`email.message.Message` to
+      convert it to a 7bit clean representation.
 
 
    .. method:: get_file(key)
@@ -184,9 +198,11 @@
       file-like object behaves as if open in binary mode.  This file should be
       closed once it is no longer needed.
 
-      .. versionadded:: 3.2
-         The file-like object supports the context manager protocol, so that
-         you can use a :keyword:`with` statement to automatically close it.
+      .. versionchanged:: 3.2
+         The file object really is a binary file; previously it was incorrectly
+         returned in text mode.  Also, the file-like object now supports the
+         context manager protocol: you can use a :keyword:`with` statement to
+         automatically close it.
 
       .. note::
 
@@ -746,9 +762,11 @@
    If *message* is omitted, the new instance is created in a default, empty state.
    If *message* is an :class:`email.Message.Message` instance, its contents are
    copied; furthermore, any format-specific information is converted insofar as
-   possible if *message* is a :class:`Message` instance. If *message* is a string
+   possible if *message* is a :class:`Message` instance. If *message* is a string,
+   a byte string,
    or a file, it should contain an :rfc:`2822`\ -compliant message, which is read
-   and parsed.
+   and parsed.  Files should be open in binary mode, but text mode files
+   are accepted for backward compatibility.
 
    The format-specific state and behaviors offered by subclasses vary, but in
    general it is only the properties that are not specific to a particular

Modified: python/branches/pep-3151/Doc/library/mailcap.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/mailcap.rst	(original)
+++ python/branches/pep-3151/Doc/library/mailcap.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: mailcap
    :synopsis: Mailcap file handling.
 
+**Source code:** :source:`Lib/mailcap.py`
+
+--------------
 
 Mailcap files are used to configure how MIME-aware applications such as mail
 readers and Web browsers react to files with different MIME types. (The name

Modified: python/branches/pep-3151/Doc/library/mimetypes.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/mimetypes.rst	(original)
+++ python/branches/pep-3151/Doc/library/mimetypes.rst	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,10 @@
 
 .. index:: pair: MIME; content type
 
+**Source code:** :source:`Lib/mimetypes.py`
+
+--------------
+
 The :mod:`mimetypes` module converts between a filename or URL and the MIME type
 associated with the filename extension.  Conversions are provided from filename
 to MIME type and from MIME type to filename extension; encodings are not

Modified: python/branches/pep-3151/Doc/library/modulefinder.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/modulefinder.rst	(original)
+++ python/branches/pep-3151/Doc/library/modulefinder.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,9 @@
 .. module:: modulefinder
    :synopsis: Find modules used by a script.
 
+**Source code:** :source:`Lib/modulefinder.py`
+
+--------------
 
 This module provides a :class:`ModuleFinder` class that can be used to determine
 the set of modules imported by a script. ``modulefinder.py`` can also be run as

Modified: python/branches/pep-3151/Doc/library/msilib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/msilib.rst	(original)
+++ python/branches/pep-3151/Doc/library/msilib.rst	Sat Feb 26 08:16:32 2011
@@ -351,7 +351,7 @@
 -----------------
 
 
-.. class:: Directory(database, cab, basedir, physical,  logical, default, component, [componentflags])
+.. class:: Directory(database, cab, basedir, physical,  logical, default, [componentflags])
 
    Create a new directory in the Directory table. There is a current component at
    each point in time for the directory, which is either explicitly created through

Modified: python/branches/pep-3151/Doc/library/multiprocessing.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/multiprocessing.rst	(original)
+++ python/branches/pep-3151/Doc/library/multiprocessing.rst	Sat Feb 26 08:16:32 2011
@@ -1,8 +1,8 @@
-:mod:`multiprocessing` --- Process-based "threading" interface
-==============================================================
+:mod:`multiprocessing` --- Process-based parallelism
+====================================================
 
 .. module:: multiprocessing
-   :synopsis: Process-based "threading" interface.
+   :synopsis: Process-based parallelism.
 
 
 Introduction
@@ -297,7 +297,7 @@
 :class:`Process` and exceptions
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
-.. class:: Process([group[, target[, name[, args[, kwargs]]]]])
+.. class:: Process([group[, target[, name[, args[, kwargs]]]]], *, daemon=None)
 
    Process objects represent activity that is run in a separate process. The
    :class:`Process` class has equivalents of all the methods of
@@ -312,13 +312,19 @@
    :sub:`1`,N\ :sub:`2`,...,N\ :sub:`k` is a sequence of integers whose length
    is determined by the *generation* of the process.  *args* is the argument
    tuple for the target invocation.  *kwargs* is a dictionary of keyword
-   arguments for the target invocation.  By default, no arguments are passed to
-   *target*.
+   arguments for the target invocation.  If provided, the keyword-only *daemon* argument
+   sets the process :attr:`daemon` flag to ``True`` or ``False``.  If ``None``
+   (the default), this flag will be inherited from the creating process.
+
+   By default, no arguments are passed to *target*.
 
    If a subclass overrides the constructor, it must make sure it invokes the
    base class constructor (:meth:`Process.__init__`) before doing anything else
    to the process.
 
+   .. versionchanged:: 3.3
+      Added the *daemon* argument.
+
    .. method:: run()
 
       Method representing the process's activity.
@@ -1334,7 +1340,7 @@
 
    from multiprocessing.managers import BaseManager
 
-   class MathsClass(object):
+   class MathsClass:
        def add(self, x, y):
            return x + y
        def mul(self, x, y):

Modified: python/branches/pep-3151/Doc/library/netrc.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/netrc.rst	(original)
+++ python/branches/pep-3151/Doc/library/netrc.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,9 @@
 .. moduleauthor:: Eric S. Raymond <esr at snark.thyrsus.com>
 .. sectionauthor:: Eric S. Raymond <esr at snark.thyrsus.com>
 
+**Source code:** :source:`Lib/netrc.py`
+
+--------------
 
 The :class:`netrc` class parses and encapsulates the netrc file format used by
 the Unix :program:`ftp` program and other FTP clients.

Modified: python/branches/pep-3151/Doc/library/nntplib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/nntplib.rst	(original)
+++ python/branches/pep-3151/Doc/library/nntplib.rst	Sat Feb 26 08:16:32 2011
@@ -10,6 +10,10 @@
    pair: NNTP; protocol
    single: Network News Transfer Protocol
 
+**Source code:** :source:`Lib/nntplib.py`
+
+--------------
+
 This module defines the class :class:`NNTP` which implements the client side of
 the Network News Transfer Protocol.  It can be used to implement a news reader
 or poster, or automated news processors.  It is compatible with :rfc:`3977`

Modified: python/branches/pep-3151/Doc/library/numeric.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/numeric.rst	(original)
+++ python/branches/pep-3151/Doc/library/numeric.rst	Sat Feb 26 08:16:32 2011
@@ -23,6 +23,3 @@
    decimal.rst
    fractions.rst
    random.rst
-   itertools.rst
-   functools.rst
-   operator.rst

Modified: python/branches/pep-3151/Doc/library/operator.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/operator.rst	(original)
+++ python/branches/pep-3151/Doc/library/operator.rst	Sat Feb 26 08:16:32 2011
@@ -9,7 +9,7 @@
 .. testsetup::
 
    import operator
-   from operator import itemgetter
+   from operator import itemgetter, iadd
 
 
 The :mod:`operator` module exports a set of functions implemented in C
@@ -19,8 +19,7 @@
 trailing ``__`` are also provided for convenience.
 
 The functions fall into categories that perform object comparisons, logical
-operations, mathematical operations, sequence operations, and abstract type
-tests.
+operations, mathematical operations and sequence operations.
 
 The object comparison functions are useful for all objects, and are named after
 the rich comparison operators they support:
@@ -226,91 +225,6 @@
 
    Set the value of *a* at index *b* to *c*.
 
-
-Many operations have an "in-place" version.  The following functions provide a
-more primitive access to in-place operators than the usual syntax does; for
-example, the :term:`statement` ``x += y`` is equivalent to
-``x = operator.iadd(x, y)``.  Another way to put it is to say that
-``z = operator.iadd(x, y)`` is equivalent to the compound statement
-``z = x; z += y``.
-
-.. function:: iadd(a, b)
-              __iadd__(a, b)
-
-   ``a = iadd(a, b)`` is equivalent to ``a += b``.
-
-
-.. function:: iand(a, b)
-              __iand__(a, b)
-
-   ``a = iand(a, b)`` is equivalent to ``a &= b``.
-
-
-.. function:: iconcat(a, b)
-              __iconcat__(a, b)
-
-   ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
-
-
-.. function:: ifloordiv(a, b)
-              __ifloordiv__(a, b)
-
-   ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
-
-
-.. function:: ilshift(a, b)
-              __ilshift__(a, b)
-
-   ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
-
-
-.. function:: imod(a, b)
-              __imod__(a, b)
-
-   ``a = imod(a, b)`` is equivalent to ``a %= b``.
-
-
-.. function:: imul(a, b)
-              __imul__(a, b)
-
-   ``a = imul(a, b)`` is equivalent to ``a *= b``.
-
-
-.. function:: ior(a, b)
-              __ior__(a, b)
-
-   ``a = ior(a, b)`` is equivalent to ``a |= b``.
-
-
-.. function:: ipow(a, b)
-              __ipow__(a, b)
-
-   ``a = ipow(a, b)`` is equivalent to ``a **= b``.
-
-
-.. function:: irshift(a, b)
-              __irshift__(a, b)
-
-   ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
-
-
-.. function:: isub(a, b)
-              __isub__(a, b)
-
-   ``a = isub(a, b)`` is equivalent to ``a -= b``.
-
-
-.. function:: itruediv(a, b)
-              __itruediv__(a, b)
-
-   ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
-
-
-.. function:: ixor(a, b)
-              __ixor__(a, b)
-
-   ``a = ixor(a, b)`` is equivalent to ``a ^= b``.
-
 Example: Build a dictionary that maps the ordinals from ``0`` to ``255`` to
 their character equivalents.
 
@@ -491,3 +405,112 @@
 | Ordering              | ``a > b``               | ``gt(a, b)``                          |
 +-----------------------+-------------------------+---------------------------------------+
 
+Inplace Operators
+=================
+
+Many operations have an "in-place" version.  Listed below are functions
+providing a more primitive access to in-place operators than the usual syntax
+does; for example, the :term:`statement` ``x += y`` is equivalent to
+``x = operator.iadd(x, y)``.  Another way to put it is to say that
+``z = operator.iadd(x, y)`` is equivalent to the compound statement
+``z = x; z += y``.
+
+In those examples, note that when an in-place method is called, the computation
+and assignment are performed in two separate steps.  The in-place functions
+listed below only do the first step, calling the in-place method.  The second
+step, assignment, is not handled.
+
+For immutable targets such as strings, numbers, and tuples, the updated
+value is computed, but not assigned back to the input variable:
+
+>>> a = 'hello'
+>>> iadd(a, ' world')
+'hello world'
+>>> a
+'hello'
+
+For mutable targets such as lists and dictionaries, the inplace method
+will perform the update, so no subsequent assignment is necessary:
+
+>>> s = ['h', 'e', 'l', 'l', 'o']
+>>> iadd(s, [' ', 'w', 'o', 'r', 'l', 'd'])
+['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
+>>> s
+['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
+
+.. function:: iadd(a, b)
+              __iadd__(a, b)
+
+   ``a = iadd(a, b)`` is equivalent to ``a += b``.
+
+
+.. function:: iand(a, b)
+              __iand__(a, b)
+
+   ``a = iand(a, b)`` is equivalent to ``a &= b``.
+
+
+.. function:: iconcat(a, b)
+              __iconcat__(a, b)
+
+   ``a = iconcat(a, b)`` is equivalent to ``a += b`` for *a* and *b* sequences.
+
+
+.. function:: ifloordiv(a, b)
+              __ifloordiv__(a, b)
+
+   ``a = ifloordiv(a, b)`` is equivalent to ``a //= b``.
+
+
+.. function:: ilshift(a, b)
+              __ilshift__(a, b)
+
+   ``a = ilshift(a, b)`` is equivalent to ``a <<= b``.
+
+
+.. function:: imod(a, b)
+              __imod__(a, b)
+
+   ``a = imod(a, b)`` is equivalent to ``a %= b``.
+
+
+.. function:: imul(a, b)
+              __imul__(a, b)
+
+   ``a = imul(a, b)`` is equivalent to ``a *= b``.
+
+
+.. function:: ior(a, b)
+              __ior__(a, b)
+
+   ``a = ior(a, b)`` is equivalent to ``a |= b``.
+
+
+.. function:: ipow(a, b)
+              __ipow__(a, b)
+
+   ``a = ipow(a, b)`` is equivalent to ``a **= b``.
+
+
+.. function:: irshift(a, b)
+              __irshift__(a, b)
+
+   ``a = irshift(a, b)`` is equivalent to ``a >>= b``.
+
+
+.. function:: isub(a, b)
+              __isub__(a, b)
+
+   ``a = isub(a, b)`` is equivalent to ``a -= b``.
+
+
+.. function:: itruediv(a, b)
+              __itruediv__(a, b)
+
+   ``a = itruediv(a, b)`` is equivalent to ``a /= b``.
+
+
+.. function:: ixor(a, b)
+              __ixor__(a, b)
+
+   ``a = ixor(a, b)`` is equivalent to ``a ^= b``.

Modified: python/branches/pep-3151/Doc/library/optparse.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/optparse.rst	(original)
+++ python/branches/pep-3151/Doc/library/optparse.rst	Sat Feb 26 08:16:32 2011
@@ -4,14 +4,16 @@
 .. module:: optparse
    :synopsis: Command-line option parsing library.
    :deprecated:
-
-.. deprecated:: 2.7
-   The :mod:`optparse` module is deprecated and will not be developed further;
-   development will continue with the :mod:`argparse` module.
-
 .. moduleauthor:: Greg Ward <gward at python.net>
 .. sectionauthor:: Greg Ward <gward at python.net>
 
+**Source code:** :source:`Lib/optparse.py`
+
+--------------
+
+.. deprecated:: 2.7
+  The :mod:`optparse` module is deprecated and will not be developed further;
+  development will continue with the :mod:`argparse` module.
 
 :mod:`optparse` is a more convenient, flexible, and powerful library for parsing
 command-line options than the old :mod:`getopt` module.  :mod:`optparse` uses a
@@ -61,9 +63,9 @@
 
 .. code-block:: text
 
-   usage: <yourscript> [options]
+   Usage: <yourscript> [options]
 
-   options:
+   Options:
      -h, --help            show this help message and exit
      -f FILE, --file=FILE  write report to FILE
      -q, --quiet           don't print status messages to stdout
@@ -104,26 +106,26 @@
    an argument used to supply extra information to guide or customize the
    execution of a program.  There are many different syntaxes for options; the
    traditional Unix syntax is a hyphen ("-") followed by a single letter,
-   e.g. ``"-x"`` or ``"-F"``.  Also, traditional Unix syntax allows multiple
-   options to be merged into a single argument, e.g.  ``"-x -F"`` is equivalent
-   to ``"-xF"``.  The GNU project introduced ``"--"`` followed by a series of
-   hyphen-separated words, e.g.  ``"--file"`` or ``"--dry-run"``.  These are the
+   e.g. ``-x`` or ``-F``.  Also, traditional Unix syntax allows multiple
+   options to be merged into a single argument, e.g. ``-x -F`` is equivalent
+   to ``-xF``.  The GNU project introduced ``--`` followed by a series of
+   hyphen-separated words, e.g. ``--file`` or ``--dry-run``.  These are the
    only two option syntaxes provided by :mod:`optparse`.
 
    Some other option syntaxes that the world has seen include:
 
-   * a hyphen followed by a few letters, e.g. ``"-pf"`` (this is *not* the same
+   * a hyphen followed by a few letters, e.g. ``-pf`` (this is *not* the same
      as multiple options merged into a single argument)
 
-   * a hyphen followed by a whole word, e.g. ``"-file"`` (this is technically
+   * a hyphen followed by a whole word, e.g. ``-file`` (this is technically
      equivalent to the previous syntax, but they aren't usually seen in the same
      program)
 
    * a plus sign followed by a single letter, or a few letters, or a word, e.g.
-     ``"+f"``, ``"+rgb"``
+     ``+f``, ``+rgb``
 
-   * a slash followed by a letter, or a few letters, or a word, e.g. ``"/f"``,
-     ``"/file"``
+   * a slash followed by a letter, or a few letters, or a word, e.g. ``/f``,
+     ``/file``
 
    These option syntaxes are not supported by :mod:`optparse`, and they never
    will be.  This is deliberate: the first three are non-standard on any
@@ -151,9 +153,9 @@
    Typically, a given option either takes an argument or it doesn't. Lots of
    people want an "optional option arguments" feature, meaning that some options
    will take an argument if they see it, and won't if they don't.  This is
-   somewhat controversial, because it makes parsing ambiguous: if ``"-a"`` takes
-   an optional argument and ``"-b"`` is another option entirely, how do we
-   interpret ``"-ab"``?  Because of this ambiguity, :mod:`optparse` does not
+   somewhat controversial, because it makes parsing ambiguous: if ``-a`` takes
+   an optional argument and ``-b`` is another option entirely, how do we
+   interpret ``-ab``?  Because of this ambiguity, :mod:`optparse` does not
    support this feature.
 
 positional argument
@@ -171,9 +173,9 @@
 
    prog -v --report /tmp/report.txt foo bar
 
-``"-v"`` and ``"--report"`` are both options.  Assuming that :option:`--report`
-takes one argument, ``"/tmp/report.txt"`` is an option argument.  ``"foo"`` and
-``"bar"`` are positional arguments.
+``-v`` and ``--report`` are both options.  Assuming that ``--report``
+takes one argument, ``/tmp/report.txt`` is an option argument.  ``foo`` and
+``bar`` are positional arguments.
 
 
 .. _optparse-what-options-for:
@@ -258,7 +260,7 @@
    parser.add_option(opt_str, ...,
                      attr=value, ...)
 
-Each option has one or more option strings, such as ``"-f"`` or ``"--file"``,
+Each option has one or more option strings, such as ``-f`` or ``--file``,
 and several option attributes that tell :mod:`optparse` what to expect and what
 to do when it encounters that option on the command line.
 
@@ -287,7 +289,7 @@
 :meth:`parse_args` returns two values:
 
 * ``options``, an object containing values for all of your options---e.g. if
-  ``"--file"`` takes a single string argument, then ``options.file`` will be the
+  ``--file`` takes a single string argument, then ``options.file`` will be the
   filename supplied by the user, or ``None`` if the user did not supply that
   option
 
@@ -333,8 +335,8 @@
    args = ["-f", "foo.txt"]
    (options, args) = parser.parse_args(args)
 
-When :mod:`optparse` sees the option string ``"-f"``, it consumes the next
-argument, ``"foo.txt"``, and stores it in ``options.filename``.  So, after this
+When :mod:`optparse` sees the option string ``-f``, it consumes the next
+argument, ``foo.txt``, and stores it in ``options.filename``.  So, after this
 call to :meth:`parse_args`, ``options.filename`` is ``"foo.txt"``.
 
 Some other option types supported by :mod:`optparse` are ``int`` and ``float``.
@@ -346,13 +348,13 @@
 Also, there's no explicit action, since the default is ``store``.
 
 Let's parse another fake command-line.  This time, we'll jam the option argument
-right up against the option: since ``"-n42"`` (one argument) is equivalent to
-``"-n 42"`` (two arguments), the code ::
+right up against the option: since ``-n42`` (one argument) is equivalent to
+``-n 42`` (two arguments), the code ::
 
    (options, args) = parser.parse_args(["-n42"])
    print(options.num)
 
-will print ``"42"``.
+will print ``42``.
 
 If you don't specify a type, :mod:`optparse` assumes ``string``.  Combined with
 the fact that the default action is ``store``, that means our first example can
@@ -362,9 +364,9 @@
 
 If you don't supply a destination, :mod:`optparse` figures out a sensible
 default from the option strings: if the first long option string is
-``"--foo-bar"``, then the default destination is ``foo_bar``.  If there are no
+``--foo-bar``, then the default destination is ``foo_bar``.  If there are no
 long option strings, :mod:`optparse` looks at the first short option string: the
-default destination for ``"-f"`` is ``f``.
+default destination for ``-f`` is ``f``.
 
 :mod:`optparse` also includes the built-in ``complex`` type.  Adding
 types is covered in section :ref:`optparse-extending-optparse`.
@@ -378,7 +380,7 @@
 Flag options---set a variable to true or false when a particular option is seen
 ---are quite common.  :mod:`optparse` supports them with two separate actions,
 ``store_true`` and ``store_false``.  For example, you might have a ``verbose``
-flag that is turned on with ``"-v"`` and off with ``"-q"``::
+flag that is turned on with ``-v`` and off with ``-q``::
 
    parser.add_option("-v", action="store_true", dest="verbose")
    parser.add_option("-q", action="store_false", dest="verbose")
@@ -387,8 +389,8 @@
 OK.  (It just means you have to be a bit careful when setting default values---
 see below.)
 
-When :mod:`optparse` encounters ``"-v"`` on the command line, it sets
-``options.verbose`` to ``True``; when it encounters ``"-q"``,
+When :mod:`optparse` encounters ``-v`` on the command line, it sets
+``options.verbose`` to ``True``; when it encounters ``-q``,
 ``options.verbose`` is set to ``False``.
 
 
@@ -428,7 +430,7 @@
 command line is parsed.
 
 First, consider the verbose/quiet example.  If we want :mod:`optparse` to set
-``verbose`` to ``True`` unless ``"-q"`` is seen, then we can do this::
+``verbose`` to ``True`` unless ``-q`` is seen, then we can do this::
 
    parser.add_option("-v", action="store_true", dest="verbose", default=True)
    parser.add_option("-q", action="store_false", dest="verbose")
@@ -486,15 +488,15 @@
                      help="interaction mode: novice, intermediate, "
                           "or expert [default: %default]")
 
-If :mod:`optparse` encounters either ``"-h"`` or ``"--help"`` on the
+If :mod:`optparse` encounters either ``-h`` or ``--help`` on the
 command-line, or if you just call :meth:`parser.print_help`, it prints the
 following to standard output:
 
 .. code-block:: text
 
-   usage: <yourscript> [options] arg1 arg2
+   Usage: <yourscript> [options] arg1 arg2
 
-   options:
+   Options:
      -h, --help            show this help message and exit
      -v, --verbose         make lots of noise [default]
      -q, --quiet           be vewwy quiet (I'm hunting wabbits)
@@ -513,12 +515,12 @@
 
      usage = "usage: %prog [options] arg1 arg2"
 
-  :mod:`optparse` expands ``"%prog"`` in the usage string to the name of the
+  :mod:`optparse` expands ``%prog`` in the usage string to the name of the
   current program, i.e. ``os.path.basename(sys.argv[0])``.  The expanded string
   is then printed before the detailed option help.
 
   If you don't supply a usage string, :mod:`optparse` uses a bland but sensible
-  default: ``"usage: %prog [options]"``, which is fine if your script doesn't
+  default: ``"Usage: %prog [options]"``, which is fine if your script doesn't
   take any positional arguments.
 
 * every option defines a help string, and doesn't worry about line-wrapping---
@@ -531,17 +533,17 @@
      -m MODE, --mode=MODE
 
   Here, "MODE" is called the meta-variable: it stands for the argument that the
-  user is expected to supply to :option:`-m`/:option:`--mode`.  By default,
+  user is expected to supply to ``-m``/``--mode``.  By default,
   :mod:`optparse` converts the destination variable name to uppercase and uses
   that for the meta-variable.  Sometimes, that's not what you want---for
-  example, the :option:`--filename` option explicitly sets ``metavar="FILE"``,
+  example, the ``--filename`` option explicitly sets ``metavar="FILE"``,
   resulting in this automatically-generated option description::
 
      -f FILE, --filename=FILE
 
   This is important for more than just saving space, though: the manually
-  written help text uses the meta-variable "FILE" to clue the user in that
-  there's a connection between the semi-formal syntax "-f FILE" and the informal
+  written help text uses the meta-variable ``FILE`` to clue the user in that
+  there's a connection between the semi-formal syntax ``-f FILE`` and the informal
   semantic description "write output to FILE". This is a simple but effective
   way to make your help text a lot clearer and more useful for end users.
 
@@ -550,12 +552,33 @@
   default value.  If an option has no default value (or the default value is
   ``None``), ``%default`` expands to ``none``.
 
+Grouping Options
+++++++++++++++++
+
 When dealing with many options, it is convenient to group these options for
 better help output.  An :class:`OptionParser` can contain several option groups,
 each of which can contain several options.
 
-Continuing with the parser defined above, adding an :class:`OptionGroup` to a
-parser is easy::
+An option group is obtained using the class :class:`OptionGroup`:
+
+.. class:: OptionGroup(parser, title, description=None)
+
+   where
+
+   * parser is the :class:`OptionParser` instance the group will be insterted in
+     to
+   * title is the group title
+   * description, optional, is a long description of the group
+
+:class:`OptionGroup` inherits from :class:`OptionContainer` (like
+:class:`OptionParser`) and so the :meth:`add_option` method can be used to add
+an option to the group.
+
+Once all the options are declared, using the :class:`OptionParser` method
+:meth:`add_option_group` the group is added to the previously defined parser.
+
+Continuing with the parser defined in the previous section, adding an
+:class:`OptionGroup` to a parser is easy::
 
     group = OptionGroup(parser, "Dangerous Options",
                         "Caution: use these options at your own risk.  "
@@ -567,20 +590,73 @@
 
 .. code-block:: text
 
-    usage:  [options] arg1 arg2
+   Usage: <yourscript> [options] arg1 arg2
+
+   Options:
+     -h, --help            show this help message and exit
+     -v, --verbose         make lots of noise [default]
+     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
+     -f FILE, --filename=FILE
+                           write output to FILE
+     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or
+                           expert [default: intermediate]
+
+     Dangerous Options:
+       Caution: use these options at your own risk.  It is believed that some
+       of them bite.
+
+       -g                  Group option.
+
+A bit more complete example might invole using more than one group: still
+extendind the previous example::
+
+    group = OptionGroup(parser, "Dangerous Options",
+                        "Caution: use these options at your own risk.  "
+                        "It is believed that some of them bite.")
+    group.add_option("-g", action="store_true", help="Group option.")
+    parser.add_option_group(group)
+
+    group = OptionGroup(parser, "Debug Options")
+    group.add_option("-d", "--debug", action="store_true",
+                     help="Print debug information")
+    group.add_option("-s", "--sql", action="store_true",
+                     help="Print all SQL statements executed")
+    group.add_option("-e", action="store_true", help="Print every action done")
+    parser.add_option_group(group)
+
+that results in the following output:
+
+.. code-block:: text
+
+   Usage: <yourscript> [options] arg1 arg2
+
+   Options:
+     -h, --help            show this help message and exit
+     -v, --verbose         make lots of noise [default]
+     -q, --quiet           be vewwy quiet (I'm hunting wabbits)
+     -f FILE, --filename=FILE
+                           write output to FILE
+     -m MODE, --mode=MODE  interaction mode: novice, intermediate, or expert
+                           [default: intermediate]
+
+     Dangerous Options:
+       Caution: use these options at your own risk.  It is believed that some
+       of them bite.
+
+       -g                  Group option.
+
+     Debug Options:
+       -d, --debug         Print debug information
+       -s, --sql           Print all SQL statements executed
+       -e                  Print every action done
+
+Another interesting method, in particular when working programmatically with
+option groups is:
+
+.. method:: OptionParser.get_option_group(opt_str)
 
-    options:
-      -h, --help           show this help message and exit
-      -v, --verbose        make lots of noise [default]
-      -q, --quiet          be vewwy quiet (I'm hunting wabbits)
-      -fFILE, --file=FILE  write output to FILE
-      -mMODE, --mode=MODE  interaction mode: one of 'novice', 'intermediate'
-                           [default], 'expert'
-
-      Dangerous Options:
-      Caution: use of these options is at your own risk.  It is believed that
-      some of them bite.
-      -g                 Group option.
+   Return, if defined, the :class:`OptionGroup` that has the title or the long
+   description equals to *opt_str*
 
 .. _optparse-printing-version-string:
 
@@ -593,11 +669,11 @@
 
    parser = OptionParser(usage="%prog [-f] [-q]", version="%prog 1.0")
 
-``"%prog"`` is expanded just like it is in ``usage``.  Apart from that,
+``%prog`` is expanded just like it is in ``usage``.  Apart from that,
 ``version`` can contain anything you like.  When you supply it, :mod:`optparse`
-automatically adds a ``"--version"`` option to your parser. If it encounters
+automatically adds a ``--version`` option to your parser. If it encounters
 this option on the command line, it expands your ``version`` string (by
-replacing ``"%prog"``), prints it to stdout, and exits.
+replacing ``%prog``), prints it to stdout, and exits.
 
 For example, if your script is called ``/usr/bin/foo``::
 
@@ -610,7 +686,7 @@
 
    Print the version message for the current program (``self.version``) to
    *file* (default stdout).  As with :meth:`print_usage`, any occurrence
-   of ``"%prog"`` in ``self.version`` is replaced with the name of the current
+   of ``%prog`` in ``self.version`` is replaced with the name of the current
    program.  Does nothing if ``self.version`` is empty or undefined.
 
 .. method:: OptionParser.get_version()
@@ -633,9 +709,9 @@
 
 Handling user errors is much more important, since they are guaranteed to happen
 no matter how stable your code is.  :mod:`optparse` can automatically detect
-some user errors, such as bad option arguments (passing ``"-n 4x"`` where
-:option:`-n` takes an integer argument), missing arguments (``"-n"`` at the end
-of the command line, where :option:`-n` takes an argument of any type).  Also,
+some user errors, such as bad option arguments (passing ``-n 4x`` where
+``-n`` takes an integer argument), missing arguments (``-n`` at the end
+of the command line, where ``-n`` takes an argument of any type).  Also,
 you can call :func:`OptionParser.error` to signal an application-defined error
 condition::
 
@@ -648,18 +724,18 @@
 program's usage message and an error message to standard error and exits with
 error status 2.
 
-Consider the first example above, where the user passes ``"4x"`` to an option
+Consider the first example above, where the user passes ``4x`` to an option
 that takes an integer::
 
    $ /usr/bin/foo -n 4x
-   usage: foo [options]
+   Usage: foo [options]
 
    foo: error: option -n: invalid integer value: '4x'
 
 Or, where the user fails to pass a value at all::
 
    $ /usr/bin/foo -n
-   usage: foo [options]
+   Usage: foo [options]
 
    foo: error: -n option requires an argument
 
@@ -741,8 +817,8 @@
    ``version`` (default: ``None``)
       A version string to print when the user supplies a version option. If you
       supply a true value for ``version``, :mod:`optparse` automatically adds a
-      version option with the single option string ``"--version"``.  The
-      substring ``"%prog"`` is expanded the same as for ``usage``.
+      version option with the single option string ``--version``.  The
+      substring ``%prog`` is expanded the same as for ``usage``.
 
    ``conflict_handler`` (default: ``"error"``)
       Specifies what to do when options with conflicting option strings are
@@ -761,11 +837,11 @@
       IndentedHelpFormatter and TitledHelpFormatter.
 
    ``add_help_option`` (default: ``True``)
-      If true, :mod:`optparse` will add a help option (with option strings ``"-h"``
-      and ``"--help"``) to the parser.
+      If true, :mod:`optparse` will add a help option (with option strings ``-h``
+      and ``--help``) to the parser.
 
    ``prog``
-      The string to use when expanding ``"%prog"`` in ``usage`` and ``version``
+      The string to use when expanding ``%prog`` in ``usage`` and ``version``
       instead of ``os.path.basename(sys.argv[0])``.
 
    ``epilog`` (default: ``None``)
@@ -809,7 +885,7 @@
 ^^^^^^^^^^^^^^^^
 
 Each Option instance represents a set of synonymous command-line option strings,
-e.g. :option:`-f` and :option:`--file`.  You can specify any number of short or
+e.g. ``-f`` and ``--file``.  You can specify any number of short or
 long option strings, but you must specify at least one overall option string.
 
 The canonical way to create an :class:`Option` instance is with the
@@ -972,7 +1048,7 @@
 .. attribute:: Option.help
 
    Help text to print for this option when listing all available options after
-   the user supplies a :attr:`~Option.help` option (such as ``"--help"``).  If
+   the user supplies a :attr:`~Option.help` option (such as ``--help``).  If
    no help text is supplied, the option will be listed without help text.  To
    hide this option, use the special value :data:`optparse.SUPPRESS_HELP`.
 
@@ -1010,9 +1086,9 @@
   If :attr:`~Option.type` is not supplied, it defaults to ``"string"``.
 
   If :attr:`~Option.dest` is not supplied, :mod:`optparse` derives a destination
-  from the first long option string (e.g., ``"--foo-bar"`` implies
+  from the first long option string (e.g., ``--foo-bar`` implies
   ``foo_bar``). If there are no long option strings, :mod:`optparse` derives a
-  destination from the first short option string (e.g., ``"-f"`` implies ``f``).
+  destination from the first short option string (e.g., ``-f`` implies ``f``).
 
   Example::
 
@@ -1043,7 +1119,7 @@
      parser.add_option("--noisy",
                        action="store_const", const=2, dest="verbose")
 
-  If ``"--noisy"`` is seen, :mod:`optparse` will set  ::
+  If ``--noisy`` is seen, :mod:`optparse` will set  ::
 
      options.verbose = 2
 
@@ -1078,13 +1154,13 @@
 
      parser.add_option("-t", "--tracks", action="append", type="int")
 
-  If ``"-t3"`` is seen on the command-line, :mod:`optparse` does the equivalent
+  If ``-t3`` is seen on the command-line, :mod:`optparse` does the equivalent
   of::
 
      options.tracks = []
      options.tracks.append(int("3"))
 
-  If, a little later on, ``"--tracks=4"`` is seen, it does::
+  If, a little later on, ``--tracks=4`` is seen, it does::
 
      options.tracks.append(int("4"))
 
@@ -1106,13 +1182,13 @@
 
      parser.add_option("-v", action="count", dest="verbosity")
 
-  The first time ``"-v"`` is seen on the command line, :mod:`optparse` does the
+  The first time ``-v`` is seen on the command line, :mod:`optparse` does the
   equivalent of::
 
      options.verbosity = 0
      options.verbosity += 1
 
-  Every subsequent occurrence of ``"-v"`` results in  ::
+  Every subsequent occurrence of ``-v`` results in  ::
 
      options.verbosity += 1
 
@@ -1155,15 +1231,15 @@
                        help="Input file to read data from")
      parser.add_option("--secret", help=SUPPRESS_HELP)
 
-  If :mod:`optparse` sees either ``"-h"`` or ``"--help"`` on the command line,
+  If :mod:`optparse` sees either ``-h`` or ``--help`` on the command line,
   it will print something like the following help message to stdout (assuming
   ``sys.argv[0]`` is ``"foo.py"``):
 
   .. code-block:: text
 
-     usage: foo.py [options]
+     Usage: foo.py [options]
 
-     options:
+     Options:
        -h, --help        Show this help message and exit
        -v                Be moderately verbose
        --file=FILENAME   Input file to read data from
@@ -1269,8 +1345,8 @@
 
 .. method:: OptionParser.disable_interspersed_args()
 
-   Set parsing to stop on the first non-option.  For example, if ``"-a"`` and
-   ``"-b"`` are both simple options that take no arguments, :mod:`optparse`
+   Set parsing to stop on the first non-option.  For example, if ``-a`` and
+   ``-b`` are both simple options that take no arguments, :mod:`optparse`
    normally accepts this syntax::
 
       prog -a arg1 -b arg2
@@ -1300,7 +1376,7 @@
 .. method:: OptionParser.has_option(opt_str)
 
    Return true if the OptionParser has an option with option string *opt_str*
-   (e.g., ``"-q"`` or ``"--verbose"``).
+   (e.g., ``-q`` or ``--verbose``).
 
 .. method:: OptionParser.remove_option(opt_str)
 
@@ -1353,12 +1429,12 @@
    parser.add_option("-n", "--noisy", ..., help="be noisy")
 
 At this point, :mod:`optparse` detects that a previously-added option is already
-using the ``"-n"`` option string.  Since ``conflict_handler`` is ``"resolve"``,
-it resolves the situation by removing ``"-n"`` from the earlier option's list of
-option strings.  Now ``"--dry-run"`` is the only way for the user to activate
+using the ``-n`` option string.  Since ``conflict_handler`` is ``"resolve"``,
+it resolves the situation by removing ``-n`` from the earlier option's list of
+option strings.  Now ``--dry-run`` is the only way for the user to activate
 that option.  If the user asks for help, the help message will reflect that::
 
-   options:
+   Options:
      --dry-run     do no harm
      [...]
      -n, --noisy   be noisy
@@ -1371,10 +1447,10 @@
 
    parser.add_option("--dry-run", ..., help="new dry-run option")
 
-At this point, the original :option:`-n/--dry-run` option is no longer
+At this point, the original ``-n``/``--dry-run`` option is no longer
 accessible, so :mod:`optparse` removes it, leaving this help text::
 
-   options:
+   Options:
      [...]
      -n, --noisy   be noisy
      --dry-run     new dry-run option
@@ -1409,7 +1485,7 @@
 .. method:: OptionParser.print_usage(file=None)
 
    Print the usage message for the current program (``self.usage``) to *file*
-   (default stdout).  Any occurrence of the string ``"%prog"`` in ``self.usage``
+   (default stdout).  Any occurrence of the string ``%prog`` in ``self.usage``
    is replaced with the name of the current program.  Does nothing if
    ``self.usage`` is empty or not defined.
 
@@ -1473,9 +1549,9 @@
 
 ``callback`` is a function (or other callable object), so you must have already
 defined ``my_callback()`` when you create this callback option. In this simple
-case, :mod:`optparse` doesn't even know if :option:`-c` takes any arguments,
+case, :mod:`optparse` doesn't even know if ``-c`` takes any arguments,
 which usually means that the option takes no arguments---the mere presence of
-:option:`-c` on the command-line is all it needs to know.  In some
+``-c`` on the command-line is all it needs to know.  In some
 circumstances, though, you might want your callback to consume an arbitrary
 number of command-line arguments.  This is where writing callbacks gets tricky;
 it's covered later in this section.
@@ -1528,8 +1604,8 @@
 ``opt_str``
    is the option string seen on the command-line that's triggering the callback.
    (If an abbreviated long option was used, ``opt_str`` will be the full,
-   canonical option string---e.g. if the user puts ``"--foo"`` on the
-   command-line as an abbreviation for ``"--foobar"``, then ``opt_str`` will be
+   canonical option string---e.g. if the user puts ``--foo`` on the
+   command-line as an abbreviation for ``--foobar``, then ``opt_str`` will be
    ``"--foobar"``.)
 
 ``value``
@@ -1604,8 +1680,8 @@
 Callback example 2: check option order
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
-Here's a slightly more interesting example: record the fact that ``"-a"`` is
-seen, but blow up if it comes after ``"-b"`` in the command-line.  ::
+Here's a slightly more interesting example: record the fact that ``-a`` is
+seen, but blow up if it comes after ``-b`` in the command-line.  ::
 
    def check_order(option, opt_str, value, parser):
        if parser.values.b:
@@ -1622,7 +1698,7 @@
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 If you want to re-use this callback for several similar options (set a flag, but
-blow up if ``"-b"`` has already been seen), it needs a bit of work: the error
+blow up if ``-b`` has already been seen), it needs a bit of work: the error
 message and the flag that it sets must be generalized.  ::
 
    def check_order(option, opt_str, value, parser):
@@ -1692,15 +1768,15 @@
 built-in capabilities for it.  And you have to deal with certain intricacies of
 conventional Unix command-line parsing that :mod:`optparse` normally handles for
 you.  In particular, callbacks should implement the conventional rules for bare
-``"--"`` and ``"-"`` arguments:
+``--`` and ``-`` arguments:
 
-* either ``"--"`` or ``"-"`` can be option arguments
+* either ``--`` or ``-`` can be option arguments
 
-* bare ``"--"`` (if not the argument to some option): halt command-line
-  processing and discard the ``"--"``
+* bare ``--`` (if not the argument to some option): halt command-line
+  processing and discard the ``--``
 
-* bare ``"-"`` (if not the argument to some option): halt command-line
-  processing but keep the ``"-"`` (append it to ``parser.largs``)
+* bare ``-`` (if not the argument to some option): halt command-line
+  processing but keep the ``-`` (append it to ``parser.largs``)
 
 If you want an option that takes a variable number of arguments, there are
 several subtle, tricky issues to worry about.  The exact implementation you
@@ -1771,7 +1847,7 @@
       def check_mytype(option, opt, value)
 
    where ``option`` is an :class:`Option` instance, ``opt`` is an option string
-   (e.g., ``"-f"``), and ``value`` is the string from the command line that must
+   (e.g., ``-f``), and ``value`` is the string from the command line that must
    be checked and converted to your desired type.  ``check_mytype()`` should
    return an object of the hypothetical type ``mytype``.  The value returned by
    a type-checking function will wind up in the OptionValues instance returned
@@ -1883,7 +1959,7 @@
 ``"append"`` action, but instead of taking a single value from the command-line
 and appending it to an existing list, ``"extend"`` will take multiple values in
 a single comma-delimited string, and extend an existing list with them.  That
-is, if ``"--names"`` is an ``"extend"`` option of type ``"string"``, the command
+is, if ``--names`` is an ``"extend"`` option of type ``"string"``, the command
 line ::
 
    --names=foo,bar --names blah --names ding,dong

Modified: python/branches/pep-3151/Doc/library/os.path.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/os.path.rst	(original)
+++ python/branches/pep-3151/Doc/library/os.path.rst	Sat Feb 26 08:16:32 2011
@@ -228,7 +228,7 @@
 
    *start* defaults to :attr:`os.curdir`.
 
-   Availability:  Windows, Unix.
+   Availability: Unix, Windows.
 
 
 .. function:: samefile(path1, path2)
@@ -241,7 +241,7 @@
    name using the Windows API call GetFinalPathNameByHandle. This function
    raises an exception if handles cannot be obtained to either file.
 
-   Availability: Windows, Unix.
+   Availability: Unix, Windows.
 
    .. versionchanged:: 3.2
       Added Windows support.

Modified: python/branches/pep-3151/Doc/library/os.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/os.rst	(original)
+++ python/branches/pep-3151/Doc/library/os.rst	Sat Feb 26 08:16:32 2011
@@ -286,6 +286,22 @@
    .. versionchanged:: 3.2
       Added support for Windows.
 
+.. function:: getpriority(which, who)
+
+   .. index:: single: process; scheduling priority
+
+   Get program scheduling priority. The value *which* is one of
+   :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
+   is interpreted relative to *which* (a process identifier for
+   :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
+   user ID for :const:`PRIO_USER`). A zero value for *who* denotes
+   (respectively) the calling process, the process group of the calling process,
+   or the real user ID of the calling process.
+
+   Availability: Unix
+
+   .. versionadded:: 3.3
+
 .. function:: getresuid()
 
    Return a tuple (ruid, euid, suid) denoting the current process's
@@ -336,6 +352,15 @@
 
    .. versionadded:: 3.2
 
+.. data:: PRIO_PROCESS
+          PRIO_PGRP
+          PRIO_USER
+
+   Parameters for :func:`getpriority` and :func:`setpriority` functions.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
 
 .. function:: putenv(key, value)
 
@@ -405,6 +430,25 @@
    Availability: Unix.
 
 
+.. function:: setpriority(which, who, priority)
+
+   .. index:: single: process; scheduling priority
+
+   Set program scheduling priority. The value *which* is one of
+   :const:`PRIO_PROCESS`, :const:`PRIO_PGRP`, or :const:`PRIO_USER`, and *who*
+   is interpreted relative to *which* (a process identifier for
+   :const:`PRIO_PROCESS`, process group identifier for :const:`PRIO_PGRP`, and a
+   user ID for :const:`PRIO_USER`). A zero value for *who* denotes
+   (respectively) the calling process, the process group of the calling process,
+   or the real user ID of the calling process.
+   *priority* is a value in the range -20 to 19. The default priority is 0;
+   lower priorities cause more favorable scheduling.
+
+   Availability: Unix
+
+   .. versionadded:: 3.3
+
+
 .. function:: setregid(rgid, egid)
 
    Set the current process's real and effective group ids.
@@ -562,6 +606,21 @@
 descriptor directly will bypass the file object methods, ignoring aspects such
 as internal buffering of data.
 
+.. data:: AT_SYMLINK_NOFOLLOW
+          AT_EACCESS
+          AT_FDCWD
+          AT_REMOVEDIR
+          AT_SYMLINK_FOLLOW
+          UTIME_NOW
+          UTIME_OMIT
+
+   These parameters are used as flags to the \*at family of functions.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: close(fd)
 
    Close file descriptor *fd*.
@@ -610,6 +669,19 @@
    Availability: Unix, Windows.
 
 
+.. function:: faccessat(dirfd, path, mode, flags=0)
+
+   Like :func:`access` but if *path* is relative, it is taken as relative to *dirfd*.
+   *flags* is optional and can be constructed by ORing together zero or more
+   of these values: :data:`AT_SYMLINK_NOFOLLOW`, :data:`AT_EACCESS`.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: fchmod(fd, mode)
 
    Change the mode of the file given by *fd* to the numeric *mode*.  See the docs
@@ -618,6 +690,18 @@
    Availability: Unix.
 
 
+.. function:: fchmodat(dirfd, path, mode, flags=0)
+
+   Like :func:`chmod` but if *path* is relative, it is taken as relative to *dirfd*.
+   *flags* is optional and may be 0 or :data:`AT_SYMLINK_NOFOLLOW`.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: fchown(fd, uid, gid)
 
    Change the owner and group id of the file given by *fd* to the numeric *uid*
@@ -626,6 +710,18 @@
    Availability: Unix.
 
 
+.. function:: fchownat(dirfd, path, uid, gid, flags=0)
+
+   Like :func:`chown` but if *path* is relative, it is taken as relative to *dirfd*.
+   *flags* is optional and may be 0 or :data:`AT_SYMLINK_NOFOLLOW`.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: fdatasync(fd)
 
    Force write of file with filedescriptor *fd* to disk. Does not force update of
@@ -637,6 +733,16 @@
       This function is not available on MacOS.
 
 
+.. function:: fdlistdir(fd)
+
+   Like :func:`listdir`, but uses a file descriptor instead and always returns
+   strings.  After execution of this function, *fd* will be closed.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: fpathconf(fd, name)
 
    Return system configuration information relevant to an open file. *name*
@@ -657,10 +763,21 @@
 
 .. function:: fstat(fd)
 
-   Return status for file descriptor *fd*, like :func:`stat`.
+   Return status for file descriptor *fd*, like :func:`~os.stat`.
 
    Availability: Unix, Windows.
 
+.. function:: fstatat(dirfd, path, flags=0)
+
+   Like :func:`stat` but if *path* is relative, it is taken as relative to *dirfd*.
+   *flags* is optional and may be 0 or :data:`AT_SYMLINK_NOFOLLOW`.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
 
 .. function:: fstatvfs(fd)
 
@@ -690,6 +807,18 @@
    Availability: Unix.
 
 
+.. function:: futimesat(dirfd, path, (atime, mtime))
+              futimesat(dirfd, path, None)
+
+   Like :func:`utime` but if *path* is relative, it is taken as relative to *dirfd*.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: isatty(fd)
 
    Return ``True`` if the file descriptor *fd* is open and connected to a
@@ -698,6 +827,20 @@
    Availability: Unix.
 
 
+.. function:: linkat(srcfd, srcpath, dstfd, dstpath, flags=0)
+
+   Like :func:`link` but if *srcpath* is relative, it is taken as relative to *srcfd*
+   and if *dstpath* is relative, it is taken as relative to *dstfd*.
+   *flags* is optional and may be 0 or :data:`AT_SYMLINK_FOLLOW`.
+   If *srcpath* is relative and *srcfd* is the special value :data:`AT_FDCWD`, then
+   *srcpath* is interpreted relative to the current working directory. This
+   also applies for *dstpath*.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: lseek(fd, pos, how)
 
    Set the current position of file descriptor *fd* to position *pos*, modified
@@ -717,6 +860,39 @@
    respectively. Availability: Windows, Unix.
 
 
+.. function:: mkdirat(dirfd, path, mode=0o777)
+
+   Like :func:`mkdir` but if *path* is relative, it is taken as relative to *dirfd*.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
+.. function:: mkfifoat(dirfd, path, mode=0o666)
+
+   Like :func:`mkfifo` but if *path* is relative, it is taken as relative to *dirfd*.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
+.. function:: mknodat(dirfd, path, mode=0o600, device=0)
+
+   Like :func:`mknod` but if *path* is relative, it is taken as relative to *dirfd*.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: open(file, flags[, mode])
 
    Open the file *file* and set various flags according to *flags* and possibly
@@ -739,6 +915,17 @@
       wrap a file descriptor in a file object, use :func:`fdopen`.
 
 
+.. function:: openat(dirfd, path, flags, mode=0o777)
+
+   Like :func:`open` but if *path* is relative, it is taken as relative to *dirfd*.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: openpty()
 
    .. index:: module: pty
@@ -775,6 +962,82 @@
       :meth:`~file.readline` methods.
 
 
+.. function:: sendfile(out, in, offset, nbytes)
+              sendfile(out, in, offset, nbytes, headers=None, trailers=None, flags=0)
+
+   Copy *nbytes* bytes from file descriptor *in* to file descriptor *out*
+   starting at *offset*.
+   Return the number of bytes sent. When EOF is reached return 0.
+
+   The first function notation is supported by all platforms that define
+   :func:`sendfile`.
+
+   On Linux, if *offset* is given as ``None``, the bytes are read from the
+   current position of *in* and the position of *in* is updated.
+
+   The second case may be used on Mac OS X and FreeBSD where *headers* and
+   *trailers* are arbitrary sequences of buffers that are written before and
+   after the data from *in* is written. It returns the same as the first case.
+
+   On Mac OS X and FreeBSD, a value of 0 for *nbytes* specifies to send until
+   the end of *in* is reached.
+
+   On Solaris, *out* may be the file descriptor of a regular file or the file
+   descriptor of a socket. On all other platforms, *out* must be the file
+   descriptor of an open socket.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
+.. data:: SF_NODISKIO
+          SF_MNOWAIT
+          SF_SYNC
+
+   Parameters to the :func:`sendfile` function, if the implementation supports
+   them.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
+.. function:: readlinkat(dirfd, path)
+
+   Like :func:`readlink` but if *path* is relative, it is taken as relative to *dirfd*.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
+.. function:: renameat(olddirfd, oldpath, newdirfd, newpath)
+
+   Like :func:`rename` but if *oldpath* is relative, it is taken as relative to
+   *olddirfd* and if *newpath* is relative, it is taken as relative to *newdirfd*.
+   If *oldpath* is relative and *olddirfd* is the special value :data:`AT_FDCWD`, then
+   *oldpath* is interpreted relative to the current working directory. This
+   also applies for *newpath*.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
+.. function:: symlinkat(src, dstfd, dst)
+
+   Like :func:`symlink` but if *dst* is relative, it is taken as relative to *dstfd*.
+   If *dst* is relative and *dstfd* is the special value :data:`AT_FDCWD`, then *dst*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: tcgetpgrp(fd)
 
    Return the process group associated with the terminal given by *fd* (an open
@@ -800,6 +1063,38 @@
    Availability: Unix.
 
 
+.. function:: unlinkat(dirfd, path, flags=0)
+
+   Like :func:`unlink` but if *path* is relative, it is taken as relative to *dirfd*.
+   *flags* is optional and may be 0 or :data:`AT_REMOVEDIR`. If :data:`AT_REMOVEDIR` is
+   specified, :func:`unlinkat` behaves like :func:`rmdir`.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
+.. function:: utimensat(dirfd, path, (atime_sec, atime_nsec), (mtime_sec, mtime_nsec), flags)
+              utimensat(dirfd, path, None, None, flags)
+
+   Updates the timestamps of a file with nanosecond precision.
+   The second form sets *atime* and *mtime* to the current time.
+   If *atime_nsec* or *mtime_nsec* is specified as :data:`UTIME_NOW`, the corresponding
+   timestamp is updated to the current time.
+   If *atime_nsec* or *mtime_nsec* is specified as :data:`UTIME_OMIT`, the corresponding
+   timestamp is not updated.
+   If *path* is relative, it is taken as relative to *dirfd*.
+   *flags* is optional and may be 0 or :data:`AT_SYMLINK_NOFOLLOW`.
+   If *path* is relative and *dirfd* is the special value :data:`AT_FDCWD`, then *path*
+   is interpreted relative to the current working directory.
+
+   Availability: Unix.
+
+   .. versionadded:: 3.3
+
+
 .. function:: write(fd, str)
 
    Write the bytestring in *str* to file descriptor *fd*. Return the number of
@@ -1058,7 +1353,10 @@
 
    Create a hard link pointing to *source* named *link_name*.
 
-   Availability: Unix.
+   Availability: Unix, Windows.
+
+   .. versionchanged:: 3.2
+      Added Windows support.
 
 
 .. function:: listdir(path='.')
@@ -1077,8 +1375,10 @@
 
 .. function:: lstat(path)
 
-   Like :func:`stat`, but do not follow symbolic links.  This is an alias for
-   :func:`stat` on platforms that do not support symbolic links.
+   Perform the equivalent of an :c:func:`lstat` system call on the given path.
+   Similar to :func:`~os.stat`, but does not follow symbolic links.  On
+   platforms that do not support symbolic links, this is an alias for
+   :func:`~os.stat`.
 
    .. versionchanged:: 3.2
       Added support for Windows 6.0 (Vista) symbolic links.
@@ -1140,25 +1440,31 @@
    Availability: Unix, Windows.
 
 
-.. function:: makedirs(path[, mode])
+.. function:: makedirs(path, mode=0o777, exist_ok=False)
 
    .. index::
       single: directory; creating
       single: UNC paths; and os.makedirs()
 
    Recursive directory creation function.  Like :func:`mkdir`, but makes all
-   intermediate-level directories needed to contain the leaf directory.  Throws
-   an :exc:`error` exception if the leaf directory already exists or cannot be
-   created.  The default *mode* is ``0o777`` (octal).  On some systems, *mode*
-   is ignored. Where it is used, the current umask value is first masked out.
+   intermediate-level directories needed to contain the leaf directory.  If
+   the target directory with the same mode as specified already exists,
+   raises an :exc:`OSError` exception if *exist_ok* is False, otherwise no
+   exception is raised.  If the directory cannot be created in other cases,
+   raises an :exc:`OSError` exception.  The default *mode* is ``0o777`` (octal).
+   On some systems, *mode* is ignored.  Where it is used, the current umask
+   value is first masked out.
 
    .. note::
 
-      :func:`makedirs` will become confused if the path elements to create include
-      :data:`os.pardir`.
+      :func:`makedirs` will become confused if the path elements to create
+      include :data:`pardir`.
 
    This function handles UNC paths correctly.
 
+   .. versionadded:: 3.2
+      The *exist_ok* parameter.
+
 
 .. function:: pathconf(path, name)
 
@@ -1267,56 +1573,75 @@
 
 .. function:: stat(path)
 
-   Perform a :c:func:`stat` system call on the given path.  The return value is an
-   object whose attributes correspond to the members of the :c:type:`stat`
-   structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
-   number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
-   :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
-   :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
-   access), :attr:`st_mtime` (time of most recent content modification),
-   :attr:`st_ctime` (platform dependent; time of most recent metadata change on
-   Unix, or the time of creation on Windows)::
+   Perform the equivalent of a :c:func:`stat` system call on the given path.
+   (This function follows symlinks; to stat a symlink use :func:`lstat`.)
 
-      >>> import os
-      >>> statinfo = os.stat('somefile.txt')
-      >>> statinfo
-      (33188, 422511, 769, 1, 1032, 100, 926, 1105022698,1105022732, 1105022732)
-      >>> statinfo.st_size
-      926
-      >>>
+   The return value is an object whose attributes correspond to the members
+   of the :c:type:`stat` structure, namely:
 
+   * :attr:`st_mode` - protection bits,
+   * :attr:`st_ino` - inode number,
+   * :attr:`st_dev` - device,
+   * :attr:`st_nlink` - number of hard links,
+   * :attr:`st_uid` - user id of owner,
+   * :attr:`st_gid` - group id of owner,
+   * :attr:`st_size` - size of file, in bytes,
+   * :attr:`st_atime` - time of most recent access,
+   * :attr:`st_mtime` - time of most recent content modification,
+   * :attr:`st_ctime` - platform dependent; time of most recent metadata change on
+     Unix, or the time of creation on Windows)
 
    On some Unix systems (such as Linux), the following attributes may also be
-   available: :attr:`st_blocks` (number of blocks allocated for file),
-   :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
-   inode device). :attr:`st_flags` (user defined flags for file).
+   available:
+
+   * :attr:`st_blocks` - number of blocks allocated for file
+   * :attr:`st_blksize` - filesystem blocksize
+   * :attr:`st_rdev` - type of device if an inode device
+   * :attr:`st_flags` - user defined flags for file
 
    On other Unix systems (such as FreeBSD), the following attributes may be
-   available (but may be only filled out if root tries to use them): :attr:`st_gen`
-   (file generation number), :attr:`st_birthtime` (time of file creation).
+   available (but may be only filled out if root tries to use them):
+
+   * :attr:`st_gen` - file generation number
+   * :attr:`st_birthtime` - time of file creation
 
    On Mac OS systems, the following attributes may also be available:
-   :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
 
-   .. index:: module: stat
+   * :attr:`st_rsize`
+   * :attr:`st_creator`
+   * :attr:`st_type`
 
-   For backward compatibility, the return value of :func:`stat` is also accessible
+   .. note::
+
+      The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
+      :attr:`st_ctime` members depends on the operating system and the file system.
+      For example, on Windows systems using the FAT or FAT32 file systems,
+      :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
+      resolution.  See your operating system documentation for details.
+
+   For backward compatibility, the return value of :func:`~os.stat` is also accessible
    as a tuple of at least 10 integers giving the most important (and portable)
    members of the :c:type:`stat` structure, in the order :attr:`st_mode`,
    :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
    :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
    :attr:`st_ctime`. More items may be added at the end by some implementations.
+
+   .. index:: module: stat
+
    The standard module :mod:`stat` defines functions and constants that are useful
    for extracting information from a :c:type:`stat` structure. (On Windows, some
    items are filled with dummy values.)
 
-   .. note::
+   Example::
 
-      The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
-      :attr:`st_ctime` members depends on the operating system and the file system.
-      For example, on Windows systems using the FAT or FAT32 file systems,
-      :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
-      resolution.  See your operating system documentation for details.
+      >>> import os
+      >>> statinfo = os.stat('somefile.txt')
+      >>> statinfo
+      posix.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
+      st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
+      st_mtime=1297230027, st_ctime=1297230027)
+      >>> statinfo.st_size
+      264
 
    Availability: Unix, Windows.
 
@@ -1324,7 +1649,7 @@
 .. function:: stat_float_times([newvalue])
 
    Determine whether :class:`stat_result` represents time stamps as float objects.
-   If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
+   If *newvalue* is ``True``, future calls to :func:`~os.stat` return floats, if it is
    ``False``, future calls return ints. If *newvalue* is omitted, return the
    current setting.
 
@@ -1383,7 +1708,18 @@
 
    Symbolic link support was introduced in Windows 6.0 (Vista).  :func:`symlink`
    will raise a :exc:`NotImplementedError` on Windows versions earlier than 6.0.
-   The *SeCreateSymbolicLinkPrivilege* is required in order to create symlinks.
+
+   .. note::
+
+      The *SeCreateSymbolicLinkPrivilege* is required in order to successfully
+      create symlinks. This privilege is not typically granted to regular
+      users but is available to accounts which can escalate privileges to the
+      administrator level. Either obtaining the privilege or running your
+      application as an administrator are ways to successfully create symlinks.
+
+
+      :exc:`OSError` is raised when the function is called by an unprivileged
+      user.
 
    Availability: Unix, Windows.
 
@@ -1410,8 +1746,8 @@
    respectively. Whether a directory can be given for *path* depends on whether
    the operating system implements directories as files (for example, Windows
    does not).  Note that the exact times you set here may not be returned by a
-   subsequent :func:`stat` call, depending on the resolution with which your
-   operating system records access and modification times; see :func:`stat`.
+   subsequent :func:`~os.stat` call, depending on the resolution with which your
+   operating system records access and modification times; see :func:`~os.stat`.
 
    Availability: Unix, Windows.
 

Modified: python/branches/pep-3151/Doc/library/parser.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/parser.rst	(original)
+++ python/branches/pep-3151/Doc/library/parser.rst	Sat Feb 26 08:16:32 2011
@@ -268,7 +268,7 @@
    will only need to be aware of the simple string values.
 
 Note that the functions :func:`compilest`, :func:`expr`, and :func:`suite` may
-raise exceptions which are normally thrown by the parsing and compilation
+raise exceptions which are normally raised by the parsing and compilation
 process.  These include the built in exceptions :exc:`MemoryError`,
 :exc:`OverflowError`, :exc:`SyntaxError`, and :exc:`SystemError`.  In these
 cases, these exceptions carry all the meaning normally associated with them.

Modified: python/branches/pep-3151/Doc/library/pdb.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pdb.rst	(original)
+++ python/branches/pep-3151/Doc/library/pdb.rst	Sat Feb 26 08:16:32 2011
@@ -131,11 +131,12 @@
    :data:`sys.last_traceback`.
 
 
-The ``run_*`` functions and :func:`set_trace` are aliases for instantiating the
+The ``run*`` functions and :func:`set_trace` are aliases for instantiating the
 :class:`Pdb` class and calling the method of the same name.  If you want to
 access further features, you have to do this yourself:
 
-.. class:: Pdb(completekey='tab', stdin=None, stdout=None, skip=None)
+.. class:: Pdb(completekey='tab', stdin=None, stdout=None, skip=None, \
+               nosigint=False)
 
    :class:`Pdb` is the debugger class.
 
@@ -146,6 +147,11 @@
    patterns.  The debugger will not step into frames that originate in a module
    that matches one of these patterns. [1]_
 
+   By default, Pdb sets a handler for the SIGINT signal (which is sent when the
+   user presses Ctrl-C on the console) when you give a ``continue`` command.
+   This allows you to break into the debugger again by pressing Ctrl-C.  If you
+   want Pdb not to touch the SIGINT handler, set *nosigint* tot true.
+
    Example call to enable tracing with *skip*::
 
       import pdb; pdb.Pdb(skip=['django.*']).set_trace()
@@ -153,6 +159,10 @@
    .. versionadded:: 3.1
       The *skip* argument.
 
+   .. versionadded:: 3.2
+      The *nosigint* argument.  Previously, a SIGINT handler was never set by
+      Pdb.
+
    .. method:: run(statement, globals=None, locals=None)
                runeval(expression, globals=None, locals=None)
                runcall(function, *args, **kwds)
@@ -256,8 +266,9 @@
    Temporary breakpoint, which is removed automatically when it is first hit.
    The arguments are the same as for :pdbcmd:`break`.
 
-.. pdbcommand:: cl(ear) [bpnumber [bpnumber ...]]
+.. pdbcommand:: cl(ear) [filename:lineno | bpnumber [bpnumber ...]]
 
+   With a *filename:lineno* argument, clear all the breakpoints at this line.
    With a space separated list of breakpoint numbers, clear those breakpoints.
    Without argument, clear all breaks (but first ask confirmation).
 
@@ -406,6 +417,30 @@
 
    .. versionadded:: 3.2
 
+.. pdbcommand:: display [expression]
+
+   Display the value of the expression if it changed, each time execution stops
+   in the current frame.
+
+   Without expression, list all display expressions for the current frame.
+
+   .. versionadded:: 3.2
+
+.. pdbcommand:: undisplay [expression]
+
+   Do not display the expression any more in the current frame.  Without
+   expression, clear all display expressions for the current frame.
+
+   .. versionadded:: 3.2
+
+.. pdbcommand:: interact
+
+   Start an interative interpreter (using the :mod:`code` module) whose global
+   namespace contains all the (global and local) names found in the current
+   scope.
+
+   .. versionadded:: 3.2
+
 .. _debugger-aliases:
 
 .. pdbcommand:: alias [name [command]]

Modified: python/branches/pep-3151/Doc/library/pickle.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pickle.rst	(original)
+++ python/branches/pep-3151/Doc/library/pickle.rst	Sat Feb 26 08:16:32 2011
@@ -42,7 +42,7 @@
 objects.  :mod:`marshal` exists primarily to support Python's :file:`.pyc`
 files.
 
-The :mod:`pickle` module differs from :mod:`marshal` several significant ways:
+The :mod:`pickle` module differs from :mod:`marshal` in several significant ways:
 
 * The :mod:`pickle` module keeps track of the objects it has already serialized,
   so that later references to the same object won't be serialized again.

Modified: python/branches/pep-3151/Doc/library/pickletools.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pickletools.rst	(original)
+++ python/branches/pep-3151/Doc/library/pickletools.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,11 @@
    :synopsis: Contains extensive comments about the pickle protocols and
               pickle-machine opcodes, as well as some useful functions.
 
+**Source code:** :source:`Lib/pickletools.py`
+
+--------------
+
+
 This module contains various constants relating to the intimate details of the
 :mod:`pickle` module, some lengthy comments about the implementation, and a
 few useful functions for analyzing pickled data.  The contents of this module
@@ -12,6 +17,65 @@
 ordinary users of the :mod:`pickle` module probably won't find the
 :mod:`pickletools` module relevant.
 
+Command line usage
+------------------
+
+.. versionadded:: 3.2
+
+When invoked from the command line, ``python -m pickletools`` will
+disassemble the contents of one or more pickle files.  Note that if
+you want to see the Python object stored in the pickle rather than the
+details of pickle format, you may want to use ``-m pickle`` instead.
+However, when the pickle file that you want to examine comes from an
+untrusted source, ``-m pickletools`` is a safer option because it does
+not execute pickle bytecode.
+
+For example, with a tuple ``(1, 2)`` pickled in file ``x.pickle``::
+
+    $ python -m pickle x.pickle
+    (1, 2)
+
+    $ python -m pickletools x.pickle
+        0: \x80 PROTO      3
+        2: K    BININT1    1
+        4: K    BININT1    2
+        6: \x86 TUPLE2
+        7: q    BINPUT     0
+        9: .    STOP
+    highest protocol among opcodes = 2
+
+Command line options
+^^^^^^^^^^^^^^^^^^^^
+
+.. program:: pickletools
+
+.. cmdoption:: -a, --annotate
+
+   Annotate each line with a short opcode description.
+
+.. cmdoption:: -o, --output=<file>
+
+   Name of a file where the output should be written.
+
+.. cmdoption:: -l, --indentlevel=<num>
+
+   The number of blanks by which to indent a new MARK level.
+
+.. cmdoption:: -m, --memo
+
+   When multiple objects are disassembled, preserve memo between
+   disassemblies.
+
+.. cmdoption:: -p, --preamble=<preamble>
+
+   When more than one pickle file are specified, print given preamble
+   before each disassembly.
+
+
+
+Programmatic Interface
+----------------------
+
 
 .. function:: dis(pickle, out=None, memo=None, indentlevel=4, annotate=0)
 

Modified: python/branches/pep-3151/Doc/library/pipes.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pipes.rst	(original)
+++ python/branches/pep-3151/Doc/library/pipes.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
    :synopsis: A Python interface to Unix shell pipelines.
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
+**Source code:** :source:`Lib/pipes.py`
+
+--------------
 
 The :mod:`pipes` module defines a class to abstract the concept of a *pipeline*
 --- a sequence of converters from one file to  another.

Modified: python/branches/pep-3151/Doc/library/pkgutil.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pkgutil.rst	(original)
+++ python/branches/pep-3151/Doc/library/pkgutil.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,10 @@
 .. module:: pkgutil
    :synopsis: Utilities for the import system.
 
+**Source code:** :source:`Lib/pkgutil.py`
+
+--------------
+
 This module provides utilities for the import system, in particular package
 support.
 
@@ -77,8 +81,8 @@
    newly created by a path hook.
 
    If there is no importer, a wrapper around the basic import machinery is
-   returned.  This wrapper is never inserted into the importer cache (None is
-   inserted instead).
+   returned.  This wrapper is never inserted into the importer cache (``None``
+   is inserted instead).
 
    The cache (or part of it) can be cleared manually if a rescan of
    :data:`sys.path_hooks` is necessary.

Modified: python/branches/pep-3151/Doc/library/platform.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/platform.rst	(original)
+++ python/branches/pep-3151/Doc/library/platform.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Marc-Andre Lemburg <mal at egenix.com>
 .. sectionauthor:: Bjorn Pettersen <bpettersen at corp.fairisaac.com>
 
+**Source code:** :source:`Lib/platform.py`
+
+--------------
 
 .. note::
 
@@ -36,6 +39,16 @@
    and then only if the executable points to the Python interpreter.  Reasonable
    defaults are used when the above needs are not met.
 
+   .. note::
+
+      On Mac OS X (and perhaps other platforms), executable files may be
+      universal files containing multiple architectures.
+
+      To get at the "64-bitness" of the current interpreter, it is more
+      reliable to query the :attr:`sys.maxsize` attribute::
+
+         is_64bits = sys.maxsize > 2**32
+
 
 .. function:: machine()
 
@@ -186,7 +199,7 @@
 
    .. note::
 
-      Note: this function works best with Mark Hammond's
+      This function works best with Mark Hammond's
       :mod:`win32all` package installed, but also on Python 2.3 and
       later (support for this was added in Python 2.6). It obviously
       only runs on Win32 compatible platforms.

Modified: python/branches/pep-3151/Doc/library/plistlib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/plistlib.rst	(original)
+++ python/branches/pep-3151/Doc/library/plistlib.rst	Sat Feb 26 08:16:32 2011
@@ -11,6 +11,10 @@
    pair: plist; file
    single: property list
 
+**Source code:** :source:`Lib/plistlib.py`
+
+--------------
+
 This module provides an interface for reading and writing the "property list"
 XML files used mainly by Mac OS X.
 

Modified: python/branches/pep-3151/Doc/library/poplib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/poplib.rst	(original)
+++ python/branches/pep-3151/Doc/library/poplib.rst	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,10 @@
 
 .. index:: pair: POP3; protocol
 
+**Source code:** :source:`Lib/poplib.py`
+
+--------------
+
 This module defines a class, :class:`POP3`, which encapsulates a connection to a
 POP3 server and implements the protocol as defined in :rfc:`1725`.  The
 :class:`POP3` class supports both the minimal and optional command sets.

Modified: python/branches/pep-3151/Doc/library/pprint.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pprint.rst	(original)
+++ python/branches/pep-3151/Doc/library/pprint.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/pprint.py`
+
+--------------
 
 The :mod:`pprint` module provides a capability to "pretty-print" arbitrary
 Python data structures in a form which can be used as input to the interpreter.

Modified: python/branches/pep-3151/Doc/library/profile.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/profile.rst	(original)
+++ python/branches/pep-3151/Doc/library/profile.rst	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,9 @@
 .. module:: profile
    :synopsis: Python source profiler.
 
+**Source code:** :source:`Lib/profile.py` and :source:`Lib/pstats.py`
+
+--------------
 
 .. _profiler-introduction:
 

Modified: python/branches/pep-3151/Doc/library/pty.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pty.rst	(original)
+++ python/branches/pep-3151/Doc/library/pty.rst	Sat Feb 26 08:16:32 2011
@@ -45,3 +45,50 @@
    a file descriptor. The defaults try to read 1024 bytes each time they are
    called.
 
+
+Example
+-------
+
+.. sectionauthor:: Steen Lumholt
+
+The following program acts like the Unix command :manpage:`script(1)`, using a
+pseudo-terminal to record all input and output of a terminal session in a
+"typescript". ::
+
+   import sys, os, time, getopt
+   import pty
+
+   mode = 'wb'
+   shell = 'sh'
+   filename = 'typescript'
+   if 'SHELL' in os.environ:
+       shell = os.environ['SHELL']
+
+   try:
+       opts, args = getopt.getopt(sys.argv[1:], 'ap')
+   except getopt.error as msg:
+       print('%s: %s' % (sys.argv[0], msg))
+       sys.exit(2)
+
+   for opt, arg in opts:
+       # option -a: append to typescript file
+       if opt == '-a':
+           mode = 'ab'
+       # option -p: use a Python shell as the terminal command
+       elif opt == '-p':
+           shell = sys.executable
+   if args:
+       filename = args[0]
+
+   script = open(filename, mode)
+
+   def read(fd):
+       data = os.read(fd, 1024)
+       script.write(data)
+       return data
+
+   sys.stdout.write('Script started, file is %s\n' % filename)
+   script.write(('Script started on %s\n' % time.asctime()).encode())
+   pty.spawn(shell, read)
+   script.write(('Script done on %s\n' % time.asctime()).encode())
+   sys.stdout.write('Script done, file is %s\n' % filename)

Modified: python/branches/pep-3151/Doc/library/py_compile.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/py_compile.rst	(original)
+++ python/branches/pep-3151/Doc/library/py_compile.rst	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,10 @@
 
 .. index:: pair: file; byte-code
 
+**Source code:** :source:`Lib/py_compile.py`
+
+--------------
+
 The :mod:`py_compile` module provides a function to generate a byte-code file
 from a source file, and another function used when the module source file is
 invoked as a script.
@@ -22,20 +26,29 @@
    Exception raised when an error occurs while attempting to compile the file.
 
 
-.. function:: compile(file, cfile=None, dfile=None, doraise=False)
+.. function:: compile(file, cfile=None, dfile=None, doraise=False, optimize=-1)
 
-   Compile a source file to byte-code and write out the byte-code cache  file.  The
-   source code is loaded from the file name *file*.  The  byte-code is written to
-   *cfile*, which defaults to the :PEP:`3147` path, ending in ``.pyc``
-   (``'.pyo`` if optimization is enabled in the current interpreter).  For
-   example, if *file* is ``/foo/bar/baz.py`` *cfile* will default to
-   ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2.  If *dfile* is specified, it is used as the
-   name of the source file in error messages instead of *file*.  If *doraise* is
-   true, a :exc:`PyCompileError` is raised when an error is encountered while
-   compiling *file*. If *doraise* is false (the default), an error string is
-   written to ``sys.stderr``, but no exception is raised.  This function
-   returns the path to byte-compiled file, i.e. whatever *cfile* value was
-   used.
+   Compile a source file to byte-code and write out the byte-code cache  file.
+   The source code is loaded from the file name *file*.  The  byte-code is
+   written to *cfile*, which defaults to the :PEP:`3147` path, ending in
+   ``.pyc`` (``.pyo`` if optimization is enabled in the current interpreter).
+   For example, if *file* is ``/foo/bar/baz.py`` *cfile* will default to
+   ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2.  If *dfile* is
+   specified, it is used as the name of the source file in error messages when
+   instead of *file*.  If *doraise* is true, a :exc:`PyCompileError` is raised
+   when an error is encountered while compiling *file*. If *doraise* is false
+   (the default), an error string is written to ``sys.stderr``, but no exception
+   is raised.  This function returns the path to byte-compiled file, i.e.
+   whatever *cfile* value was used.
+
+   *optimize* controls the optimization level and is passed to the built-in
+   :func:`compile` function.  The default of ``-1`` selects the optimization
+   level of the current interpreter.
+
+   .. versionchanged:: 3.2
+      Changed default value of *cfile* to be :PEP:`3147`-compliant.  Previous
+      default was *file* + ``'c'`` (``'o'`` if optimization was enabled).
+      Also added the *optimize* parameter.
 
 
 .. function:: main(args=None)
@@ -44,6 +57,11 @@
    line, if *args* is ``None``) are compiled and the resulting bytecode is
    cached in the normal manner.  This function does not search a directory
    structure to locate source files; it only compiles files named explicitly.
+   If ``'-'`` is the only parameter in args, the list of files is taken from
+   standard input.
+
+   .. versionchanged:: 3.2
+      Added support for ``'-'``.
 
 When this module is run as a script, the :func:`main` is used to compile all the
 files named on the command line.  The exit status is nonzero if one of the files

Modified: python/branches/pep-3151/Doc/library/pyclbr.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pyclbr.rst	(original)
+++ python/branches/pep-3151/Doc/library/pyclbr.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Supports information extraction for a Python class browser.
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/pyclbr.py`
+
+--------------
 
 The :mod:`pyclbr` module can be used to determine some limited information
 about the classes, methods and top-level functions defined in a module.  The

Modified: python/branches/pep-3151/Doc/library/pydoc.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pydoc.rst	(original)
+++ python/branches/pep-3151/Doc/library/pydoc.rst	Sat Feb 26 08:16:32 2011
@@ -12,6 +12,10 @@
    single: documentation; online
    single: help; online
 
+**Source code:** :source:`Lib/pydoc.py`
+
+--------------
+
 The :mod:`pydoc` module automatically generates documentation from Python
 modules.  The documentation can be presented as pages of text on the console,
 served to a Web browser, or saved to HTML files.
@@ -40,30 +44,43 @@
    executed on that occasion.  Use an ``if __name__ == '__main__':`` guard to
    only execute code when a file is invoked as a script and not just imported.
 
-Specifying a :option:`-w` flag before the argument will cause HTML documentation
+Specifying a ``-w`` flag before the argument will cause HTML documentation
 to be written out to a file in the current directory, instead of displaying text
 on the console.
 
-Specifying a :option:`-k` flag before the argument will search the synopsis
+Specifying a ``-k`` flag before the argument will search the synopsis
 lines of all available modules for the keyword given as the argument, again in a
 manner similar to the Unix :program:`man` command.  The synopsis line of a
 module is the first line of its documentation string.
 
 You can also use :program:`pydoc` to start an HTTP server on the local machine
-that will serve documentation to visiting Web browsers. :program:`pydoc`
-:option:`-p 1234` will start a HTTP server on port 1234, allowing you to browse
-the documentation at ``http://localhost:1234/`` in your preferred Web browser.
-:program:`pydoc` :option:`-g` will start the server and additionally bring up a
+that will serve documentation to visiting Web browsers.  :program:`pydoc -p 1234`
+will start a HTTP server on port 1234, allowing you to browse the
+documentation at ``http://localhost:1234/`` in your preferred Web browser.
+Specifying ``0`` as the port number will select an arbitrary unused port.
+
+:program:`pydoc -g` will start the server and additionally bring up a
 small :mod:`tkinter`\ -based graphical interface to help you search for
-documentation pages.
+documentation pages.  The ``-g`` option is deprecated, since the server can
+now be controlled directly from HTTP clients.
+
+:program:`pydoc -b` will start the server and additionally open a web
+browser to a module index page.  Each served page has a navigation bar at the
+top where you can *Get* help on an individual item, *Search* all modules with a
+keyword in their synopsis line, and go to the *Module index*, *Topics* and
+*Keywords* pages.
 
 When :program:`pydoc` generates documentation, it uses the current environment
-and path to locate modules.  Thus, invoking :program:`pydoc` :option:`spam`
+and path to locate modules.  Thus, invoking :program:`pydoc spam`
 documents precisely the version of the module you would get if you started the
 Python interpreter and typed ``import spam``.
 
 Module docs for core modules are assumed to reside in
-http://docs.python.org/library/.  This can be overridden by setting the
-:envvar:`PYTHONDOCS` environment variable to a different URL or to a local
-directory containing the Library Reference Manual pages.
+``http://docs.python.org/X.Y/library/`` where ``X`` and ``Y`` are the
+major and minor version numbers of the Python interpreter.  This can
+be overridden by setting the :envvar:`PYTHONDOCS` environment variable
+to a different URL or to a local directory containing the Library
+Reference Manual pages.
 
+.. versionchanged:: 3.2
+   Added the ``-b`` option, deprecated the ``-g`` option.

Modified: python/branches/pep-3151/Doc/library/pyexpat.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/pyexpat.rst	(original)
+++ python/branches/pep-3151/Doc/library/pyexpat.rst	Sat Feb 26 08:16:32 2011
@@ -153,6 +153,13 @@
    :attr:`ordered_attributes` and :attr:`specified_attributes` set to the values of
    this parser.
 
+.. method:: xmlparser.SetParamEntityParsing(flag)
+
+   Control parsing of parameter entities (including the external DTD subset).
+   Possible *flag* values are :const:`XML_PARAM_ENTITY_PARSING_NEVER`,
+   :const:`XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE` and
+   :const:`XML_PARAM_ENTITY_PARSING_ALWAYS`.  Return true if setting the flag
+   was successful.
 
 .. method:: xmlparser.UseForeignDTD([flag])
 

Modified: python/branches/pep-3151/Doc/library/queue.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/queue.rst	(original)
+++ python/branches/pep-3151/Doc/library/queue.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: queue
    :synopsis: A synchronized queue class.
 
+**Source code:** :source:`Lib/queue.py`
+
+--------------
 
 The :mod:`queue` module implements multi-producer, multi-consumer queues.
 It is especially useful in threaded programming when information must be
@@ -19,6 +22,7 @@
 the entries are kept sorted (using the :mod:`heapq` module) and the
 lowest valued entry is retrieved first.
 
+
 The :mod:`queue` module defines the following classes and exceptions:
 
 .. class:: Queue(maxsize=0)
@@ -59,12 +63,6 @@
    Exception raised when non-blocking :meth:`put` (or :meth:`put_nowait`) is called
    on a :class:`Queue` object which is full.
 
-.. seealso::
-
-   :class:`collections.deque` is an alternative implementation of unbounded
-   queues with fast atomic :func:`append` and :func:`popleft` operations that
-   do not require locking.
-
 
 .. _queueobjects:
 
@@ -175,3 +173,14 @@
 
    q.join()       # block until all tasks are done
 
+
+.. seealso::
+
+   Class :class:`multiprocessing.Queue`
+      A queue class for use in a multi-processing (rather than multi-threading)
+      context.
+
+   :class:`collections.deque` is an alternative implementation of unbounded
+   queues with fast atomic :func:`append` and :func:`popleft` operations that
+   do not require locking.
+

Modified: python/branches/pep-3151/Doc/library/quopri.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/quopri.rst	(original)
+++ python/branches/pep-3151/Doc/library/quopri.rst	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,10 @@
    pair: quoted-printable; encoding
    single: MIME; quoted-printable encoding
 
+**Source code:** :source:`Lib/quopri.py`
+
+--------------
+
 This module performs quoted-printable transport encoding and decoding, as
 defined in :rfc:`1521`: "MIME (Multipurpose Internet Mail Extensions) Part One:
 Mechanisms for Specifying and Describing the Format of Internet Message Bodies".
@@ -17,7 +21,6 @@
 :mod:`base64` module is more compact if there are many such characters, as when
 sending a graphics file.
 
-
 .. function:: decode(input, output, header=False)
 
    Decode the contents of the *input* file and write the resulting decoded binary
@@ -58,4 +61,3 @@
 
    Module :mod:`base64`
       Encode and decode MIME base64 data
-

Modified: python/branches/pep-3151/Doc/library/random.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/random.rst	(original)
+++ python/branches/pep-3151/Doc/library/random.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: random
    :synopsis: Generate pseudo-random numbers with various common distributions.
 
+**Source code:** :source:`Lib/random.py`
+
+--------------
 
 This module implements pseudo-random number generators for various
 distributions.
@@ -40,8 +43,8 @@
 uses the system function :func:`os.urandom` to generate random numbers
 from sources provided by the operating system.
 
-Bookkeeping functions:
 
+Bookkeeping functions:
 
 .. function:: seed([x], version=2)
 
@@ -228,41 +231,18 @@
    parameter.
 
 
-Alternative Generators:
+Alternative Generator:
 
 .. class:: SystemRandom([seed])
 
    Class that uses the :func:`os.urandom` function for generating random numbers
    from sources provided by the operating system. Not available on all systems.
-   Does not rely on software state and sequences are not reproducible. Accordingly,
+   Does not rely on software state, and sequences are not reproducible. Accordingly,
    the :meth:`seed` method has no effect and is ignored.
    The :meth:`getstate` and :meth:`setstate` methods raise
    :exc:`NotImplementedError` if called.
 
 
-Examples of basic usage::
-
-   >>> random.random()        # Random float x, 0.0 <= x < 1.0
-   0.37444887175646646
-   >>> random.uniform(1, 10)  # Random float x, 1.0 <= x < 10.0
-   1.1800146073117523
-   >>> random.randint(1, 10)  # Integer from 1 to 10, endpoints included
-   7
-   >>> random.randrange(0, 101, 2)  # Even integer from 0 to 100
-   26
-   >>> random.choice('abcdefghij')  # Choose a random element
-   'c'
-
-   >>> items = [1, 2, 3, 4, 5, 6, 7]
-   >>> random.shuffle(items)
-   >>> items
-   [7, 3, 2, 5, 6, 4, 1]
-
-   >>> random.sample([1, 2, 3, 4, 5],  3)  # Choose 3 elements
-   [4, 1, 5]
-
-
-
 .. seealso::
 
    M. Matsumoto and T. Nishimura, "Mersenne Twister: A 623-dimensionally
@@ -275,8 +255,9 @@
    random number generator with a long period and comparatively simple update
    operations.
 
+
 Notes on Reproducibility
-========================
+------------------------
 
 Sometimes it is useful to be able to reproduce the sequences given by a pseudo
 random number generator.  By re-using a seed value, the same sequence should be
@@ -290,3 +271,53 @@
 
 * The generator's :meth:`random` method will continue to produce the same
   sequence when the compatible seeder is given the same seed.
+
+.. _random-examples:
+
+Examples and Recipes
+--------------------
+
+Basic usage::
+
+   >>> random.random()                      # Random float x, 0.0 <= x < 1.0
+   0.37444887175646646
+
+   >>> random.uniform(1, 10)                # Random float x, 1.0 <= x < 10.0
+   1.1800146073117523
+
+   >>> random.randrange(10)                 # Integer from 0 to 9
+   7
+
+   >>> random.randrange(0, 101, 2)          # Even integer from 0 to 100
+   26
+
+   >>> random.choice('abcdefghij')          # Single random element
+   'c'
+
+   >>> items = [1, 2, 3, 4, 5, 6, 7]
+   >>> random.shuffle(items)
+   >>> items
+   [7, 3, 2, 5, 6, 4, 1]
+
+   >>> random.sample([1, 2, 3, 4, 5],  3)   # Three samples without replacement
+   [4, 1, 5]
+
+A common task is to make a :func:`random.choice` with weighted probababilites.
+
+If the weights are small integer ratios, a simple technique is to build a sample
+population with repeats::
+
+    >>> weighted_choices = [('Red', 3), ('Blue', 2), ('Yellow', 1), ('Green', 4)]
+    >>> population = [val for val, cnt in weighted_choices for i in range(cnt)]
+    >>> random.choice(population)
+    'Green'
+
+A more general approach is to arrange the weights in a cumulative distribution
+with :func:`itertools.accumulate`, and then locate the random value with
+:func:`bisect.bisect`::
+
+    >>> choices, weights = zip(*weighted_choices)
+    >>> cumdist = list(itertools.accumulate(weights))
+    >>> x = random.random() * cumdist[-1]
+    >>> choices[bisect.bisect(cumdist, x)]
+    'Blue'

Modified: python/branches/pep-3151/Doc/library/re.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/re.rst	(original)
+++ python/branches/pep-3151/Doc/library/re.rst	Sat Feb 26 08:16:32 2011
@@ -991,8 +991,10 @@
    The string passed to :meth:`~regex.match` or :meth:`~regex.search`.
 
 
-Examples
---------
+.. _re-examples:
+
+Regular Expression Examples
+---------------------------
 
 
 Checking For a Pair
@@ -1298,6 +1300,7 @@
     Token = collections.namedtuple('Token', 'typ value line column')
 
     def tokenize(s):
+        keywords = {'IF', 'THEN', 'FOR', 'NEXT', 'GOSUB', 'RETURN'}
         tok_spec = [
             ('NUMBER', r'\d+(\.\d*)?'), # Integer or decimal number
             ('ASSIGN', r':='),          # Assignment operator
@@ -1318,6 +1321,8 @@
                 line_start = pos
                 line += 1
             elif typ != 'SKIP':
+                if typ == 'ID' and val in keywords:
+                    typ = val
                 yield Token(typ, mo.group(typ), line, mo.start()-line_start)
             pos = mo.end()
             mo = gettok(s, pos)

Modified: python/branches/pep-3151/Doc/library/reprlib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/reprlib.rst	(original)
+++ python/branches/pep-3151/Doc/library/reprlib.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Alternate repr() implementation with size limits.
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/reprlib.py`
+
+--------------
 
 The :mod:`reprlib` module provides a means for producing object representations
 with limits on the size of the resulting strings. This is used in the Python

Modified: python/branches/pep-3151/Doc/library/resource.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/resource.rst	(original)
+++ python/branches/pep-3151/Doc/library/resource.rst	Sat Feb 26 08:16:32 2011
@@ -217,14 +217,14 @@
 
 .. data:: RUSAGE_SELF
 
-   :const:`RUSAGE_SELF` should be used to request information pertaining only to
-   the process itself.
+   Pass to :func:`getrusage` to request resources consumed by the calling
+   process, which is the sum of resources used by all threads in the process.
 
 
 .. data:: RUSAGE_CHILDREN
 
-   Pass to :func:`getrusage` to request resource information for child processes of
-   the calling process.
+   Pass to :func:`getrusage` to request resources consumed by child processes
+   of the calling process which have been terminated and waited for.
 
 
 .. data:: RUSAGE_BOTH
@@ -232,3 +232,10 @@
    Pass to :func:`getrusage` to request resources consumed by both the current
    process and child processes.  May not be available on all systems.
 
+
+.. data:: RUSAGE_THREAD
+
+   Pass to :func:`getrusage` to request resources consumed by the current
+   thread.  May not be available on all systems.
+
+   .. versionadded:: 3.2

Modified: python/branches/pep-3151/Doc/library/rlcompleter.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/rlcompleter.rst	(original)
+++ python/branches/pep-3151/Doc/library/rlcompleter.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Python identifier completion, suitable for the GNU readline library.
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
+**Source code:** :source:`Lib/rlcompleter.py`
+
+--------------
 
 The :mod:`rlcompleter` module defines a completion function suitable for the
 :mod:`readline` module by completing valid Python identifiers and keywords.

Modified: python/branches/pep-3151/Doc/library/runpy.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/runpy.rst	(original)
+++ python/branches/pep-3151/Doc/library/runpy.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Locate and run Python modules without importing them first.
 .. moduleauthor:: Nick Coghlan <ncoghlan at gmail.com>
 
+**Source code:** :source:`Lib/runpy.py`
+
+--------------
 
 The :mod:`runpy` module is used to locate and run Python modules without
 importing them first. Its main use is to implement the :option:`-m` command
@@ -70,6 +73,9 @@
    .. versionchanged:: 3.1
       Added ability to execute packages by looking for a ``__main__`` submodule.
 
+   .. versionchanged:: 3.2
+      Added ``__cached__`` global variable (see :PEP:`3147`).
+
 
 .. function:: run_path(file_path, init_globals=None, run_name=None)
 

Modified: python/branches/pep-3151/Doc/library/sched.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/sched.rst	(original)
+++ python/branches/pep-3151/Doc/library/sched.rst	Sat Feb 26 08:16:32 2011
@@ -7,10 +7,13 @@
 
 .. index:: single: event scheduling
 
+**Source code:** :source:`Lib/sched.py`
+
+--------------
+
 The :mod:`sched` module defines a class which implements a general purpose event
 scheduler:
 
-
 .. class:: scheduler(timefunc, delayfunc)
 
    The :class:`scheduler` class defines a generic interface to scheduling events.

Modified: python/branches/pep-3151/Doc/library/select.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/select.rst	(original)
+++ python/branches/pep-3151/Doc/library/select.rst	Sat Feb 26 08:16:32 2011
@@ -94,11 +94,13 @@
       library, and does not handle file descriptors that don't originate from
       WinSock.
 
-.. attribute:: select.PIPE_BUF
+.. attribute:: PIPE_BUF
+
+   The minimum number of bytes which can be written without blocking to a pipe
+   when the pipe has been reported as ready for writing by :func:`select`,
+   :func:`poll` or another interface in this module.  This doesn't apply
+   to other kind of file-like objects such as sockets.
 
-   Files reported as ready for writing by :func:`select`, :func:`poll` or
-   similar interfaces in this module are guaranteed to not block on a write
-   of up to :const:`PIPE_BUF` bytes.
    This value is guaranteed by POSIX to be at least 512.  Availability: Unix.
 
    .. versionadded:: 3.2

Modified: python/branches/pep-3151/Doc/library/shelve.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/shelve.rst	(original)
+++ python/branches/pep-3151/Doc/library/shelve.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,10 @@
 
 .. index:: module: pickle
 
+**Source code:** :source:`Lib/shelve.py`
+
+--------------
+
 A "shelf" is a persistent, dictionary-like object.  The difference with "dbm"
 databases is that the values (not the keys!) in a shelf can be essentially
 arbitrary Python objects --- anything that the :mod:`pickle` module can handle.
@@ -97,7 +101,7 @@
   implementation used.
 
 
-.. class:: Shelf(dict, protocol=None, writeback=False)
+.. class:: Shelf(dict, protocol=None, writeback=False, keyencoding='utf-8')
 
    A subclass of :class:`collections.MutableMapping` which stores pickled values
    in the *dict* object.
@@ -111,8 +115,15 @@
    This allows natural operations on mutable entries, but can consume much more
    memory and make sync and close take a long time.
 
+   The *keyencoding* parameter is the encoding used to encode keys before they
+   are used with the underlying dict.
+
+   .. versionadded:: 3.2
+      The *keyencoding* parameter; previously, keys were always encoded in
+      UTF-8.
 
-.. class:: BsdDbShelf(dict, protocol=None, writeback=False)
+
+.. class:: BsdDbShelf(dict, protocol=None, writeback=False, keyencoding='utf-8')
 
    A subclass of :class:`Shelf` which exposes :meth:`first`, :meth:`!next`,
    :meth:`previous`, :meth:`last` and :meth:`set_location` which are available
@@ -121,8 +132,8 @@
    modules.  The *dict* object passed to the constructor must support those
    methods.  This is generally accomplished by calling one of
    :func:`bsddb.hashopen`, :func:`bsddb.btopen` or :func:`bsddb.rnopen`.  The
-   optional *protocol* and *writeback* parameters have the same interpretation
-   as for the :class:`Shelf` class.
+   optional *protocol*, *writeback*, and *keyencoding* parameters have the same
+   interpretation as for the :class:`Shelf` class.
 
 
 .. class:: DbfilenameShelf(filename, flag='c', protocol=None, writeback=False)
@@ -158,8 +169,8 @@
    klist = list(d.keys()) # a list of all existing keys (slow!)
 
    # as d was opened WITHOUT writeback=True, beware:
-   d['xx'] = range(4)  # this works as expected, but...
-   d['xx'].append(5)   # *this doesn't!* -- d['xx'] is STILL range(4)!
+   d['xx'] = [0, 1, 2]    # this works as expected, but...
+   d['xx'].append(3)      # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!
 
    # having opened d without writeback=True, you need to code carefully:
    temp = d['xx']      # extracts the copy

Modified: python/branches/pep-3151/Doc/library/shlex.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/shlex.rst	(original)
+++ python/branches/pep-3151/Doc/library/shlex.rst	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,9 @@
 .. sectionauthor:: Eric S. Raymond <esr at snark.thyrsus.com>
 .. sectionauthor:: Gustavo Niemeyer <niemeyer at conectiva.com>
 
+**Source code:** :source:`Lib/shlex.py`
+
+--------------
 
 The :class:`shlex` class makes it easy to write lexical analyzers for simple
 syntaxes resembling that of the Unix shell.  This will often be useful for

Modified: python/branches/pep-3151/Doc/library/shutil.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/shutil.rst	(original)
+++ python/branches/pep-3151/Doc/library/shutil.rst	Sat Feb 26 08:16:32 2011
@@ -10,6 +10,10 @@
    single: file; copying
    single: copying files
 
+**Source code:** :source:`Lib/shutil.py`
+
+--------------
+
 The :mod:`shutil` module offers a number of high-level operations on files and
 collections of files.  In particular, functions are provided  which support file
 copying and removal. For operations on individual files, see also the
@@ -18,7 +22,7 @@
 .. warning::
 
    Even the higher-level file copying functions (:func:`copy`, :func:`copy2`)
-   can't copy all file metadata.
+   cannot copy all file metadata.
 
    On POSIX platforms, this means that file owner and group are lost as well
    as ACLs.  On Mac OS, the resource fork and other metadata are not used.
@@ -26,6 +30,7 @@
    not be correct. On Windows, file owners, ACLs and alternate data streams
    are not copied.
 
+
 Directory and files operations
 ------------------------------
 
@@ -229,19 +234,21 @@
    copytree(source, destination, ignore=_logpath)
 
 
-Archives operations
--------------------
+.. _archiving-operations:
+
+Archiving operations
+--------------------
 
 .. function:: make_archive(base_name, format, [root_dir, [base_dir, [verbose, [dry_run, [owner, [group, [logger]]]]]]])
 
-   Create an archive file (e.g. zip or tar) and returns its name.
+   Create an archive file (such as zip or tar) and return its name.
 
    *base_name* is the name of the file to create, including the path, minus
    any format-specific extension. *format* is the archive format: one of
    "zip", "tar", "bztar" (if the :mod:`bz2` module is available) or "gztar".
 
    *root_dir* is a directory that will be the root directory of the
-   archive; i.e. we typically chdir into *root_dir* before creating the
+   archive; for example, we typically chdir into *root_dir* before creating the
    archive.
 
    *base_dir* is the directory where we start archiving from;
@@ -253,6 +260,8 @@
    *owner* and *group* are used when creating a tar archive. By default,
    uses the current owner and group.
 
+   *logger* is an instance of :class:`logging.Logger`.
+
    .. versionadded:: 3.2
 
 
@@ -279,7 +288,7 @@
    Registers an archiver for the format *name*. *function* is a callable that
    will be used to invoke the archiver.
 
-   If given, *extra_args* is a sequence of ``(name, value)`` that will be
+   If given, *extra_args* is a sequence of ``(name, value)`` pairs that will be
    used as extra keywords arguments when the archiver callable is used.
 
    *description* is used by :func:`get_archive_formats` which returns the
@@ -311,7 +320,7 @@
    .. versionadded:: 3.2
 
 
-.. function:: register_unpack_format(name, extensions, function[, extra_args[,description]])
+.. function:: register_unpack_format(name, extensions, function[, extra_args[, description]])
 
    Registers an unpack format. *name* is the name of the format and
    *extensions* is a list of extensions corresponding to the format, like

Modified: python/branches/pep-3151/Doc/library/site.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/site.rst	(original)
+++ python/branches/pep-3151/Doc/library/site.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: site
    :synopsis: A standard way to reference site-specific modules.
 
+**Source code:** :source:`Lib/site.py`
+
+--------------
 
 **This module is automatically imported during initialization.** The automatic
 import can be suppressed using the interpreter's :option:`-S` option.

Modified: python/branches/pep-3151/Doc/library/smtpd.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/smtpd.rst	(original)
+++ python/branches/pep-3151/Doc/library/smtpd.rst	Sat Feb 26 08:16:32 2011
@@ -7,8 +7,9 @@
 .. moduleauthor:: Barry Warsaw <barry at zope.com>
 .. sectionauthor:: Moshe Zadka <moshez at moshez.org>
 
+**Source code:** :source:`Lib/smtpd.py`
 
-
+--------------
 
 This module offers several classes to implement SMTP (email) servers.
 
@@ -166,4 +167,4 @@
    DATA     Sets the internal state to :attr:`DATA` and stores remaining lines
             from the client in :attr:`received_data` until the terminator
             "\r\n.\r\n" is received.
-   ======== ===================================================================
\ No newline at end of file
+   ======== ===================================================================

Modified: python/branches/pep-3151/Doc/library/smtplib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/smtplib.rst	(original)
+++ python/branches/pep-3151/Doc/library/smtplib.rst	Sat Feb 26 08:16:32 2011
@@ -10,6 +10,10 @@
    pair: SMTP; protocol
    single: Simple Mail Transfer Protocol
 
+**Source code:** :source:`Lib/smtplib.py`
+
+--------------
+
 The :mod:`smtplib` module defines an SMTP client session object that can be used
 to send mail to any Internet machine with an SMTP or ESMTP listener daemon.  For
 details of SMTP and ESMTP operation, consult :rfc:`821` (Simple Mail Transfer

Modified: python/branches/pep-3151/Doc/library/sndhdr.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/sndhdr.rst	(original)
+++ python/branches/pep-3151/Doc/library/sndhdr.rst	Sat Feb 26 08:16:32 2011
@@ -10,6 +10,10 @@
    single: A-LAW
    single: u-LAW
 
+**Source code:** :source:`Lib/sndhdr.py`
+
+--------------
+
 The :mod:`sndhdr` provides utility functions which attempt to determine the type
 of sound data which is in a file.  When these functions are able to determine
 what type of sound data is stored in a file, they return a tuple ``(type,

Modified: python/branches/pep-3151/Doc/library/socket.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/socket.rst	(original)
+++ python/branches/pep-3151/Doc/library/socket.rst	Sat Feb 26 08:16:32 2011
@@ -14,16 +14,6 @@
    Some behavior may be platform dependent, since calls are made to the operating
    system socket APIs.
 
-For an introduction to socket programming (in C), see the following papers: An
-Introductory 4.3BSD Interprocess Communication Tutorial, by Stuart Sechrest and
-An Advanced 4.3BSD Interprocess Communication Tutorial, by Samuel J.  Leffler et
-al, both in the 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 to the manual pages; for Windows,
-see the WinSock (or Winsock 2) specification. For IPv6-ready APIs, readers may
-want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6.
-
 .. index:: object: socket
 
 The Python interface is a straightforward transliteration of the Unix system
@@ -34,26 +24,72 @@
 files, buffer allocation on receive operations is automatic, and buffer length
 is implicit on send operations.
 
-Socket addresses are represented as follows: A single string is used for the
-:const:`AF_UNIX` address family. A pair ``(host, port)`` is used for the
-:const:`AF_INET` address family, where *host* is a string representing either a
-hostname in Internet domain notation like ``'daring.cwi.nl'`` or an IPv4 address
-like ``'100.50.200.5'``, and *port* is an integral port number. For
-:const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo,
-scopeid)`` is used, where *flowinfo* and *scopeid* represents ``sin6_flowinfo``
-and ``sin6_scope_id`` member in :const:`struct sockaddr_in6` in C. For
-:mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for
-backward compatibility. Note, however, omission of *scopeid* can cause problems
-in manipulating scoped IPv6 addresses. Other address families are currently not
-supported. The address format required by a particular socket object is
-automatically selected based on the address family specified when the socket
-object was created.
+
+.. seealso::
+
+   Module :mod:`socketserver`
+      Classes that simplify writing network servers.
+
+   Module :mod:`ssl`
+      A TLS/SSL wrapper for socket objects.
+
+
+Socket families
+---------------
+
+Depending on the system and the build options, various socket families
+are supported by this module.
+
+Socket addresses are represented as follows:
+
+- A single string is used for the :const:`AF_UNIX` address family.
+
+- A pair ``(host, port)`` is used for the :const:`AF_INET` address family,
+  where *host* is a string representing either a hostname in Internet domain
+  notation like ``'daring.cwi.nl'`` or an IPv4 address like ``'100.50.200.5'``,
+  and *port* is an integral port number.
+
+- For :const:`AF_INET6` address family, a four-tuple ``(host, port, flowinfo,
+  scopeid)`` is used, where *flowinfo* and *scopeid* represent the ``sin6_flowinfo``
+  and ``sin6_scope_id`` members in :const:`struct sockaddr_in6` in C.  For
+  :mod:`socket` module methods, *flowinfo* and *scopeid* can be omitted just for
+  backward compatibility.  Note, however, omission of *scopeid* can cause problems
+  in manipulating scoped IPv6 addresses.
+
+- :const:`AF_NETLINK` sockets are represented as pairs ``(pid, groups)``.
+
+- Linux-only support for TIPC is available using the :const:`AF_TIPC`
+  address family.  TIPC is an open, non-IP based networked protocol designed
+  for use in clustered computer environments.  Addresses are represented by a
+  tuple, and the fields depend on the address type. The general tuple form is
+  ``(addr_type, v1, v2, v3 [, scope])``, where:
+
+  - *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or
+    TIPC_ADDR_ID.
+  - *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and
+    TIPC_NODE_SCOPE.
+  - If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type, *v2* is
+    the port identifier, and *v3* should be 0.
+
+    If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server type, *v2*
+    is the lower port number, and *v3* is the upper port number.
+
+    If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
+    reference, and *v3* should be set to 0.
+
+    If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
+    reference, and *v3* should be set to 0.
+
+- Certain other address families (:const:`AF_BLUETOOTH`, :const:`AF_PACKET`)
+  support specific representations.
+
+  .. XXX document them!
 
 For IPv4 addresses, two special forms are accepted instead of a host address:
 the empty string represents :const:`INADDR_ANY`, and the string
-``'<broadcast>'`` represents :const:`INADDR_BROADCAST`. The behavior is not
-available for IPv6 for backward compatibility, therefore, you may want to avoid
-these if you intend to support IPv6 with your Python programs.
+``'<broadcast>'`` represents :const:`INADDR_BROADCAST`.  This behavior is not
+compatible with IPv6, therefore, you may want to avoid these if you intend
+to support IPv6 with your Python programs.
 
 If you use a hostname in the *host* portion of IPv4/v6 socket address, the
 program may show a nondeterministic behavior, as Python uses the first address
@@ -62,40 +98,18 @@
 resolution and/or the host configuration.  For deterministic behavior use a
 numeric address in *host* portion.
 
-AF_NETLINK sockets are represented as  pairs ``pid, groups``.
-
-
-Linux-only support for TIPC is also available using the :const:`AF_TIPC`
-address family. TIPC is an open, non-IP based networked protocol designed
-for use in clustered computer environments.  Addresses are represented by a
-tuple, and the fields depend on the address type. The general tuple form is
-``(addr_type, v1, v2, v3 [, scope])``, where:
-
-- *addr_type* is one of TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, or
-  TIPC_ADDR_ID.
-- *scope* is one of TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and
-  TIPC_NODE_SCOPE.
-- If *addr_type* is TIPC_ADDR_NAME, then *v1* is the server type, *v2* is
-  the port identifier, and *v3* should be 0.
-
-  If *addr_type* is TIPC_ADDR_NAMESEQ, then *v1* is the server type, *v2*
-  is the lower port number, and *v3* is the upper port number.
-
-  If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
-  reference, and *v3* should be set to 0.
-
-  If *addr_type* is TIPC_ADDR_ID, then *v1* is the node, *v2* is the
-  reference, and *v3* should be set to 0.
-
-
 All errors raise exceptions.  The normal exceptions for invalid argument types
 and out-of-memory conditions can be raised; errors related to socket or address
-semantics raise the error :exc:`socket.error`.
+semantics raise :exc:`socket.error` or one of its subclasses.
 
 Non-blocking mode is supported through :meth:`~socket.setblocking`.  A
 generalization of this based on timeouts is supported through
 :meth:`~socket.settimeout`.
 
+
+Module contents
+---------------
+
 The module :mod:`socket` exports the following constants and functions:
 
 
@@ -134,8 +148,8 @@
 .. exception:: timeout
 
    This exception is raised when a timeout occurs on a socket which has had
-   timeouts enabled via a prior call to :meth:`settimeout`.  The accompanying value
-   is a string whose value is currently always "timed out".
+   timeouts enabled via a prior call to :meth:`~socket.settimeout`.  The
+   accompanying value is a string whose value is currently always "timed out".
 
 
 .. data:: AF_UNIX
@@ -144,7 +158,8 @@
 
    These constants represent the address (and protocol) families, used for the
    first argument to :func:`socket`.  If the :const:`AF_UNIX` constant is not
-   defined then this protocol is unsupported.
+   defined then this protocol is unsupported.  More constants may be available
+   depending on the system.
 
 
 .. data:: SOCK_STREAM
@@ -154,8 +169,9 @@
           SOCK_SEQPACKET
 
    These constants represent the socket types, used for the second argument to
-   :func:`socket`. (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be
-   generally useful.)
+   :func:`socket`.  More constants may be available depending on the system.
+   (Only :const:`SOCK_STREAM` and :const:`SOCK_DGRAM` appear to be generally
+   useful.)
 
 .. data:: SOCK_CLOEXEC
           SOCK_NONBLOCK
@@ -499,9 +515,10 @@
 
 .. function:: setdefaulttimeout(timeout)
 
-   Set the default timeout in floating seconds for new socket objects. A value of
-   ``None`` indicates that new socket objects have no timeout. When the socket
-   module is first imported, the default is ``None``.
+   Set the default timeout in floating seconds for new socket objects.  When
+   the socket module is first imported, the default is ``None``.  See
+   :meth:`~socket.settimeout` for possible values and their respective
+   meanings.
 
 
 .. data:: SocketType
@@ -510,12 +527,6 @@
    same as ``type(socket(...))``.
 
 
-.. seealso::
-
-   Module :mod:`socketserver`
-      Classes that simplify writing network servers.
-
-
 .. _socket-objects:
 
 Socket Objects
@@ -545,6 +556,12 @@
    remote end will receive no more data (after queued data is flushed). Sockets are
    automatically closed when they are garbage-collected.
 
+   .. note::
+      :meth:`close()` releases the resource associated with a connection but
+      does not necessarily close the connection immediately.  If you want
+      to close the connection in a timely fashion, call :meth:`shutdown()`
+      before :meth:`close()`.
+
 
 .. method:: socket.connect(address)
 
@@ -608,6 +625,13 @@
    to decode C structures encoded as byte strings).
 
 
+.. method:: socket.gettimeout()
+
+   Return the timeout in floating seconds associated with socket operations,
+   or ``None`` if no timeout is set.  This reflects the last call to
+   :meth:`setblocking` or :meth:`settimeout`.
+
+
 .. method:: socket.ioctl(control, option)
 
    :platform: Windows
@@ -627,18 +651,25 @@
    is system-dependent (usually 5).
 
 
-.. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, errors=None, newline=None)
+.. method:: socket.makefile(mode='r', buffering=None, *, encoding=None, \
+                            errors=None, newline=None)
 
    .. index:: single: I/O control; buffering
 
-   Return a :term:`file object` associated with the socket.  The exact
-   returned type depends on the arguments given to :meth:`makefile`.  These
-   arguments are interpreted the same way as by the built-in :func:`open`
-   function.
-
-   Closing the file object won't close the socket unless there are no
-   remaining references to the socket.  The socket must be in blocking mode
-   (it can not have a timeout).
+   Return a :term:`file object` associated with the socket.  The exact returned
+   type depends on the arguments given to :meth:`makefile`.  These arguments are
+   interpreted the same way as by the built-in :func:`open` function.
+
+   Closing the file object won't close the socket unless there are no remaining
+   references to the socket.  The socket must be in blocking mode; it can have
+   a timeout, but the file object's internal buffer may end up in a inconsistent
+   state if a timeout occurs.
+
+   .. note::
+
+      On Windows, the file-like object created by :meth:`makefile` cannot be
+      used where a file object with a file descriptor is expected, such as the
+      stream arguments of :meth:`subprocess.Popen`.
 
 
 .. method:: socket.recv(bufsize[, flags])
@@ -712,55 +743,26 @@
 
 .. method:: socket.setblocking(flag)
 
-   Set blocking or non-blocking mode of the socket: if *flag* is 0, the socket is
-   set to non-blocking, else to blocking mode.  Initially all sockets are in
-   blocking mode.  In non-blocking mode, if a :meth:`recv` call doesn't find any
-   data, or if a :meth:`send` call can't immediately dispose of the data, a
-   :exc:`error` exception is raised; in blocking mode, the calls block until they
-   can proceed. ``s.setblocking(0)`` is equivalent to ``s.settimeout(0.0)``;
-   ``s.setblocking(1)`` is equivalent to ``s.settimeout(None)``.
+   Set blocking or non-blocking mode of the socket: if *flag* is false, the
+   socket is set to non-blocking, else to blocking mode.
 
+   This method is a shorthand for certain :meth:`~socket.settimeout` calls:
 
-.. method:: socket.settimeout(value)
+   * ``sock.setblocking(True)`` is equivalent to ``sock.settimeout(None)``
 
-   Set a timeout on blocking socket operations.  The *value* argument can be a
-   nonnegative float expressing seconds, or ``None``. If a float is given,
-   subsequent socket operations will raise a :exc:`timeout` exception if the
-   timeout period *value* has elapsed before the operation has completed.  Setting
-   a timeout of ``None`` disables timeouts on socket operations.
-   ``s.settimeout(0.0)`` is equivalent to ``s.setblocking(0)``;
-   ``s.settimeout(None)`` is equivalent to ``s.setblocking(1)``.
+   * ``sock.setblocking(False)`` is equivalent to ``sock.settimeout(0.0)``
 
 
-.. method:: socket.gettimeout()
-
-   Return the timeout in floating seconds associated with socket operations, or
-   ``None`` if no timeout is set.  This reflects the last call to
-   :meth:`setblocking` or :meth:`settimeout`.
+.. method:: socket.settimeout(value)
 
+   Set a timeout on blocking socket operations.  The *value* argument can be a
+   nonnegative floating point number expressing seconds, or ``None``.
+   If a non-zero value is given, subsequent socket operations will raise a
+   :exc:`timeout` exception if the timeout period *value* has elapsed before
+   the operation has completed.  If zero is given, the socket is put in
+   non-blocking mode. If ``None`` is given, the socket is put in blocking mode.
 
-Some notes on socket blocking and timeouts: A socket object can be in one of
-three modes: blocking, non-blocking, or timeout.  Sockets are always created in
-blocking mode.  In blocking mode, operations block until complete or
-the system returns an error (such as connection timed out).  In
-non-blocking mode, operations fail (with an error that is unfortunately
-system-dependent) if they cannot be completed immediately.  In timeout mode,
-operations fail if they cannot be completed within the timeout specified for the
-socket or if the system returns an error.  The :meth:`~socket.setblocking`
-method is simply a shorthand for certain :meth:`~socket.settimeout` calls.
-
-Timeout mode internally sets the socket in non-blocking mode.  The blocking and
-timeout modes are shared between file descriptors and socket objects that refer
-to the same network endpoint.  A consequence of this is that file objects
-returned by the :meth:`~socket.makefile` method must only be used when the
-socket is in blocking mode; in timeout or non-blocking mode file operations
-that cannot be completed immediately will fail.
-
-Note that the :meth:`~socket.connect` operation is subject to the timeout
-setting, and in general it is recommended to call :meth:`~socket.settimeout`
-before calling :meth:`~socket.connect` or pass a timeout parameter to
-:meth:`create_connection`.  The system network stack may return a connection
-timeout error of its own regardless of any Python socket timeout setting.
+   For further information, please consult the :ref:`notes on socket timeouts <socket-timeouts>`.
 
 
 .. method:: socket.setsockopt(level, optname, value)
@@ -806,6 +808,61 @@
    The socket protocol.
 
 
+
+.. _socket-timeouts:
+
+Notes on socket timeouts
+------------------------
+
+A socket object can be in one of three modes: blocking, non-blocking, or
+timeout.  Sockets are by default always created in blocking mode, but this
+can be changed by calling :func:`setdefaulttimeout`.
+
+* In *blocking mode*, operations block until complete or the system returns
+  an error (such as connection timed out).
+
+* In *non-blocking mode*, operations fail (with an error that is unfortunately
+  system-dependent) if they cannot be completed immediately: functions from the
+  :mod:`select` can be used to know when and whether a socket is available for
+  reading or writing.
+
+* In *timeout mode*, operations fail if they cannot be completed within the
+  timeout specified for the socket (they raise a :exc:`timeout` exception)
+  or if the system returns an error.
+
+.. note::
+   At the operating system level, sockets in *timeout mode* are internally set
+   in non-blocking mode.  Also, the blocking and timeout modes are shared between
+   file descriptors and socket objects that refer to the same network endpoint.
+   This implementation detail can have visible consequences if e.g. you decide
+   to use the :meth:`~socket.fileno()` of a socket.
+
+Timeouts and the ``connect`` method
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+The :meth:`~socket.connect` operation is also subject to the timeout
+setting, and in general it is recommended to call :meth:`~socket.settimeout`
+before calling :meth:`~socket.connect` or pass a timeout parameter to
+:meth:`create_connection`.  However, the system network stack may also
+return a connection timeout error of its own regardless of any Python socket
+timeout setting.
+
+Timeouts and the ``accept`` method
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+If :func:`getdefaulttimeout` is not :const:`None`, sockets returned by
+the :meth:`~socket.accept` method inherit that timeout.  Otherwise, the
+behaviour depends on settings of the listening socket:
+
+* if the listening socket is in *blocking mode* or in *timeout mode*,
+  the socket returned by :meth:`~socket.accept` is in *blocking mode*;
+
+* if the listening socket is in *non-blocking mode*, whether the socket
+  returned by :meth:`~socket.accept` is in blocking or non-blocking mode
+  is operating system-dependent.  If you want to ensure cross-platform
+  behaviour, it is recommended you manually override this setting.
+
+
 .. _socket-example:
 
 Example
@@ -950,3 +1007,21 @@
 
    # disabled promiscuous mode
    s.ioctl(socket.SIO_RCVALL, socket.RCVALL_OFF)
+
+
+.. seealso::
+
+   For an introduction to socket programming (in C), see the following papers:
+
+   - *An Introductory 4.3BSD Interprocess Communication Tutorial*, by Stuart Sechrest
+
+   - *An Advanced 4.3BSD Interprocess Communication Tutorial*, by Samuel J.  Leffler et
+     al,
+
+   both in the 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 to the manual pages; for Windows,
+   see the WinSock (or Winsock 2) specification.  For IPv6-ready APIs, readers may
+   want to refer to :rfc:`3493` titled Basic Socket Interface Extensions for IPv6.
+

Modified: python/branches/pep-3151/Doc/library/socketserver.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/socketserver.rst	(original)
+++ python/branches/pep-3151/Doc/library/socketserver.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,10 @@
 .. module:: socketserver
    :synopsis: A framework for network servers.
 
+**Source code:** :source:`Lib/socketserver.py`
+
+--------------
+
 The :mod:`socketserver` module simplifies the task of writing network servers.
 
 There are four basic server classes: :class:`TCPServer` uses the Internet TCP

Modified: python/branches/pep-3151/Doc/library/someos.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/someos.rst	(original)
+++ python/branches/pep-3151/Doc/library/someos.rst	Sat Feb 26 08:16:32 2011
@@ -14,11 +14,11 @@
 
    select.rst
    threading.rst
-   dummy_threading.rst
-   _thread.rst
-   _dummy_thread.rst
-   concurrent.futures.rst
    multiprocessing.rst
+   concurrent.futures.rst
    mmap.rst
    readline.rst
    rlcompleter.rst
+   dummy_threading.rst
+   _thread.rst
+   _dummy_thread.rst

Modified: python/branches/pep-3151/Doc/library/sqlite3.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/sqlite3.rst	(original)
+++ python/branches/pep-3151/Doc/library/sqlite3.rst	Sat Feb 26 08:16:32 2011
@@ -710,7 +710,7 @@
 This is a good approach if you write the class yourself. Let's suppose you have
 a class like this::
 
-   class Point(object):
+   class Point:
        def __init__(self, x, y):
            self.x, self.y = x, y
 
@@ -888,4 +888,4 @@
 .. [#f1] The sqlite3 module is not built with loadable extension support by
   default, because some platforms (notably Mac OS X) have SQLite libraries which
   are compiled without this feature. To get loadable extension support, you must
-  modify setup.py and and remove the line that sets SQLITE_OMIT_LOAD_EXTENSION.
+  pass --enable-loadable-sqlite-extensions to configure.

Modified: python/branches/pep-3151/Doc/library/ssl.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/ssl.rst	(original)
+++ python/branches/pep-3151/Doc/library/ssl.rst	Sat Feb 26 08:16:32 2011
@@ -1,8 +1,8 @@
-:mod:`ssl` --- SSL wrapper for socket objects
-=============================================
+:mod:`ssl` --- TLS/SSL wrapper for socket objects
+=================================================
 
 .. module:: ssl
-   :synopsis: SSL wrapper for socket objects
+   :synopsis: TLS/SSL wrapper for socket objects
 
 .. moduleauthor:: Bill Janssen <bill.janssen at gmail.com>
 .. sectionauthor::  Bill Janssen <bill.janssen at gmail.com>
@@ -12,6 +12,10 @@
 
 .. index:: TLS, SSL, Transport Layer Security, Secure Sockets Layer
 
+**Source code:** :source:`Lib/ssl.py`
+
+--------------
+
 This module provides access to Transport Layer Security (often known as "Secure
 Sockets Layer") encryption and peer authentication facilities for network
 sockets, both client-side and server-side.  This module uses the OpenSSL
@@ -536,6 +540,15 @@
    following an `OpenSSL specific layout
    <http://www.openssl.org/docs/ssl/SSL_CTX_load_verify_locations.html>`_.
 
+.. method:: SSLContext.set_default_verify_paths()
+
+   Load a set of default "certification authority" (CA) certificates from
+   a filesystem path defined when building the OpenSSL library.  Unfortunately,
+   there's no easy way to know whether this method succeeds: no error is
+   returned if no certificates are to be found.  When the OpenSSL library is
+   provided as part of the operating system, though, it is likely to be
+   configured properly.
+
 .. method:: SSLContext.set_ciphers(ciphers)
 
    Set the available ciphers for sockets created with this context.
@@ -759,11 +772,11 @@
 should use the following idiom::
 
    try:
-      import ssl
+       import ssl
    except ImportError:
-      pass
+       pass
    else:
-      [ do something that requires SSL support ]
+       ... # do something that requires SSL support
 
 Client-side operation
 ^^^^^^^^^^^^^^^^^^^^^
@@ -874,26 +887,27 @@
 method to create a server-side SSL socket for the connection::
 
    while True:
-      newsocket, fromaddr = bindsocket.accept()
-      connstream = context.wrap_socket(newsocket, server_side=True)
-      try:
-         deal_with_client(connstream)
-      finally:
-         connstream.close()
+       newsocket, fromaddr = bindsocket.accept()
+       connstream = context.wrap_socket(newsocket, server_side=True)
+       try:
+           deal_with_client(connstream)
+       finally:
+           connstream.shutdown(socket.SHUT_RDWR)
+           connstream.close()
 
 Then you'll read data from the ``connstream`` and do something with it till you
 are finished with the client (or the client is finished with you)::
 
    def deal_with_client(connstream):
-      data = connstream.recv(1024)
-      # empty data means the client is finished with us
-      while data:
-         if not do_something(connstream, data):
-            # we'll assume do_something returns False
-            # when we're finished with client
-            break
-         data = connstream.recv(1024)
-      # finished with client
+       data = connstream.recv(1024)
+       # empty data means the client is finished with us
+       while data:
+           if not do_something(connstream, data):
+               # we'll assume do_something returns False
+               # when we're finished with client
+               break
+           data = connstream.recv(1024)
+       # finished with client
 
 And go back to listening for new client connections (of course, a real server
 would probably handle each client connection in a separate thread, or put

Modified: python/branches/pep-3151/Doc/library/stat.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/stat.rst	(original)
+++ python/branches/pep-3151/Doc/library/stat.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
               os.lstat() and os.fstat().
 .. sectionauthor:: Skip Montanaro <skip at automatrix.com>
 
+**Source code:** :source:`Lib/stat.py`
+
+--------------
 
 The :mod:`stat` module defines constants and functions for interpreting the
 results of :func:`os.stat`, :func:`os.fstat` and :func:`os.lstat` (if they

Modified: python/branches/pep-3151/Doc/library/stdtypes.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/stdtypes.rst	(original)
+++ python/branches/pep-3151/Doc/library/stdtypes.rst	Sat Feb 26 08:16:32 2011
@@ -197,8 +197,8 @@
    operator: in
    operator: not in
 
-Two more operations with the same syntactic priority, ``in`` and ``not in``, are
-supported only by sequence types (below).
+Two more operations with the same syntactic priority, :keyword:`in` and
+:keyword:`not in`, are supported only by sequence types (below).
 
 
 .. _typesnumeric:
@@ -836,8 +836,8 @@
 must have a trailing comma, such as ``(d,)``.
 
 Objects of type range are created using the :func:`range` function.  They don't
-support slicing, concatenation or repetition, and using ``in``, ``not in``,
-:func:`min` or :func:`max` on them is inefficient.
+support concatenation or repetition, and using :func:`min` or :func:`max` on
+them is inefficient.
 
 Most sequence types support the following operations.  The ``in`` and ``not in``
 operations have the same priorities as the comparison operations.  The ``+`` and
@@ -846,7 +846,7 @@
 
 This table lists the sequence operations sorted in ascending priority
 (operations in the same box have the same priority).  In the table, *s* and *t*
-are sequences of the same type; *n*, *i* and *j* are integers:
+are sequences of the same type; *n*, *i*, *j* and *k* are integers.
 
 +------------------+--------------------------------+----------+
 | Operation        | Result                         | Notes    |
@@ -876,6 +876,12 @@
 +------------------+--------------------------------+----------+
 | ``max(s)``       | largest item of *s*            |          |
 +------------------+--------------------------------+----------+
+| ``s.index(i)``   | index of the first occurence   |          |
+|                  | of *i* in *s*                  |          |
++------------------+--------------------------------+----------+
+| ``s.count(i)``   | total number of occurences of  |          |
+|                  | *i* in *s*                     |          |
++------------------+--------------------------------+----------+
 
 Sequence types also support comparisons.  In particular, tuples and lists are
 compared lexicographically by comparing corresponding elements.  This means that
@@ -1072,20 +1078,26 @@
 .. method:: str.isalnum()
 
    Return true if all characters in the string are alphanumeric and there is at
-   least one character, false otherwise.
+   least one character, false otherwise.  A character ``c`` is alphanumeric if one
+   of the following returns ``True``: ``c.isalpha()``, ``c.isdecimal()``,
+   ``c.isdigit()``, or ``c.isnumeric()``.
 
 
 .. method:: str.isalpha()
 
    Return true if all characters in the string are alphabetic and there is at least
-   one character, false otherwise.
+   one character, false otherwise.  Alphabetic characters are those characters defined
+   in the Unicode character database as "Letter", i.e., those with general category
+   property being one of "Lm", "Lt", "Lu", "Ll", or "Lo".  Note that this is different
+   from the "Alphabetic" property defined in the Unicode Standard.
 
 
 .. method:: str.isdecimal()
 
    Return true if all characters in the string are decimal
    characters and there is at least one character, false
-   otherwise. Decimal characters include digit characters, and all characters
+   otherwise. Decimal characters are those from general category "Nd". This category
+   includes digit characters, and all characters
    that that can be used to form decimal-radix numbers, e.g. U+0660,
    ARABIC-INDIC DIGIT ZERO.
 
@@ -1093,7 +1105,9 @@
 .. method:: str.isdigit()
 
    Return true if all characters in the string are digits and there is at least one
-   character, false otherwise.
+   character, false otherwise.  Digits include decimal characters and digits that need
+   special handling, such as the compatibility superscript digits.  Formally, a digit
+   is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.
 
 
 .. method:: str.isidentifier()
@@ -1105,7 +1119,9 @@
 .. method:: str.islower()
 
    Return true if all cased characters in the string are lowercase and there is at
-   least one cased character, false otherwise.
+   least one cased character, false otherwise.  Cased characters are those with
+   general category property being one of "Lu", "Ll", or "Lt" and lowercase characters
+   are those with general category property "Ll".
 
 
 .. method:: str.isnumeric()
@@ -1114,7 +1130,8 @@
    characters, and there is at least one character, false
    otherwise. Numeric characters include digit characters, and all characters
    that have the Unicode numeric value property, e.g. U+2155,
-   VULGAR FRACTION ONE FIFTH.
+   VULGAR FRACTION ONE FIFTH.  Formally, numeric characters are those with the property
+   value Numeric_Type=Digit, Numeric_Type=Decimal or Numeric_Type=Numeric.
 
 
 .. method:: str.isprintable()
@@ -1131,8 +1148,9 @@
 .. method:: str.isspace()
 
    Return true if there are only whitespace characters in the string and there is
-   at least one character, false otherwise.
-
+   at least one character, false otherwise.  Whitespace characters  are those
+   characters defined in the Unicode character database as "Other" or "Separator"
+   and those with bidirectional property being one of "WS", "B", or "S".
 
 .. method:: str.istitle()
 
@@ -1144,7 +1162,9 @@
 .. method:: str.isupper()
 
    Return true if all cased characters in the string are uppercase and there is at
-   least one cased character, false otherwise.
+   least one cased character, false otherwise. Cased characters are those with
+   general category property being one of "Lu", "Ll", or "Lt" and uppercase characters
+   are those with general category property "Lu".
 
 
 .. method:: str.join(iterable)
@@ -1575,16 +1595,14 @@
 The :class:`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.
+range it represents.
 
-Range objects have relatively little behavior: they support indexing,
-iteration, the :func:`len` function, and the following methods.
+Range objects have relatively little behavior: they support indexing, contains,
+iteration, the :func:`len` function, and the following methods:
 
 .. method:: range.count(x)
 
-   Return the number of *i*'s for which ``s[i] == x``.  Normally the
-   result will be 0 or 1, but it could be greater if *x* defines an
-   unusual equality function.
+   Return the number of *i*'s for which ``s[i] == x``.
 
     .. versionadded:: 3.2
 
@@ -1624,6 +1642,8 @@
    single: append() (sequence method)
    single: extend() (sequence method)
    single: count() (sequence method)
+   single: clear() (sequence method)
+   single: copy() (sequence method)
    single: index() (sequence method)
    single: insert() (sequence method)
    single: pop() (sequence method)
@@ -1655,6 +1675,12 @@
 | ``s.extend(x)``              | same as ``s[len(s):len(s)] =   | \(2)                |
 |                              | x``                            |                     |
 +------------------------------+--------------------------------+---------------------+
+| ``s.clear()``                | remove all items from ``s``    | \(8)                |
+|                              |                                |                     |
++------------------------------+--------------------------------+---------------------+
+| ``s.copy()``                 | return a shallow copy of ``s`` | \(8)                |
+|                              |                                |                     |
++------------------------------+--------------------------------+---------------------+
 | ``s.count(x)``               | return number of *i*'s for     |                     |
 |                              | which ``s[i] == x``            |                     |
 +------------------------------+--------------------------------+---------------------+
@@ -1731,7 +1757,11 @@
       detect that the list has been mutated during a sort.
 
 (8)
-   :meth:`sort` is not supported by :class:`bytearray` objects.
+   :meth:`clear`, :meth:`!copy` and :meth:`sort` are not supported by
+   :class:`bytearray` objects.
+
+    .. versionadded:: 3.3
+       :meth:`clear` and :meth:`!copy` methods.
 
 
 .. _bytes-methods:
@@ -2099,8 +2129,20 @@
       returned or raised by the ``__missing__(key)`` call if the key is not
       present. No other operations or methods invoke :meth:`__missing__`. If
       :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
-      :meth:`__missing__` must be a method; it cannot be an instance variable. For
-      an example, see :class:`collections.defaultdict`.
+      :meth:`__missing__` must be a method; it cannot be an instance variable::
+
+          >>> class Counter(dict):
+          ...     def __missing__(self, key):
+          ...         return 0
+          >>> c = Counter()
+          >>> c['red']
+          0
+          >>> c['red'] += 1
+          >>> c['red']
+          1
+
+      See :class:`collections.Counter` for a complete implementation including
+      other methods helpful for accumulating and managing tallies.
 
    .. describe:: d[key] = value
 
@@ -2275,8 +2317,8 @@
 ===============
 
 :class:`memoryview` objects allow Python code to access the internal data
-of an object that supports the buffer protocol without copying.  Memory
-is generally interpreted as simple bytes.
+of an object that supports the :ref:`buffer protocol <bufferobjects>` without
+copying.  Memory is generally interpreted as simple bytes.
 
 .. class:: memoryview(obj)
 
@@ -2415,6 +2457,10 @@
       A tuple of integers the length of :attr:`ndim` giving the size in bytes to
       access each element for each dimension of the array.
 
+   .. attribute:: readonly
+
+      A bool indicating whether the memory is read only.
+
    .. memoryview.suboffsets isn't documented because it only seems useful for C
 
 
@@ -2429,12 +2475,9 @@
    single: protocol; context management
 
 Python's :keyword:`with` statement supports the concept of a runtime context
-defined by a context manager.  This is implemented using two separate methods
+defined by a context manager.  This is implemented using a pair of methods
 that allow user-defined classes to define a runtime context that is entered
-before the statement body is executed and exited when the statement ends.
-
-The :dfn:`context management protocol` consists of a pair of methods that need
-to be provided for a context manager object to define a runtime context:
+before the statement body is executed and exited when the statement ends:
 
 
 .. method:: contextmanager.__enter__()
@@ -2482,9 +2525,9 @@
 their implementation of the context management protocol. See the
 :mod:`contextlib` module for some examples.
 
-Python's :term:`generator`\s and the ``contextlib.contextmanager`` :term:`decorator`
+Python's :term:`generator`\s and the :class:`contextlib.contextmanager` decorator
 provide a convenient way to implement these protocols.  If a generator function is
-decorated with the ``contextlib.contextmanager`` decorator, it will return a
+decorated with the :class:`contextlib.contextmanager` decorator, it will return a
 context manager implementing the necessary :meth:`__enter__` and
 :meth:`__exit__` methods, rather than the iterator produced by an undecorated
 generator function.

Modified: python/branches/pep-3151/Doc/library/string.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/string.rst	(original)
+++ python/branches/pep-3151/Doc/library/string.rst	Sat Feb 26 08:16:32 2011
@@ -5,16 +5,15 @@
    :synopsis: Common string operations.
 
 
-.. index:: module: re
+.. seealso::
 
-The :mod:`string` module contains a number of useful constants and classes
-for string formatting.  In addition, Python's built-in string classes
-support the sequence type methods described in the :ref:`typesseq`
-section, and also the string-specific methods described in the
-:ref:`string-methods` section.  To output formatted strings, see the
-:ref:`string-formatting` section.  Also, see the :mod:`re` module for
-string functions based on regular expressions.
+   :ref:`typesseq`
 
+   :ref:`string-methods`
+
+**Source code:** :source:`Lib/string.py`
+
+--------------
 
 String constants
 ----------------
@@ -91,7 +90,7 @@
 
    The :class:`Formatter` class has the following public methods:
 
-   .. method:: format(format_string, *args, *kwargs)
+   .. method:: format(format_string, *args, **kwargs)
 
       :meth:`format` is the primary API method.  It takes a format template
       string, and an arbitrary set of positional and keyword argument.
@@ -311,10 +310,10 @@
    | Option  | Meaning                                                  |
    +=========+==========================================================+
    | ``'<'`` | Forces the field to be left-aligned within the available |
-   |         | space (this is the default).                             |
+   |         | space (this is the default for most objects).            |
    +---------+----------------------------------------------------------+
    | ``'>'`` | Forces the field to be right-aligned within the          |
-   |         | available space.                                         |
+   |         | available space (this is the default for numbers).       |
    +---------+----------------------------------------------------------+
    | ``'='`` | Forces the padding to be placed after the sign (if any)  |
    |         | but before the digits.  This is used for printing fields |
@@ -345,9 +344,18 @@
    |         | positive numbers, and a minus sign on negative numbers.  |
    +---------+----------------------------------------------------------+
 
-The ``'#'`` option is only valid for integers, and only for binary, octal, or
-hexadecimal output.  If present, it specifies that the output will be prefixed
-by ``'0b'``, ``'0o'``, or ``'0x'``, respectively.
+
+The ``'#'`` option causes the "alternate form" to be used for the
+conversion.  The alternate form is defined differently for different
+types.  This option is only valid for integer, float, complex and
+Decimal types. For integers, when binary, octal, or hexadecimal output
+is used, this option adds the prefix respective ``'0b'``, ``'0o'``, or
+``'0x'`` to the output value. For floats, complex and Decimal the
+alternate form causes the result of the conversion to always contain a
+decimal-point character, even if no digits follow it. Normally, a
+decimal-point character appears in the result of these conversions
+only if a digit follows it. In addition, for ``'g'`` and ``'G'``
+conversions, trailing zeros are not removed from the result.
 
 The ``','`` option signals the use of a comma for a thousands separator.
 For a locale aware separator, use the ``'n'`` integer presentation type
@@ -587,7 +595,7 @@
 Nesting arguments and more complex examples::
 
    >>> for align, text in zip('<^>', ['left', 'center', 'right']):
-   ...     '{0:{align}{fill}16}'.format(text, fill=align, align=align)
+   ...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
    ...
    'left<<<<<<<<<<<<'
    '^^^^^center^^^^^'

Modified: python/branches/pep-3151/Doc/library/struct.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/struct.rst	(original)
+++ python/branches/pep-3151/Doc/library/struct.rst	Sat Feb 26 08:16:32 2011
@@ -164,58 +164,53 @@
 +--------+--------------------------+--------------------+----------------+------------+
 | ``c``  | :c:type:`char`           | bytes of length 1  | 1              |            |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``b``  | :c:type:`signed char`    | integer            | 1              | \(1),\(4)  |
+| ``b``  | :c:type:`signed char`    | integer            | 1              | \(1),\(3)  |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``B``  | :c:type:`unsigned char`  | integer            | 1              | \(4)       |
+| ``B``  | :c:type:`unsigned char`  | integer            | 1              | \(3)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``?``  | :c:type:`_Bool`          | bool               | 1              | \(2)       |
+| ``?``  | :c:type:`_Bool`          | bool               | 1              | \(1)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``h``  | :c:type:`short`          | integer            | 2              | \(4)       |
+| ``h``  | :c:type:`short`          | integer            | 2              | \(3)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``H``  | :c:type:`unsigned short` | integer            | 2              | \(4)       |
+| ``H``  | :c:type:`unsigned short` | integer            | 2              | \(3)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``i``  | :c:type:`int`            | integer            | 4              | \(4)       |
+| ``i``  | :c:type:`int`            | integer            | 4              | \(3)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``I``  | :c:type:`unsigned int`   | integer            | 4              | \(4)       |
+| ``I``  | :c:type:`unsigned int`   | integer            | 4              | \(3)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``l``  | :c:type:`long`           | integer            | 4              | \(4)       |
+| ``l``  | :c:type:`long`           | integer            | 4              | \(3)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``L``  | :c:type:`unsigned long`  | integer            | 4              | \(4)       |
+| ``L``  | :c:type:`unsigned long`  | integer            | 4              | \(3)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``q``  | :c:type:`long long`      | integer            | 8              | \(3), \(4) |
+| ``q``  | :c:type:`long long`      | integer            | 8              | \(2), \(3) |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``Q``  | :c:type:`unsigned long   | integer            | 8              | \(3), \(4) |
+| ``Q``  | :c:type:`unsigned long   | integer            | 8              | \(2), \(3) |
 |        | long`                    |                    |                |            |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``f``  | :c:type:`float`          | float              | 4              | \(5)       |
+| ``f``  | :c:type:`float`          | float              | 4              | \(4)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``d``  | :c:type:`double`         | float              | 8              | \(5)       |
+| ``d``  | :c:type:`double`         | float              | 8              | \(4)       |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``s``  | :c:type:`char[]`         | bytes              |                | \(1)       |
+| ``s``  | :c:type:`char[]`         | bytes              |                |            |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``p``  | :c:type:`char[]`         | bytes              |                | \(1)       |
+| ``p``  | :c:type:`char[]`         | bytes              |                |            |
 +--------+--------------------------+--------------------+----------------+------------+
-| ``P``  | :c:type:`void \*`        | integer            |                | \(6)       |
+| ``P``  | :c:type:`void \*`        | integer            |                | \(5)       |
 +--------+--------------------------+--------------------+----------------+------------+
 
 Notes:
 
 (1)
-   The ``c``, ``s`` and ``p`` conversion codes operate on :class:`bytes`
-   objects, but packing with such codes also supports :class:`str` objects,
-   which are encoded using UTF-8.
-
-(2)
    The ``'?'`` conversion code corresponds to the :c:type:`_Bool` type defined by
    C99. If this type is not available, it is simulated using a :c:type:`char`. In
    standard mode, it is always represented by one byte.
 
-(3)
+(2)
    The ``'q'`` and ``'Q'`` conversion codes are available in native mode only if
    the platform C compiler supports C :c:type:`long long`, or, on Windows,
    :c:type:`__int64`.  They are always available in standard modes.
 
-(4)
+(3)
    When attempting to pack a non-integer using any of the integer conversion
    codes, if the non-integer has a :meth:`__index__` method then that method is
    called to convert the argument to an integer before packing.
@@ -223,12 +218,12 @@
    .. versionchanged:: 3.2
       Use of the :meth:`__index__` method for non-integers is new in 3.2.
 
-(5)
+(4)
    For the ``'f'`` and ``'d'`` conversion codes, the packed representation uses
    the IEEE 754 binary32 (for ``'f'``) or binary64 (for ``'d'``) format,
    regardless of the floating-point format used by the platform.
 
-(6)
+(5)
    The ``'P'`` format character is only available for the native byte ordering
    (selected as the default or with the ``'@'`` byte order character). The byte
    order character ``'='`` chooses to use little- or big-endian ordering based
@@ -310,9 +305,9 @@
 The ordering of format characters may have an impact on size since the padding
 needed to satisfy alignment requirements is different::
 
-    >>> pack('ci', '*', 0x12131415)
+    >>> pack('ci', b'*', 0x12131415)
     b'*\x00\x00\x00\x12\x13\x14\x15'
-    >>> pack('ic', 0x12131415, '*')
+    >>> pack('ic', 0x12131415, b'*')
     b'\x12\x13\x14\x15*'
     >>> calcsize('ci')
     8

Modified: python/branches/pep-3151/Doc/library/subprocess.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/subprocess.rst	(original)
+++ python/branches/pep-3151/Doc/library/subprocess.rst	Sat Feb 26 08:16:32 2011
@@ -28,7 +28,7 @@
 This module defines one class called :class:`Popen`:
 
 
-.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=False, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False)
+.. class:: Popen(args, bufsize=0, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=())
 
    Arguments are:
 
@@ -76,6 +76,24 @@
 
       Popen(['/bin/sh', '-c', args[0], args[1], ...])
 
+   .. warning::
+
+      Executing shell commands that incorporate unsanitized input from an
+      untrusted source makes a program vulnerable to `shell injection
+      <http://en.wikipedia.org/wiki/Shell_injection#Shell_injection>`_,
+      a serious security flaw which can result in arbitrary command execution.
+      For this reason, the use of *shell=True* is **strongly discouraged** in cases
+      where the command string is constructed from external input::
+
+         >>> from subprocess import call
+         >>> filename = input("What file would you like to display?\n")
+         What file would you like to display?
+         non_existent; rm -rf / #
+         >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
+
+      *shell=False* does not suffer from this vulnerability; the above Note may be
+      helpful in getting code using *shell=False* to work.
+
    On Windows: the :class:`Popen` class uses CreateProcess() to execute the child
    program, which operates on strings.  If *args* is a sequence, it will be
    converted to a string using the :meth:`list2cmdline` method.  Please note that
@@ -135,12 +153,22 @@
 
    If *close_fds* is true, all file descriptors except :const:`0`, :const:`1` and
    :const:`2` will be closed before the child process is executed. (Unix only).
-   Or, on Windows, if *close_fds* is true then no handles will be inherited by the
+   The default varies by platform:  Always true on Unix.  On Windows it is
+   true when *stdin*/*stdout*/*stderr* are :const:`None`, false otherwise.
+   On Windows, if *close_fds* is true then no handles will be inherited by the
    child process.  Note that on Windows, you cannot set *close_fds* to true and
    also redirect the standard handles by setting *stdin*, *stdout* or *stderr*.
 
-   If *shell* is :const:`True`, the specified command will be executed through the
-   shell.
+   .. versionchanged:: 3.2
+      The default for *close_fds* was changed from :const:`False` to
+      what is described above.
+
+   *pass_fds* is an optional sequence of file descriptors to keep open
+   between the parent and child.  Providing any *pass_fds* forces
+   *close_fds* to be :const:`True`.  (Unix only)
+
+   .. versionadded:: 3.2
+      The *pass_fds* parameter was added.
 
    If *cwd* is not ``None``, the child's current directory will be changed to *cwd*
    before it is executed.  Note that this directory is not considered when
@@ -190,6 +218,16 @@
    underlying CreateProcess() function.  They can specify things such as appearance
    of the main window and priority for the new process.  (Windows only)
 
+   Popen objects are supported as context managers via the :keyword:`with` statement,
+   closing any open file descriptors on exit.
+   ::
+
+      with Popen(["ifconfig"], stdout=PIPE) as proc:
+          log.write(proc.stdout.read())
+
+   .. versionchanged:: 3.2
+      Added context manager support.
+
 
 .. data:: PIPE
 
@@ -481,8 +519,11 @@
    ==>
    p1 = Popen(["dmesg"], stdout=PIPE)
    p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
+   p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
    output = p2.communicate()[0]
 
+The p1.stdout.close() call after starting the p2 is important in order for p1
+to receive a SIGPIPE if p2 exits before p1.
 
 Replacing :func:`os.system`
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^
@@ -621,4 +662,5 @@
 * ``stdin=PIPE`` and ``stdout=PIPE`` must be specified.
 
 * popen2 closes all file descriptors by default, but you have to specify
-  ``close_fds=True`` with :class:`Popen`.
+  ``close_fds=True`` with :class:`Popen` to guarantee this behavior on
+  all platforms or past Python versions.

Modified: python/branches/pep-3151/Doc/library/sunau.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/sunau.rst	(original)
+++ python/branches/pep-3151/Doc/library/sunau.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Provide an interface to the Sun AU sound format.
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 
+**Source code:** :source:`Lib/sunau.py`
+
+--------------
 
 The :mod:`sunau` module provides a convenient interface to the Sun AU sound
 format.  Note that this module is interface-compatible with the modules

Modified: python/branches/pep-3151/Doc/library/symbol.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/symbol.rst	(original)
+++ python/branches/pep-3151/Doc/library/symbol.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Constants representing internal nodes of the parse tree.
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/symbol.py`
+
+--------------
 
 This module provides constants which represent the numeric values of internal
 nodes of the parse tree.  Unlike most Python constants, these use lower-case

Modified: python/branches/pep-3151/Doc/library/sys.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/sys.rst	(original)
+++ python/branches/pep-3151/Doc/library/sys.rst	Sat Feb 26 08:16:32 2011
@@ -99,13 +99,39 @@
 
 .. function:: displayhook(value)
 
-   If *value* is not ``None``, this function prints it to ``sys.stdout``, and saves
-   it in ``builtins._``.
+   If *value* is not ``None``, this function prints ``repr(value)`` to
+   ``sys.stdout``, and saves *value* in ``builtins._``. If ``repr(value)`` is
+   not encodable to ``sys.stdout.encoding`` with ``sys.stdout.errors`` error
+   handler (which is probably ``'strict'``), encode it to
+   ``sys.stdout.encoding`` with ``'backslashreplace'`` error handler.
 
    ``sys.displayhook`` is called on the result of evaluating an :term:`expression`
    entered in an interactive Python session.  The display of these values can be
    customized by assigning another one-argument function to ``sys.displayhook``.
 
+   Pseudo-code::
+
+       def displayhook(value):
+           if value is None:
+               return
+           # Set '_' to None to avoid recursion
+           builtins._ = None
+           text = repr(value)
+           try:
+               sys.stdout.write(text)
+           except UnicodeEncodeError:
+               bytes = text.encode(sys.stdout.encoding, 'backslashreplace')
+               if hasattr(sys.stdout, 'buffer'):
+                   sys.stdout.buffer.write(bytes)
+               else:
+                   text = bytes.decode(sys.stdout.encoding, 'strict')
+                   sys.stdout.write(text)
+           sys.stdout.write("\n")
+           builtins._ = value
+
+   .. versionchanged:: 3.2
+      Use ``'backslashreplace'`` error handler on :exc:`UnicodeEncodeError`.
+
 
 .. function:: excepthook(type, value, traceback)
 
@@ -169,7 +195,7 @@
 
    A string giving the site-specific directory prefix where the platform-dependent
    Python files are installed; by default, this is also ``'/usr/local'``.  This can
-   be set at build time with the :option:`--exec-prefix` argument to the
+   be set at build time with the ``--exec-prefix`` argument to the
    :program:`configure` script.  Specifically, all configuration files (e.g. the
    :file:`pyconfig.h` header file) are installed in the directory ``exec_prefix +
    '/lib/pythonversion/config'``, and shared library modules are installed in
@@ -238,6 +264,11 @@
    +------------------------------+------------------------------------------+
    | :const:`bytes_warning`       | -b                                       |
    +------------------------------+------------------------------------------+
+   | :const:`quiet`               | -q                                       |
+   +------------------------------+------------------------------------------+
+
+   .. versionchanged:: 3.2
+      Added ``quiet`` attribute for the new :option:`-q` flag.
 
 
 .. data:: float_info
@@ -389,6 +420,9 @@
    additional garbage collector overhead if the object is managed by the garbage
    collector.
 
+   See `recursive sizeof recipe <http://code.activestate.com/recipes/577504>`_
+   for an example of using :func:`getsizeof` recursively to find the size of
+   containers and all their contents.
 
 .. function:: getswitchinterval()
 
@@ -600,7 +634,7 @@
     imported. The :meth:`find_module` method is called at least with the
     absolute name of the module being imported. If the module to be imported is
     contained in package then the parent package's :attr:`__path__` attribute
-    is passed in as a second argument. The method returns :keyword:`None` if
+    is passed in as a second argument. The method returns ``None`` if
     the module cannot be found, else returns a :term:`loader`.
 
     :data:`sys.meta_path` is searched before any implicit default finders or
@@ -653,7 +687,7 @@
     A dictionary acting as a cache for :term:`finder` objects. The keys are
     paths that have been passed to :data:`sys.path_hooks` and the values are
     the finders that are found. If a path is a valid file system path but no
-    explicit finder is found on :data:`sys.path_hooks` then :keyword:`None` is
+    explicit finder is found on :data:`sys.path_hooks` then ``None`` is
     stored to represent the implicit default finder should be used. If the path
     is not an existing path then :class:`imp.NullImporter` is set.
 
@@ -685,7 +719,7 @@
 
    A string giving the site-specific directory prefix where the platform
    independent Python files are installed; by default, this is the string
-   ``'/usr/local'``.  This can be set at build time with the :option:`--prefix`
+   ``'/usr/local'``.  This can be set at build time with the ``--prefix``
    argument to the :program:`configure` script.  The main collection of Python
    library modules is installed in the directory ``prefix + '/lib/pythonversion'``
    while the platform independent header files (all except :file:`pyconfig.h`) are
@@ -862,7 +896,7 @@
 
    Activate dumping of VM measurements using the Pentium timestamp counter, if
    *on_flag* is true. Deactivate these dumps if *on_flag* is off. The function is
-   available only if Python was compiled with :option:`--with-tsc`. To understand
+   available only if Python was compiled with ``--with-tsc``. To understand
    the output of this dump, read :file:`Python/ceval.c` in the Python sources.
 
    .. impl-detail::

Modified: python/branches/pep-3151/Doc/library/sysconfig.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/sysconfig.rst	(original)
+++ python/branches/pep-3151/Doc/library/sysconfig.rst	Sat Feb 26 08:16:32 2011
@@ -5,10 +5,15 @@
    :synopsis: Python's configuration information
 .. moduleauthor:: Tarek Ziade <tarek at ziade.org>
 .. sectionauthor:: Tarek Ziade <tarek at ziade.org>
-.. versionadded:: 3.2
 .. index::
    single: configuration information
 
+**Source code:** :source:`Lib/sysconfig.py`
+
+.. versionadded:: 3.2
+
+--------------
+
 The :mod:`sysconfig` module provides access to Python's configuration
 information like the list of installation paths and the configuration variables
 relevant for the current platform.

Modified: python/branches/pep-3151/Doc/library/tabnanny.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/tabnanny.rst	(original)
+++ python/branches/pep-3151/Doc/library/tabnanny.rst	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,10 @@
 
 .. rudimentary documentation based on module comments
 
+**Source code:** :source:`Lib/tabnanny.py`
+
+--------------
+
 For the time being this module is intended to be called as a script. However it
 is possible to import it into an IDE and use the function :func:`check`
 described below.

Modified: python/branches/pep-3151/Doc/library/tarfile.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/tarfile.rst	(original)
+++ python/branches/pep-3151/Doc/library/tarfile.rst	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,9 @@
 .. moduleauthor:: Lars Gustäbel <lars at gustaebel.de>
 .. sectionauthor:: Lars Gustäbel <lars at gustaebel.de>
 
+**Source code:** :source:`Lib/tarfile.py`
+
+--------------
 
 The :mod:`tarfile` module makes it possible to read and write tar
 archives, including those using gzip or bz2 compression.
@@ -370,19 +373,20 @@
       and :meth:`close`, and also supports iteration over its lines.
 
 
-.. method:: TarFile.add(name, arcname=None, recursive=True, exclude=None, filter=None)
+.. method:: TarFile.add(name, arcname=None, recursive=True, exclude=None, *, filter=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 :const:`False`. If *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
-   (:const:`True`) or added (:const:`False`). If *filter* is specified it must
-   be a function that takes a :class:`TarInfo` object argument and returns the
-   changed :class:`TarInfo` object. If it instead returns :const:`None` the :class:`TarInfo`
-   object will be excluded from the archive. See :ref:`tar-examples` for an
-   example.
+   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
+   :const:`False`. If *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 (:const:`True`) or added
+   (:const:`False`). If *filter* is specified it must be a keyword argument.  It
+   should be a function that takes a :class:`TarInfo` object argument and
+   returns the changed :class:`TarInfo` object. If it instead returns
+   :const:`None` the :class:`TarInfo` object will be excluded from the
+   archive. See :ref:`tar-examples` for an example.
 
    .. versionchanged:: 3.2
       Added the *filter* parameter.

Modified: python/branches/pep-3151/Doc/library/telnetlib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/telnetlib.rst	(original)
+++ python/branches/pep-3151/Doc/library/telnetlib.rst	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,10 @@
 
 .. index:: single: protocol; Telnet
 
+**Source code:** :source:`Lib/telnetlib.py`
+
+--------------
+
 The :mod:`telnetlib` module provides a :class:`Telnet` class that implements the
 Telnet protocol.  See :rfc:`854` for details about the protocol. In addition, it
 provides symbolic constants for the protocol characters (see below), and for the

Modified: python/branches/pep-3151/Doc/library/tempfile.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/tempfile.rst	(original)
+++ python/branches/pep-3151/Doc/library/tempfile.rst	Sat Feb 26 08:16:32 2011
@@ -12,6 +12,10 @@
    pair: temporary; file name
    pair: temporary; file
 
+**Source code:** :source:`Lib/tempfile.py`
+
+--------------
+
 This module generates temporary files and directories.  It works on all
 supported platforms.  It provides three new functions,
 :func:`NamedTemporaryFile`, :func:`mkstemp`, and :func:`mkdtemp`, which should

Modified: python/branches/pep-3151/Doc/library/test.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/test.rst	(original)
+++ python/branches/pep-3151/Doc/library/test.rst	Sat Feb 26 08:16:32 2011
@@ -6,11 +6,11 @@
 .. sectionauthor:: Brett Cannon <brett at python.org>
 
 .. note::
-    The :mod:`test` package is meant for internal use by Python only. It is
-    documented for the benefit of the core developers of Python. Any use of
-    this package outside of Python's standard library is discouraged as code
-    mentioned here can change or be removed without notice between releases of
-    Python.
+   The :mod:`test` package is meant for internal use by Python only. It is
+   documented for the benefit of the core developers of Python. Any use of
+   this package outside of Python's standard library is discouraged as code
+   mentioned here can change or be removed without notice between releases of
+   Python.
 
 
 The :mod:`test` package contains all regression tests for Python as well as the
@@ -154,33 +154,35 @@
 
 .. _regrtest:
 
-Running tests using :mod:`test.regrtest`
-----------------------------------------
+Running tests using the command-line interface
+----------------------------------------------
 
-:mod:`test.regrtest` can be used as a script to drive Python's regression test
-suite. Running the script by itself automatically starts running all regression
+The :mod:`test` package can be run as a script to drive Python's regression
+test suite, thanks to the :option:`-m` option: :program:`python -m test`. Under
+the hood, it uses :mod:`test.regrtest`; the call :program:`python -m
+test.regrtest` used in previous Python versions still works).
+Running the script by itself automatically starts running all regression
 tests in the :mod:`test` package. It does this by finding all modules in the
 package whose name starts with ``test_``, importing them, and executing the
 function :func:`test_main` if present. The names of tests to execute may also
 be passed to the script. Specifying a single regression test (:program:`python
-regrtest.py` :option:`test_spam.py`) will minimize output and only print
+-m test test_spam`) will minimize output and only print
 whether the test passed or failed and thus minimize output.
 
-Running :mod:`test.regrtest` directly allows what resources are available for
-tests to use to be set. You do this by using the :option:`-u` command-line
-option. Run :program:`python regrtest.py` :option:`-uall` to turn on all
-resources; specifying :option:`all` as an option for :option:`-u` enables all
+Running :mod:`test` directly allows what resources are available for
+tests to use to be set. You do this by using the ``-u`` command-line
+option. Run :program:`python -m test -uall` to turn on all
+resources; specifying ``all`` as an option for ``-u`` enables all
 possible resources. If all but one resource is desired (a more common case), a
 comma-separated list of resources that are not desired may be listed after
-:option:`all`. The command :program:`python regrtest.py`
-:option:`-uall,-audio,-largefile` will run :mod:`test.regrtest` with all
-resources except the :option:`audio` and :option:`largefile` resources. For a
-list of all resources and more command-line options, run :program:`python
-regrtest.py` :option:`-h`.
+``all``. The command :program:`python -m test -uall,-audio,-largefile`
+will run :mod:`test` with all resources except the ``audio`` and
+``largefile`` resources. For a list of all resources and more command-line
+options, run :program:`python -m test -h`.
 
 Some other ways to execute the regression tests depend on what platform the
-tests are being executed on. On Unix, you can run :program:`make`
-:option:`test` at the top-level directory where Python was built. On Windows,
+tests are being executed on. On Unix, you can run :program:`make test` at the
+top-level directory where Python was built. On Windows,
 executing :program:`rt.bat` from your :file:`PCBuild` directory will run all
 regression tests.
 

Modified: python/branches/pep-3151/Doc/library/textwrap.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/textwrap.rst	(original)
+++ python/branches/pep-3151/Doc/library/textwrap.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Greg Ward <gward at python.net>
 .. sectionauthor:: Greg Ward <gward at python.net>
 
+**Source code:** :source:`Lib/textwrap.py`
+
+--------------
 
 The :mod:`textwrap` module provides two convenience functions, :func:`wrap` and
 :func:`fill`, as well as :class:`TextWrapper`, the class that does all the work,
@@ -13,7 +16,6 @@
 or two  text strings, the convenience functions should be good enough;
 otherwise,  you should use an instance of :class:`TextWrapper` for efficiency.
 
-
 .. function:: wrap(text, width=70, **kwargs)
 
    Wraps the single paragraph in *text* (a string) so every line is at most
@@ -117,6 +119,13 @@
          each tab character will be replaced by a single space, which is *not*
          the same as tab expansion.
 
+      .. note::
+
+         If :attr:`replace_whitespace` is false, newlines may appear in the
+         middle of a line and cause strange output. For this reason, text should
+         be split into paragraphs (using :meth:`str.splitlines` or similar)
+         which are wrapped separately.
+
 
    .. attribute:: drop_whitespace
 

Modified: python/branches/pep-3151/Doc/library/threading.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/threading.rst	(original)
+++ python/branches/pep-3151/Doc/library/threading.rst	Sat Feb 26 08:16:32 2011
@@ -1,9 +1,12 @@
-:mod:`threading` --- Higher-level threading interface
-=====================================================
+:mod:`threading` --- Thread-based parallelism
+=============================================
 
 .. module:: threading
-   :synopsis: Higher-level threading interface.
+   :synopsis: Thread-based parallelism.
 
+**Source code:** :source:`Lib/threading.py`
+
+--------------
 
 This module constructs higher-level threading interfaces on top of the lower
 level :mod:`_thread` module.  See also the :mod:`queue` module.
@@ -17,6 +20,18 @@
    methods and functions in this module in the Python 2.x series are still
    supported by this module.
 
+.. impl-detail::
+
+   Due to the :term:`Global Interpreter Lock`, in CPython only one thread
+   can execute Python code at once (even though certain performance-oriented
+   libraries might overcome this limitation).
+   If you want your application to make better of use of the computational
+   resources of multi-core machines, you are advised to use
+   :mod:`multiprocessing` or :class:`concurrent.futures.ProcessPoolExecutor`.
+   However, threading is still an appropriate model if you want to run
+   multiple I/O-bound tasks simultaneously.
+
+
 This module defines the following functions and objects:
 
 
@@ -226,7 +241,7 @@
 A thread can be flagged as a "daemon thread".  The significance of this flag is
 that the entire Python program exits when only daemon threads are left.  The
 initial value is inherited from the creating thread.  The flag can be set
-through the :attr:`daemon` property.
+through the :attr:`daemon` property or the *daemon* constructor argument.
 
 There is a "main thread" object; this corresponds to the initial thread of
 control in the Python program.  It is not a daemon thread.
@@ -239,7 +254,8 @@
 impossible to detect the termination of alien threads.
 
 
-.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={})
+.. class:: Thread(group=None, target=None, name=None, args=(), kwargs={},
+                  verbose=None, *, daemon=None)
 
    This constructor should always be called with keyword arguments.  Arguments
    are:
@@ -258,10 +274,19 @@
    *kwargs* is a dictionary of keyword arguments for the target invocation.
    Defaults to ``{}``.
 
+   *verbose* is a flag used for debugging messages.
+
+   If not ``None``, *daemon* explicitly sets whether the thread is daemonic.
+   If ``None`` (the default), the daemonic property is inherited from the
+   current thread.
+
    If the subclass overrides the constructor, it must make sure to invoke the
    base class constructor (``Thread.__init__()``) before doing anything else to
    the thread.
 
+   .. versionchanged:: 3.3
+      Added the *daemon* argument.
+
    .. method:: start()
 
       Start the thread's activity.
@@ -269,7 +294,7 @@
       It must be called at most once per thread object.  It arranges for the
       object's :meth:`run` method to be invoked in a separate thread of control.
 
-      This method will raise a :exc:`RuntimeException` if called more than once
+      This method will raise a :exc:`RuntimeError` if called more than once
       on the same thread object.
 
    .. method:: run()
@@ -403,6 +428,9 @@
    .. versionchanged:: 3.2
       The *timeout* parameter is new.
 
+   .. versionchanged:: 3.2
+      Lock acquires can now be interrupted by signals on POSIX.
+
 
 .. method:: Lock.release()
 
@@ -534,6 +562,13 @@
 in a typical producer-consumer situation, adding one item to the buffer only
 needs to wake up one consumer thread.
 
+Note:  Condition variables can be, depending on the implementation, subject
+to both spurious wakeups (when :meth:`wait` returns without a :meth:`notify`
+call) and stolen wakeups (when another thread acquires the lock before the
+awoken thread.)  For this reason, it is always necessary to verify the state
+the thread is waiting for when :meth:`wait` returns and optionally repeat
+the call as often as necessary.
+
 
 .. class:: Condition(lock=None)
 
@@ -580,6 +615,35 @@
       .. versionchanged:: 3.2
          Previously, the method always returned ``None``.
 
+   .. method:: wait_for(predicate, timeout=None)
+
+      Wait until a condition evaluates to True.  *predicate* should be a
+      callable which result will be interpreted as a boolean value.
+      A *timeout* may be provided giving the maximum time to wait.
+
+      This utility method may call :meth:`wait` repeatedly until the predicate
+      is satisfied, or until a timeout occurs. The return value is
+      the last return value of the predicate and will evaluate to
+      ``False`` if the method timed out.
+
+      Ignoring the timeout feature, calling this method is roughly equivalent to
+      writing::
+
+        while not predicate():
+            cv.wait()
+
+      Therefore, the same rules apply as with :meth:`wait`: The lock must be
+      held when called and is re-aquired on return.  The predicate is evaluated
+      with the lock held.
+
+      Using this method, the consumer example above can be written thus::
+
+         with cv:
+             cv.wait_for(an_item_is_available)
+             get_an_available_item()
+
+      .. versionadded:: 3.2
+
    .. method:: notify()
 
       Wake up a thread waiting on this condition, if any.  If the calling thread
@@ -663,9 +727,9 @@
 ^^^^^^^^^^^^^^^^^^^^^^^^^^
 
 Semaphores are often used to guard resources with limited capacity, for example,
-a database server.  In any situation where the size of the resource size is
-fixed, you should use a bounded semaphore.  Before spawning any worker threads,
-your main thread would initialize the semaphore::
+a database server.  In any situation where the size of the resource is fixed,
+you should use a bounded semaphore.  Before spawning any worker threads, your
+main thread would initialize the semaphore::
 
    maxconnections = 5
    ...
@@ -814,7 +878,7 @@
       constructor.
 
       The return value is an integer in the range 0 to *parties* -- 1, different
-      for each thrad.  This can be used to select a thread to do some special
+      for each thread.  This can be used to select a thread to do some special
       housekeeping, e.g.::
 
          i = barrier.wait()

Modified: python/branches/pep-3151/Doc/library/time.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/time.rst	(original)
+++ python/branches/pep-3151/Doc/library/time.rst	Sat Feb 26 08:16:32 2011
@@ -24,9 +24,9 @@
 
 .. index:: single: Year 2038
 
-* The functions in this module do not handle dates and times before the epoch or
+* The functions in this module may not handle dates and times before the epoch or
   far in the future.  The cut-off point in the future is determined by the C
-  library; for Unix, it is typically in 2038.
+  library; for 32-bit systems, it is typically in 2038.
 
 .. index::
    single: Year 2000
@@ -34,20 +34,31 @@
 
 .. _time-y2kissues:
 
-* **Year 2000 (Y2K) issues**:  Python depends on the platform's C library, which
+* **Year 2000 (Y2K) issues**: Python depends on the platform's C library, which
   generally doesn't have year 2000 issues, since all dates and times are
-  represented internally as seconds since the epoch.  Functions accepting a
-  :class:`struct_time` (see below) generally require a 4-digit year.  For backward
-  compatibility, 2-digit years are supported if the module variable
-  ``accept2dyear`` is a non-zero integer; this variable is initialized to ``1``
-  unless the environment variable :envvar:`PYTHONY2K` is set to a non-empty
-  string, in which case it is initialized to ``0``.  Thus, you can set
-  :envvar:`PYTHONY2K` to a non-empty string in the environment to require 4-digit
-  years for all year input.  When 2-digit years are accepted, they are converted
-  according to the POSIX or X/Open standard: values 69-99 are mapped to 1969-1999,
-  and values 0--68 are mapped to 2000--2068. Values 100--1899 are always illegal.
-  Note that this is new as of Python 1.5.2(a2); earlier versions, up to Python
-  1.5.1 and 1.5.2a1, would add 1900 to year values below 1900.
+  represented internally as seconds since the epoch.  Function :func:`strptime`
+  can parse 2-digit years when given ``%y`` format code.  When 2-digit years are
+  parsed, they are converted according to the POSIX and ISO C standards: values
+  69--99 are mapped to 1969--1999, and values 0--68 are mapped to 2000--2068.
+
+  For backward compatibility, years with less than 4 digits are treated
+  specially by :func:`asctime`, :func:`mktime`, and :func:`strftime` functions
+  that operate on a 9-tuple or :class:`struct_time` values. If year (the first
+  value in the 9-tuple) is specified with less than 4 digits, its interpretation
+  depends on the value of ``accept2dyear`` variable.
+
+  If ``accept2dyear`` is true (default), a backward compatibility behavior is
+  invoked as follows:
+
+    - for 2-digit year, century is guessed according to POSIX rules for
+      ``%y`` strptime format.  A deprecation warning is issued when century
+      information is guessed in this way.
+
+    - for 3-digit or negative year, a :exc:`ValueError` exception is raised.
+
+  If ``accept2dyear`` is false (set by the program or as a result of a
+  non-empty value assigned to ``PYTHONY2K`` environment variable) all year
+  values are interpreted as given.
 
 .. index::
    single: UTC
@@ -109,10 +120,19 @@
 
 .. data:: accept2dyear
 
-   Boolean value indicating whether two-digit year values will be accepted.  This
-   is true by default, but will be set to false if the environment variable
-   :envvar:`PYTHONY2K` has been set to a non-empty string.  It may also be modified
-   at run time.
+   Boolean value indicating whether two-digit year values will be
+   mapped to 1969--2068 range by :func:`asctime`, :func:`mktime`, and
+   :func:`strftime` functions.  This is true by default, but will be
+   set to false if the environment variable :envvar:`PYTHONY2K` has
+   been set to a non-empty string.  It may also be modified at run
+   time.
+
+   .. deprecated:: 3.2
+      Mapping of 2-digit year values by :func:`asctime`,
+      :func:`mktime`, and :func:`strftime` functions to 1969--2068
+      range is deprecated.  Programs that need to process 2-digit
+      years should use ``%y`` code available in :func:`strptime`
+      function or convert 2-digit year values to 4-digit themselves.
 
 
 .. data:: altzone
@@ -125,7 +145,7 @@
 .. function:: asctime([t])
 
    Convert a tuple or :class:`struct_time` representing a time as returned by
-   :func:`gmtime` or :func:`localtime` to a 24-character string of the following
+   :func:`gmtime` or :func:`localtime` to a string of the following
    form: ``'Sun Jun 20 23:21:05 1993'``.  If *t* is not provided, the current time
    as returned by :func:`localtime` is used. Locale information is not used by
    :func:`asctime`.
@@ -288,7 +308,7 @@
    | ``%y``    | Year without century as a decimal number       |       |
    |           | [00,99].                                       |       |
    +-----------+------------------------------------------------+-------+
-   | ``%Y``    | Year with century as a decimal number.         |       |
+   | ``%Y``    | Year with century as a decimal number.         | \(4)  |
    |           |                                                |       |
    +-----------+------------------------------------------------+-------+
    | ``%Z``    | Time zone name (no characters if no time zone  |       |
@@ -304,13 +324,20 @@
       the output hour field if the ``%I`` directive is used to parse the hour.
 
    (2)
-      The range really is ``0`` to ``61``; this accounts for leap seconds and the
-      (very rare) double leap seconds.
+      The range really is ``0`` to ``61``; value ``60`` is valid in
+      timestamps representing leap seconds and value ``61`` is supported
+      for historical reasons.
 
    (3)
       When used with the :func:`strptime` function, ``%U`` and ``%W`` are only used in
       calculations when the day of the week and the year are specified.
 
+   (4)
+      Produces different results depending on the value of
+      ``time.accept2dyear`` variable.  See :ref:`Year 2000 (Y2K)
+      issues <time-y2kissues>` for details.
+
+
    Here is an example, a format for dates compatible with that specified  in the
    :rfc:`2822` Internet email standard.  [#]_ ::
 
@@ -380,7 +407,7 @@
    +-------+-------------------+---------------------------------+
    | 4     | :attr:`tm_min`    | range [0, 59]                   |
    +-------+-------------------+---------------------------------+
-   | 5     | :attr:`tm_sec`    | range [0, 61]; see **(1)** in   |
+   | 5     | :attr:`tm_sec`    | range [0, 61]; see **(2)** in   |
    |       |                   | :func:`strftime` description    |
    +-------+-------------------+---------------------------------+
    | 6     | :attr:`tm_wday`   | range [0, 6], Monday is 0       |

Modified: python/branches/pep-3151/Doc/library/timeit.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/timeit.rst	(original)
+++ python/branches/pep-3151/Doc/library/timeit.rst	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,10 @@
    single: Benchmarking
    single: Performance
 
+**Source code:** :source:`Lib/timeit.py`
+
+--------------
+
 This module provides a simple way to time small bits of Python code. It has both
 command line as well as callable interfaces.  It avoids a number of common traps
 for measuring execution times.  See also Tim Peters' introduction to the
@@ -117,27 +121,36 @@
 
    python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [statement ...]
 
-where the following options are understood:
+Where the following options are understood:
+
+.. program:: timeit
+
+.. cmdoption:: -n N, --number=N
 
--n N/:option:`--number=N`
    how many times to execute 'statement'
 
--r N/:option:`--repeat=N`
+.. cmdoption:: -r N, --repeat=N
+
    how many times to repeat the timer (default 3)
 
--s S/:option:`--setup=S`
-   statement to be executed once initially (default ``'pass'``)
+.. cmdoption:: -s S, --setup=S
+
+   statement to be executed once initially (default ``pass``)
+
+.. cmdoption:: -t, --time
 
--t/:option:`--time`
    use :func:`time.time` (default on all platforms but Windows)
 
--c/:option:`--clock`
+.. cmdoption:: -c, --clock
+
    use :func:`time.clock` (default on Windows)
 
--v/:option:`--verbose`
+.. cmdoption:: -v, --verbose
+
    print raw timing results; repeat for more digits precision
 
--h/:option:`--help`
+.. cmdoption:: -h, --help
+
    print a short usage message and exit
 
 A multi-line statement may be given by specifying each line as a separate

Modified: python/branches/pep-3151/Doc/library/tkinter.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/tkinter.rst	(original)
+++ python/branches/pep-3151/Doc/library/tkinter.rst	Sat Feb 26 08:16:32 2011
@@ -659,9 +659,7 @@
 
 scrollcommand
    This is almost always the :meth:`!set` method of some scrollbar widget, but can
-   be any widget method that takes a single argument.   Refer to the file
-   :file:`Demo/tkinter/matt/canvas-with-scrollbars.py` in the Python source
-   distribution for an example.
+   be any widget method that takes a single argument.
 
 wrap:
    Must be one of: ``"none"``, ``"char"``, or ``"word"``.

Modified: python/branches/pep-3151/Doc/library/tkinter.tix.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/tkinter.tix.rst	(original)
+++ python/branches/pep-3151/Doc/library/tkinter.tix.rst	Sat Feb 26 08:16:32 2011
@@ -84,11 +84,7 @@
 -----------
 
 `Tix <http://tix.sourceforge.net/dist/current/man/html/TixCmd/TixIntro.htm>`_
-introduces over 40 widget classes to the :mod:`tkinter` repertoire.  There is a
-demo of all the :mod:`tkinter.tix` widgets in the :file:`Demo/tix` directory of
-the standard distribution.
-
-.. The Python sample code is still being added to Python, hence commented out
+introduces over 40 widget classes to the :mod:`tkinter` repertoire.
 
 
 Basic Widgets
@@ -503,8 +499,8 @@
 
    To view the current settings, the common usage is::
 
-      import Tix
-      root = Tix.Tk()
+      from tkinter import tix
+      root = tix.Tk()
       print(root.tix_configure())
 
 

Modified: python/branches/pep-3151/Doc/library/token.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/token.rst	(original)
+++ python/branches/pep-3151/Doc/library/token.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Constants representing terminal nodes of the parse tree.
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/token.py`
+
+--------------
 
 This module provides constants which represent the numeric values of leaf nodes
 of the parse tree (terminal tokens).  Refer to the file :file:`Grammar/Grammar`

Modified: python/branches/pep-3151/Doc/library/tokenize.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/tokenize.rst	(original)
+++ python/branches/pep-3151/Doc/library/tokenize.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Ka Ping Yee
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/tokenize.py`
+
+--------------
 
 The :mod:`tokenize` module provides a lexical scanner for Python source code,
 implemented in Python.  The scanner in this module returns comments as tokens

Modified: python/branches/pep-3151/Doc/library/trace.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/trace.rst	(original)
+++ python/branches/pep-3151/Doc/library/trace.rst	Sat Feb 26 08:16:32 2011
@@ -4,112 +4,189 @@
 .. module:: trace
    :synopsis: Trace or track Python statement execution.
 
+**Source code:** :source:`Lib/trace.py`
+
+--------------
 
 The :mod:`trace` module allows you to trace program execution, generate
 annotated statement coverage listings, print caller/callee relationships and
 list functions executed during a program run.  It can be used in another program
 or from the command line.
 
-
 .. _trace-cli:
 
-Command Line Usage
+Command-Line Usage
 ------------------
 
 The :mod:`trace` module can be invoked from the command line.  It can be as
 simple as ::
 
-   python -m trace --count somefile.py ...
+   python -m trace --count -C . somefile.py ...
+
+The above will execute :file:`somefile.py` and generate annotated listings of
+all Python modules imported during the execution into the current directory.
+
+.. program:: trace
+
+.. cmdoption:: --help
+
+   Display usage and exit.
+
+.. cmdoption:: --version
+
+   Display the version of the module and exit.
+
+Main options
+^^^^^^^^^^^^
 
-The above will generate annotated listings of all Python modules imported during
-the execution of :file:`somefile.py`.
+At least one of the following options must be specified when invoking
+:mod:`trace`.  The :option:`--listfuncs <-l>` option is mutually exclusive with
+the :option:`--trace <-t>` and :option:`--counts <-c>` options . When
+:option:`--listfuncs <-l>` is provided, neither :option:`--counts <-c>` nor
+:option:`--trace <-t>` are accepted, and vice versa.
 
-The following command-line arguments are supported:
+.. program:: trace
+
+.. cmdoption:: -c, --count
+
+   Produce a set of annotated listing files upon program completion that shows
+   how many times each statement was executed.  See also
+   :option:`--coverdir <-C>`, :option:`--file <-f>` and
+   :option:`--no-report <-R>` below.
+
+.. cmdoption:: -t, --trace
 
-:option:`--trace`, :option:`-t`
    Display lines as they are executed.
 
-:option:`--count`, :option:`-c`
-   Produce a set of  annotated listing files upon program completion that shows how
-   many times each statement was executed.
+.. cmdoption:: -l, --listfuncs
+
+   Display the functions executed by running the program.
+
+.. cmdoption:: -r, --report
 
-:option:`--report`, :option:`-r`
    Produce an annotated list from an earlier program run that used the
-   :option:`--count` and :option:`--file` arguments.
+   :option:`--count <-c>` and :option:`--file <-f>` option.  This does not
+   execute any code.
 
-:option:`--no-report`, :option:`-R`
-   Do not generate annotated listings.  This is useful if you intend to make
-   several runs with :option:`--count` then produce a single set of annotated
-   listings at the end.
+.. cmdoption:: -T, --trackcalls
+
+   Display the calling relationships exposed by running the program.
+
+Modifiers
+^^^^^^^^^
+
+.. program:: trace
 
-:option:`--listfuncs`, :option:`-l`
-   List the functions executed by running the program.
+.. cmdoption:: -f, --file=<file>
 
-:option:`--trackcalls`, :option:`-T`
-   Generate calling relationships exposed by running the program.
+   Name of a file to accumulate counts over several tracing runs.  Should be
+   used with the :option:`--count <-c>` option.
 
-:option:`--file`, :option:`-f`
-   Name a file containing (or to contain) counts.
+.. cmdoption:: -C, --coverdir=<dir>
 
-:option:`--coverdir`, :option:`-C`
-   Name a directory in which to save annotated listing files.
+   Directory where the report files go.  The coverage report for
+   ``package.module`` is written to file :file:`{dir}/{package}/{module}.cover`.
+
+.. cmdoption:: -m, --missing
 
-:option:`--missing`, :option:`-m`
    When generating annotated listings, mark lines which were not executed with
-   '``>>>>>>``'.
+   ``>>>>>>``.
+
+.. cmdoption:: -s, --summary
+
+   When using :option:`--count <-c>` or :option:`--report <-r>`, write a brief
+   summary to stdout for each file processed.
+
+.. cmdoption:: -R, --no-report
+
+   Do not generate annotated listings.  This is useful if you intend to make
+   several runs with :option:`--count <-c>`, and then produce a single set of
+   annotated listings at the end.
+
+.. cmdoption:: -g, --timing
+
+   Prefix each line with the time since the program started.  Only used while
+   tracing.
+
+Filters
+^^^^^^^
 
-:option:`--summary`, :option:`-s`
-   When using :option:`--count` or :option:`--report`, write a brief summary to
-   stdout for each file processed.
-
-:option:`--ignore-module`
-   Accepts comma separated list of module names. Ignore each of the named
-   module and its submodules (if it is a package).  May be given
-   multiple times.
-
-:option:`--ignore-dir`
-   Ignore all modules and packages in the named directory and subdirectories
-   (multiple directories can be joined by os.pathsep).  May be given multiple
-   times.
+These options may be repeated multiple times.
 
+.. program:: trace
+
+.. cmdoption:: --ignore-module=<mod>
+
+   Ignore each of the given module names and its submodules (if it is a
+   package).  The argument can be a list of names separated by a comma.
+
+.. cmdoption:: --ignore-dir=<dir>
+
+   Ignore all modules and packages in the named directory and subdirectories.
+   The argument can be a list of directories separated by :data:`os.pathsep`.
 
 .. _trace-api:
 
-Programming Interface
----------------------
+Programmatic Interface
+----------------------
+
+.. class:: Trace(count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(),\
+                 ignoredirs=(), infile=None, outfile=None, timing=False)
+
+   Create an object to trace execution of a single statement or expression.  All
+   parameters are optional.  *count* enables counting of line numbers.  *trace*
+   enables line execution tracing.  *countfuncs* enables listing of the
+   functions called during the run.  *countcallers* enables call relationship
+   tracking.  *ignoremods* is a list of modules or packages to ignore.
+   *ignoredirs* is a list of directories whose modules or packages should be
+   ignored.  *infile* is the name of the file from which to read stored count
+   information.  *outfile* is the name of the file in which to write updated
+   count information.  *timing* enables a timestamp relative to when tracing was
+   started to be displayed.
+
+    .. method:: run(cmd)
+
+       Execute the command and gather statistics from the execution with
+       the current tracing parameters.  *cmd* must be a string or code object,
+       suitable for passing into :func:`exec`.
 
+    .. method:: runctx(cmd, globals=None, locals=None)
 
-.. class:: Trace(count=1, trace=1, countfuncs=0, countcallers=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None, timing=False)
+       Execute the command and gather statistics from the execution with the
+       current tracing parameters, in the defined global and local
+       environments.  If not defined, *globals* and *locals* default to empty
+       dictionaries.
 
-   Create an object to trace execution of a single statement or expression. All
-   parameters are optional.  *count* enables counting of line numbers. *trace*
-   enables line execution tracing.  *countfuncs* enables listing of the functions
-   called during the run.  *countcallers* enables call relationship tracking.
-   *ignoremods* is a list of modules or packages to ignore.  *ignoredirs* is a list
-   of directories whose modules or packages should be ignored.  *infile* is the
-   file from which to read stored count information.  *outfile* is a file in which
-   to write updated count information. *timing* enables a timestamp relative
-   to when tracing was started to be displayed.
+    .. method:: runfunc(func, *args, **kwds)
 
+       Call *func* with the given arguments under control of the :class:`Trace`
+       object with the current tracing parameters.
 
-.. method:: Trace.run(cmd)
+    .. method:: results()
 
-   Run *cmd* under control of the Trace object with the current tracing parameters.
+       Return a :class:`CoverageResults` object that contains the cumulative
+       results of all previous calls to ``run``, ``runctx`` and ``runfunc``
+       for the given :class:`Trace` instance.  Does not reset the accumulated
+       trace results.
 
+.. class:: CoverageResults
 
-.. method:: Trace.runctx(cmd, globals=None, locals=None)
+   A container for coverage results, created by :meth:`Trace.results`.  Should
+   not be created directly by the user.
 
-   Run *cmd* under control of the Trace object with the current tracing parameters
-   in the defined global and local environments.  If not defined, *globals* and
-   *locals* default to empty dictionaries.
+    .. method:: update(other)
 
+       Merge in data from another :class:`CoverageResults` object.
 
-.. method:: Trace.runfunc(func, *args, **kwds)
+    .. method:: write_results(show_missing=True, summary=False, coverdir=None)
 
-   Call *func* with the given arguments under control of the :class:`Trace` object
-   with the current tracing parameters.
+       Write coverage results.  Set *show_missing* to show lines that had no
+       hits.  Set *summary* to include in the output the coverage summary per
+       module.  *coverdir* specifies the directory into which the coverage
+       result files will be output.  If ``None``, the results for each source
+       file are placed in its directory.
 
-This is a simple example showing the use of this module::
+A simple example demonstrating the use of the programmatic interface::
 
    import sys
    import trace

Modified: python/branches/pep-3151/Doc/library/turtle.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/turtle.rst	(original)
+++ python/branches/pep-3151/Doc/library/turtle.rst	Sat Feb 26 08:16:32 2011
@@ -1878,7 +1878,7 @@
 
       >>> cv = screen.getcanvas()
       >>> cv
-      <turtle.ScrolledCanvas instance at 0x...>
+      <turtle.ScrolledCanvas object at ...>
 
 
 .. function:: getshapes()
@@ -2268,7 +2268,7 @@
 stored and an additional one in the current working directory.  The latter will
 override the settings of the first one.
 
-The :file:`Demo/turtle` directory contains a :file:`turtle.cfg` file.  You can
+The :file:`Lib/turtledemo` directory contains a :file:`turtle.cfg` file.  You can
 study it as an example and see its effects when running the demos (preferably
 not from within the demo-viewer).
 
@@ -2400,8 +2400,7 @@
   strings and numbers respectively.
 
 - Two example scripts :file:`tdemo_nim.py` and :file:`tdemo_round_dance.py`
-  have been added to the Demo directory (source distribution only). As usual
-  they can be viewed and executed within the demo viewer :file:`turtleDemo.py`.
+  have been added to the :file:`Lib/turtledemo` directory.
 
 
 .. doctest::

Modified: python/branches/pep-3151/Doc/library/types.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/types.rst	(original)
+++ python/branches/pep-3151/Doc/library/types.rst	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,9 @@
 .. module:: types
    :synopsis: Names for built-in types.
 
+**Source code:** :source:`Lib/types.py`
+
+--------------
 
 This module defines names for some object types that are used by the standard
 Python interpreter, but not exposed as builtins like :class:`int` or

Modified: python/branches/pep-3151/Doc/library/unicodedata.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/unicodedata.rst	(original)
+++ python/branches/pep-3151/Doc/library/unicodedata.rst	Sat Feb 26 08:16:32 2011
@@ -13,14 +13,15 @@
    single: character
    pair: Unicode; database
 
-This module provides access to the Unicode Character Database which defines
-character properties for all Unicode characters. The data in this database is
-based on the :file:`UnicodeData.txt` file version 5.2.0 which is publicly
-available from ftp://ftp.unicode.org/.
+This module provides access to the Unicode Character Database (UCD) which
+defines character properties for all Unicode characters. The data contained in
+this database is compiled from the `UCD version 6.0.0
+<http://www.unicode.org/Public/6.0.0/ucd>`_.
 
-The module uses the same names and symbols as defined by the UnicodeData File
-Format 5.2.0 (see http://www.unicode.org/reports/tr44/tr44-4.html).
-It defines the following functions:
+The module uses the same names and symbols as defined by Unicode
+Standard Annex #44, `"Unicode Character Database"
+<http://www.unicode.org/reports/tr44/tr44-6.html>`_.  It defines the
+following functions:
 
 
 .. function:: lookup(name)

Modified: python/branches/pep-3151/Doc/library/unittest.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/unittest.rst	(original)
+++ python/branches/pep-3151/Doc/library/unittest.rst	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,8 @@
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 .. sectionauthor:: Raymond Hettinger <python at rcn.com>
 
+(If you are already familiar with the basic concepts of testing, you might want
+to skip to :ref:`the list of assert methods <assert-methods>`.)
 
 The Python unit testing framework, sometimes referred to as "PyUnit," is a
 Python language version of JUnit, by Kent Beck and Erich Gamma. JUnit is, in
@@ -95,6 +97,13 @@
       A special-interest-group for discussion of testing, and testing tools,
       in Python.
 
+   The script :file:`Tools/unittestgui/unittestgui.py` in the Python source distribution is
+   a GUI tool for test discovery and execution.  This is intended largely for ease of use
+   for those new to unit testing.  For production environments it is recommended that
+   tests be driven by a continuous integration system such as `Hudson <http://hudson-ci.org/>`_
+   or `Buildbot <http://buildbot.net/trac>`_.
+
+
 .. _unittest-minimal-example:
 
 Basic example
@@ -154,7 +163,7 @@
 test.
 
 The final block shows a simple way to run the tests. :func:`unittest.main`
-provides a command line interface to the test script.  When run from the command
+provides a command-line interface to the test script.  When run from the command
 line, the above script produces an output that looks like this::
 
    ...
@@ -189,7 +198,7 @@
 
 .. _unittest-command-line-interface:
 
-Command Line Interface
+Command-Line Interface
 ----------------------
 
 The unittest module can be used from the command line to run tests from
@@ -202,11 +211,25 @@
 You can pass in a list with any combination of module names, and fully
 qualified class or method names.
 
+Test modules can be specified by file path as well::
+
+   python -m unittest tests/test_something.py
+
+This allows you to use the shell filename completion to specify the test module.
+The file specified must still be importable as a module. The path is converted
+to a module name by removing the '.py' and converting path separators into '.'.
+If you want to execute a test file that isn't importable as a module you should
+execute the file directly instead.
+
 You can run tests with more detail (higher verbosity) by passing in the -v flag::
 
    python -m unittest -v test_module
 
-For a list of all the command line options::
+When executed without arguments :ref:`unittest-test-discovery` is started::
+
+   python -m unittest
+
+For a list of all the command-line options::
 
    python -m unittest -h
 
@@ -215,31 +238,33 @@
    not modules or classes.
 
 
-failfast, catch and buffer command line options
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+Command-line options
+~~~~~~~~~~~~~~~~~~~~
 
-unittest supports three command options.
+:program:`unittest` supports these command-line options:
 
-* :option:`-b` / :option:`--buffer`
+.. program:: unittest
 
-  The standard output and standard error streams are buffered during the test
-  run. Output during a passing test is discarded. Output is echoed normally
-  on test fail or error and is added to the failure messages.
+.. cmdoption:: -b, --buffer
 
-* :option:`-c` / :option:`--catch`
+   The standard output and standard error streams are buffered during the test
+   run. Output during a passing test is discarded. Output is echoed normally
+   on test fail or error and is added to the failure messages.
 
-  Control-C during the test run waits for the current test to end and then
-  reports all the results so far. A second control-C raises the normal
-  :exc:`KeyboardInterrupt` exception.
+.. cmdoption:: -c, --catch
 
-  See `Signal Handling`_ for the functions that provide this functionality.
+   Control-C during the test run waits for the current test to end and then
+   reports all the results so far. A second control-C raises the normal
+   :exc:`KeyboardInterrupt` exception.
 
-* :option:`-f` / :option:`--failfast`
+   See `Signal Handling`_ for the functions that provide this functionality.
 
-  Stop the test run on the first error or failure.
+.. cmdoption:: -f, --failfast
+
+   Stop the test run on the first error or failure.
 
 .. versionadded:: 3.2
-   The command line options ``-c``, ``-b`` and ``-f`` were added.
+   The command-line options ``-b``, ``-c`` and ``-f`` were added.
 
 The command line can also be used for test discovery, for running all of the
 tests in a project or just a subset.
@@ -257,18 +282,36 @@
 directory of the project (in other words, they must all be in Python packages).
 
 Test discovery is implemented in :meth:`TestLoader.discover`, but can also be
-used from the command line. The basic command line usage is::
+used from the command line. The basic command-line usage is::
 
    cd project_directory
    python -m unittest discover
 
+.. note::
+
+   As a shortcut, ``python -m unittest`` is the equivalent of
+   ``python -m unittest discover``. If you want to pass arguments to test
+   discovery the `discover` sub-command must be used explicitly.
+
 The ``discover`` sub-command has the following options:
 
-   -v, --verbose    Verbose output
-   -s directory     Directory to start discovery ('.' default)
-   -p pattern       Pattern to match test files ('test*.py' default)
-   -t directory     Top level directory of project (default to
-                    start directory)
+.. program:: unittest discover
+
+.. cmdoption:: -v, --verbose
+
+   Verbose output
+
+.. cmdoption:: -s directory
+
+   Directory to start discovery ('.' default)
+
+.. cmdoption:: -p pattern
+
+   Pattern to match test files ('test*.py' default)
+
+.. cmdoption:: -t directory
+
+   Top level directory of project (defaults to start directory)
 
 The :option:`-s`, :option:`-p`, and :option:`-t` options can be passed in
 as positional arguments in that order. The following two command lines
@@ -309,9 +352,9 @@
 
 The basic building blocks of unit testing are :dfn:`test cases` --- single
 scenarios that must be set up and checked for correctness.  In :mod:`unittest`,
-test cases are represented by instances of :mod:`unittest`'s :class:`TestCase`
-class. To make your own test cases you must write subclasses of
-:class:`TestCase`, or use :class:`FunctionTestCase`.
+test cases are represented by :class:`unittest.TestCase` instances.
+To make your own test cases you must write subclasses of
+:class:`TestCase` or use :class:`FunctionTestCase`.
 
 An instance of a :class:`TestCase`\ -derived class is an object that can
 completely run a single test method, together with optional set-up and tidy-up
@@ -678,6 +721,11 @@
    Here, we create two instances of :class:`WidgetTestCase`, each of which runs a
    single test.
 
+   .. versionchanged::
+      `TestCase` can be instantiated successfully without providing a method
+      name. This makes it easier to experiment with `TestCase` from the
+      interactive interpreter.
+
    *methodName* defaults to :meth:`runTest`.
 
    :class:`TestCase` instances provide three groups of methods: one group used
@@ -740,7 +788,7 @@
    .. method:: run(result=None)
 
       Run the test, collecting the result into the test result object passed as
-      *result*.  If *result* is omitted or :const:`None`, a temporary result
+      *result*.  If *result* is omitted or ``None``, a temporary result
       object is created (by calling the :meth:`defaultTestResult` method) and
       used. The result object is not returned to :meth:`run`'s caller.
 
@@ -762,7 +810,7 @@
       by the test to be propagated to the caller, and can be used to support
       running tests under a debugger.
 
-
+   .. _assert-methods:
 
    The :class:`TestCase` class provides a number of methods to check for and
    report failures, such as:
@@ -807,19 +855,22 @@
    | <TestCase.assertNotIsInstance>`         |                             |               |
    +-----------------------------------------+-----------------------------+---------------+
 
+   All the assert methods (except :meth:`assertRaises`,
+   :meth:`assertRaisesRegex`, :meth:`assertWarns`, :meth:`assertWarnsRegex`)
+   accept a *msg* argument that, if specified, is used as the error message on
+   failure (see also :data:`longMessage`).
 
    .. method:: assertEqual(first, second, msg=None)
 
-      Test that *first* and *second* are equal.  If the values do not compare
-      equal, the test will fail.
+      Test that *first* and *second* are equal.  If the values do not
+      compare equal, the test will fail.
 
       In addition, if *first* and *second* are the exact same type and one of
       list, tuple, dict, set, frozenset or str or any type that a subclass
       registers with :meth:`addTypeEqualityFunc` the type specific equality
       function will be called in order to generate a more useful default
-      error message.
-
-      If specified, *msg* will be used as the error message on failure.
+      error message (see also the :ref:`list of type-specific methods
+      <type-specific-methods>`).
 
       .. versionchanged:: 3.1
          Added the automatic calling of type specific equality function.
@@ -831,8 +882,8 @@
 
    .. method:: assertNotEqual(first, second, msg=None)
 
-      Test that *first* and *second* are not equal.  If the values do compare
-      equal, the test will fail.
+      Test that *first* and *second* are not equal.  If the values do
+      compare equal, the test will fail.
 
    .. method:: assertTrue(expr, msg=None)
                assertFalse(expr, msg=None)
@@ -849,7 +900,8 @@
    .. method:: assertIs(first, second, msg=None)
                assertIsNot(first, second, msg=None)
 
-      Test that *first* and *second* evaluate (or don't evaluate) to the same object.
+      Test that *first* and *second* evaluate (or don't evaluate) to the
+      same object.
 
       .. versionadded:: 3.1
 
@@ -889,14 +941,14 @@
    | :meth:`assertRaises(exc, fun, *args, **kwds)            | ``fun(*args, **kwds)`` raises `exc`  |            |
    | <TestCase.assertRaises>`                                |                                      |            |
    +---------------------------------------------------------+--------------------------------------+------------+
-   | :meth:`assertRaisesRegexp(exc, re, fun, *args, **kwds)  | ``fun(*args, **kwds)`` raises `exc`  | 3.1        |
-   | <TestCase.assertRaisesRegexp>`                          | and the message matches `re`         |            |
+   | :meth:`assertRaisesRegex(exc, re, fun, *args, **kwds)   | ``fun(*args, **kwds)`` raises `exc`  | 3.1        |
+   | <TestCase.assertRaisesRegex>`                           | and the message matches `re`         |            |
    +---------------------------------------------------------+--------------------------------------+------------+
    | :meth:`assertWarns(warn, fun, *args, **kwds)            | ``fun(*args, **kwds)`` raises `warn` | 3.2        |
    | <TestCase.assertWarns>`                                 |                                      |            |
    +---------------------------------------------------------+--------------------------------------+------------+
-   | :meth:`assertWarnsRegexp(warn, re, fun, *args, **kwds)  | ``fun(*args, **kwds)`` raises `warn` | 3.2        |
-   | <TestCase.assertWarnsRegexp>`                           | and the message matches `re`         |            |
+   | :meth:`assertWarnsRegex(warn, re, fun, *args, **kwds)   | ``fun(*args, **kwds)`` raises `warn` | 3.2        |
+   | <TestCase.assertWarnsRegex>`                            | and the message matches `re`         |            |
    +---------------------------------------------------------+--------------------------------------+------------+
 
    .. method:: assertRaises(exception, callable, *args, **kwds)
@@ -932,23 +984,26 @@
          Added the :attr:`exception` attribute.
 
 
-   .. method:: assertRaisesRegexp(exception, regexp, callable, *args, **kwds)
-               assertRaisesRegexp(exception, regexp)
+   .. method:: assertRaisesRegex(exception, regex, callable, *args, **kwds)
+               assertRaisesRegex(exception, regex)
 
-      Like :meth:`assertRaises` but also tests that *regexp* matches
-      on the string representation of the raised exception.  *regexp* may be
+      Like :meth:`assertRaises` but also tests that *regex* matches
+      on the string representation of the raised exception.  *regex* may be
       a regular expression object or a string containing a regular expression
       suitable for use by :func:`re.search`.  Examples::
 
-         self.assertRaisesRegexp(ValueError, 'invalid literal for.*XYZ$',
-                                 int, 'XYZ')
+         self.assertRaisesRegex(ValueError, 'invalid literal for.*XYZ$',
+                                int, 'XYZ')
 
       or::
 
-         with self.assertRaisesRegexp(ValueError, 'literal'):
+         with self.assertRaisesRegex(ValueError, 'literal'):
             int('XYZ')
 
       .. versionadded:: 3.1
+         under the name ``assertRaisesRegexp``.
+      .. versionchanged:: 3.2
+         Renamed to :meth:`assertRaisesRegex`.
 
 
    .. method:: assertWarns(warning, callable, *args, **kwds)
@@ -985,21 +1040,21 @@
       .. versionadded:: 3.2
 
 
-   .. method:: assertWarnsRegexp(warning, regexp, callable, *args, **kwds)
-               assertWarnsRegexp(warning, regexp)
+   .. method:: assertWarnsRegex(warning, regex, callable, *args, **kwds)
+               assertWarnsRegex(warning, regex)
 
-      Like :meth:`assertWarns` but also tests that *regexp* matches on the
-      message of the triggered warning.  *regexp* may be a regular expression
+      Like :meth:`assertWarns` but also tests that *regex* matches on the
+      message of the triggered warning.  *regex* may be a regular expression
       object or a string containing a regular expression suitable for use
       by :func:`re.search`.  Example::
 
-         self.assertWarnsRegexp(DeprecationWarning,
-                                r'legacy_function\(\) is deprecated',
-                                legacy_function, 'XYZ')
+         self.assertWarnsRegex(DeprecationWarning,
+                               r'legacy_function\(\) is deprecated',
+                               legacy_function, 'XYZ')
 
       or::
 
-         with self.assertWarnsRegexp(RuntimeWarning, 'unsafe frobnicating'):
+         with self.assertWarnsRegex(RuntimeWarning, 'unsafe frobnicating'):
              frobnicate('/etc/passwd')
 
       .. versionadded:: 3.2
@@ -1029,17 +1084,14 @@
    | :meth:`assertLessEqual(a, b)          | ``a <= b``                     | 3.1          |
    | <TestCase.assertLessEqual>`           |                                |              |
    +---------------------------------------+--------------------------------+--------------+
-   | :meth:`assertRegexpMatches(s, re)     | ``regex.search(s)``            | 3.1          |
-   | <TestCase.assertRegexpMatches>`       |                                |              |
-   +---------------------------------------+--------------------------------+--------------+
-   | :meth:`assertNotRegexpMatches(s, re)  | ``not regex.search(s)``        | 3.2          |
-   | <TestCase.assertNotRegexpMatches>`    |                                |              |
+   | :meth:`assertRegex(s, re)             | ``regex.search(s)``            | 3.1          |
+   | <TestCase.assertRegex>`               |                                |              |
    +---------------------------------------+--------------------------------+--------------+
-   | :meth:`assertDictContainsSubset(a, b) | all the key/value pairs        | 3.1          |
-   | <TestCase.assertDictContainsSubset>`  | in `a` exist in `b`            |              |
+   | :meth:`assertNotRegex(s, re)          | ``not regex.search(s)``        | 3.2          |
+   | <TestCase.assertNotRegex>`            |                                |              |
    +---------------------------------------+--------------------------------+--------------+
-   | :meth:`assertItemsEqual(a, b)         | `a` and `b` have the same      | 3.2          |
-   | <TestCase.assertItemsEqual>`          | elements in the same number,   |              |
+   | :meth:`assertCountEqual(a, b)         | `a` and `b` have the same      | 3.2          |
+   | <TestCase.assertCountEqual>`          | elements in the same number,   |              |
    |                                       | regardless of their order      |              |
    +---------------------------------------+--------------------------------+--------------+
 
@@ -1059,9 +1111,9 @@
       Supplying both *delta* and *places* raises a ``TypeError``.
 
       .. versionchanged:: 3.2
-         assertAlmostEqual automatically considers almost equal objects that compare equal.
-         assertNotAlmostEqual automatically fails if the objects compare equal.
-         Added the ``delta`` keyword argument.
+         :meth:`assertAlmostEqual` automatically considers almost equal objects
+         that compare equal.  :meth:`assertNotAlmostEqual` automatically fails
+         if the objects compare equal.  Added the *delta* keyword argument.
 
 
    .. method:: assertGreater(first, second, msg=None)
@@ -1078,62 +1130,92 @@
       .. versionadded:: 3.1
 
 
-   .. method:: assertRegexpMatches(text, regexp, msg=None)
-               assertNotRegexpMatches(text, regexp, msg=None)
+   .. method:: assertRegex(text, regex, msg=None)
+               assertNotRegex(text, regex, msg=None)
 
-      Test that a *regexp* search matches (or does not match) *text*.  In case
+      Test that a *regex* search matches (or does not match) *text*.  In case
       of failure, the error message will include the pattern and the *text* (or
-      the pattern and the part of *text* that unexpectedly matched).  *regexp*
+      the pattern and the part of *text* that unexpectedly matched).  *regex*
       may be a regular expression object or a string containing a regular
       expression suitable for use by :func:`re.search`.
 
-      .. versionadded:: 3.1 :meth:`~TestCase.assertRegexpMatches`
-      .. versionadded:: 3.2 :meth:`~TestCase.assertNotRegexpMatches`
+      .. versionadded:: 3.1
+         under the name ``assertRegexpMatches``.
+      .. versionchanged:: 3.2
+         The method ``assertRegexpMatches()`` has been renamed to
+         :meth:`.assertRegex`.
+      .. versionadded:: 3.2
+         :meth:`.assertNotRegex`.
+
 
+   .. method:: assertDictContainsSubset(subset, dictionary, msg=None)
 
-   .. method:: assertDictContainsSubset(expected, actual, msg=None)
+      Tests whether the key/value pairs in *dictionary* are a superset of
+      those in *subset*.  If not, an error message listing the missing keys
+      and mismatched values is generated.
 
-      Tests whether the key/value pairs in dictionary *actual* are a
-      superset of those in *expected*.  If not, an error message listing
-      the missing keys and mismatched values is generated.
+      Note, the arguments are in the opposite order of what the method name
+      dictates.  Instead, consider using the set-methods on :ref:`dictionary
+      views <dict-views>`, for example: ``d.keys() <= e.keys()`` or
+      ``d.items() <= d.items()``.
 
       .. versionadded:: 3.1
+      .. deprecated:: 3.2
 
 
-   .. method:: assertItemsEqual(actual, expected, msg=None)
+   .. method:: assertCountEqual(first, second, msg=None)
 
-      Test that sequence *expected* contains the same elements as *actual*,
+      Test that sequence *first* contains the same elements as *second*,
       regardless of their order. When they don't, an error message listing the
       differences between the sequences will be generated.
 
-      Duplicate elements are *not* ignored when comparing *actual* and
-      *expected*. It verifies if each element has the same count in both
-      sequences. It is the equivalent of ``assertEqual(sorted(expected),
-      sorted(actual))`` but it works with sequences of unhashable objects as
-      well.
+      Duplicate elements are *not* ignored when comparing *first* and
+      *second*. It verifies whether each element has the same count in both
+      sequences. Equivalent to:
+      ``assertEqual(Counter(list(first)), Counter(list(second)))``
+      but works with sequences of unhashable objects as well.
 
       .. versionadded:: 3.2
 
+   .. method:: assertSameElements(first, second, msg=None)
 
-   .. method:: assertSameElements(actual, expected, msg=None)
-
-      Test that sequence *expected* contains the same elements as *actual*,
+      Test that sequence *first* contains the same elements as *second*,
       regardless of their order. When they don't, an error message listing
       the differences between the sequences will be generated.
 
-      Duplicate elements are ignored when comparing *actual* and *expected*.
-      It is the equivalent of ``assertEqual(set(expected), set(actual))``
+      Duplicate elements are ignored when comparing *first* and *second*.
+      It is the equivalent of ``assertEqual(set(first), set(second))``
       but it works with sequences of unhashable objects as well. Because
       duplicates are ignored, this method has been deprecated in favour of
-      :meth:`assertItemsEqual`.
+      :meth:`assertCountEqual`.
 
       .. versionadded:: 3.1
       .. deprecated:: 3.2
 
 
+   .. _type-specific-methods:
 
-   The following methods are used automatically by :meth:`~TestCase.assertEqual`
-   and usually is not necessary to invoke them directly:
+   The :meth:`assertEqual` method dispatches the equality check for objects of
+   the same type to different type-specific methods.  These methods are already
+   implemented for most of the built-in types, but it's also possible to
+   register new methods using :meth:`addTypeEqualityFunc`:
+
+   .. method:: addTypeEqualityFunc(typeobj, function)
+
+      Registers a type-specific method called by :meth:`assertEqual` to check
+      if two objects of exactly the same *typeobj* (not subclasses) compare
+      equal.  *function* must take two positional arguments and a third msg=None
+      keyword argument just as :meth:`assertEqual` does.  It must raise
+      :data:`self.failureException(msg) <failureException>` when inequality
+      between the first two parameters is detected -- possibly providing useful
+      information and explaining the inequalities in details in the error
+      message.
+
+      .. versionadded:: 3.1
+
+   The list of type-specific methods automatically used by
+   :meth:`~TestCase.assertEqual` are summarized in the following table.  Note
+   that it's usually not necessary to invoke these methods directly.
 
    +-----------------------------------------+-----------------------------+--------------+
    | Method                                  | Used to compare             | New in       |
@@ -1169,21 +1251,22 @@
       .. versionadded:: 3.1
 
 
-   .. method:: assertSequenceEqual(seq1, seq2, msg=None, seq_type=None)
+   .. method:: assertSequenceEqual(first, second, msg=None, seq_type=None)
 
       Tests that two sequences are equal.  If a *seq_type* is supplied, both
-      *seq1* and *seq2* must be instances of *seq_type* or a failure will
+      *first* and *second* must be instances of *seq_type* or a failure will
       be raised.  If the sequences are different an error message is
       constructed that shows the difference between the two.
 
-      This method is used to implement :meth:`assertListEqual` and
+      This method is not called directly by :meth:`assertEqual`, but
+      it's used to implement :meth:`assertListEqual` and
       :meth:`assertTupleEqual`.
 
       .. versionadded:: 3.1
 
 
-   .. method:: assertListEqual(list1, list2, msg=None)
-               assertTupleEqual(tuple1, tuple2, msg=None)
+   .. method:: assertListEqual(first, second, msg=None)
+               assertTupleEqual(first, second, msg=None)
 
       Tests that two lists or tuples are equal.  If not an error message is
       constructed that shows only the differences between the two.  An error
@@ -1194,19 +1277,19 @@
       .. versionadded:: 3.1
 
 
-   .. method:: assertSetEqual(set1, set2, msg=None)
+   .. method:: assertSetEqual(first, second, msg=None)
 
       Tests that two sets are equal.  If not, an error message is constructed
       that lists the differences between the sets.  This method is used by
       default when comparing sets or frozensets with :meth:`assertEqual`.
 
-      Fails if either of *set1* or *set2* does not have a :meth:`set.difference`
+      Fails if either of *first* or *second* does not have a :meth:`set.difference`
       method.
 
       .. versionadded:: 3.1
 
 
-   .. method:: assertDictEqual(expected, actual, msg=None)
+   .. method:: assertDictEqual(first, second, msg=None)
 
       Test that two dictionaries are equal.  If not, an error message is
       constructed that shows the differences in the dictionaries. This
@@ -1217,12 +1300,14 @@
 
 
 
+   .. _other-methods-and-attrs:
+
    Finally the :class:`TestCase` provides the following methods and attributes:
 
 
    .. method:: fail(msg=None)
 
-      Signals a test failure unconditionally, with *msg* or :const:`None` for
+      Signals a test failure unconditionally, with *msg* or ``None`` for
       the error message.
 
 
@@ -1237,18 +1322,19 @@
 
    .. attribute:: longMessage
 
-      If set to True then any explicit failure message you pass in to the
-      assert methods will be appended to the end of the normal failure message.
-      The normal messages contain useful information about the objects involved,
-      for example the message from assertEqual shows you the repr of the two
-      unequal objects. Setting this attribute to True allows you to have a
-      custom error message in addition to the normal one.
+      If set to ``True`` then any explicit failure message you pass in to the
+      :ref:`assert methods <assert-methods>` will be appended to the end of the
+      normal failure message.  The normal messages contain useful information
+      about the objects involved, for example the message from assertEqual
+      shows you the repr of the two unequal objects. Setting this attribute
+      to ``True`` allows you to have a custom error message in addition to the
+      normal one.
 
-      This attribute defaults to False, meaning that a custom message passed
-      to an assert method will silence the normal message.
+      This attribute defaults to ``True``. If set to False then a custom message
+      passed to an assert method will silence the normal message.
 
       The class setting can be overridden in individual tests by assigning an
-      instance attribute to True or False before calling the assert methods.
+      instance attribute to ``True`` or ``False`` before calling the assert methods.
 
       .. versionadded:: 3.1
 
@@ -1297,32 +1383,16 @@
 
    .. method:: shortDescription()
 
-      Returns a description of the test, or :const:`None` if no description
+      Returns a 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 :const:`None`.
+      or ``None``.
 
-      .. versionchanged:: 3.1,3.2
+      .. versionchanged:: 3.1
          In 3.1 this was changed to add the test name to the short description
-         even in the presence of a docstring. This caused compatibility issues
+         even in the presence of a docstring.  This caused compatibility issues
          with unittest extensions and adding the test name was moved to the
-         :class:`TextTestResult`.
-
-   .. method:: addTypeEqualityFunc(typeobj, function)
-
-      Registers a type specific :meth:`assertEqual` equality checking
-      function to be called by :meth:`assertEqual` when both objects it has
-      been asked to compare are exactly *typeobj* (not subclasses).
-      *function* must take two positional arguments and a third msg=None
-      keyword argument just as :meth:`assertEqual` does.  It must raise
-      ``self.failureException`` when inequality between the first two
-      parameters is detected.
-
-      One good use of custom equality checking functions for a type
-      is to raise ``self.failureException`` with an error message useful
-      for debugging the problem by explaining the inequalities in detail.
-
-      .. versionadded:: 3.1
+         :class:`TextTestResult` in Python 3.2.
 
 
    .. method:: addCleanup(function, *args, **kwargs)
@@ -1364,6 +1434,8 @@
    :mod:`unittest`-based test framework.
 
 
+.. _deprecated-aliases:
+
 Deprecated aliases
 ##################
 
@@ -1371,21 +1443,27 @@
 aliases that are now deprecated.  The following table lists the correct names
 along with their deprecated aliases:
 
-   ==============================  ===============================
-    Method Name                     Deprecated alias(es)
-   ==============================  ===============================
-    :meth:`.assertEqual`            failUnlessEqual, assertEquals
-    :meth:`.assertNotEqual`         failIfEqual
-    :meth:`.assertTrue`             failUnless, assert\_
+   ==============================  ====================== ======================
+    Method Name                     Deprecated alias       Deprecated alias
+   ==============================  ====================== ======================
+    :meth:`.assertEqual`            failUnlessEqual        assertEquals
+    :meth:`.assertNotEqual`         failIfEqual            assertNotEquals
+    :meth:`.assertTrue`             failUnless             assert\_
     :meth:`.assertFalse`            failIf
     :meth:`.assertRaises`           failUnlessRaises
-    :meth:`.assertAlmostEqual`      failUnlessAlmostEqual
-    :meth:`.assertNotAlmostEqual`   failIfAlmostEqual
-   ==============================  ===============================
-
-   .. deprecated:: 3.1
-         the aliases listed in the second column
-
+    :meth:`.assertAlmostEqual`      failUnlessAlmostEqual  assertAlmostEquals
+    :meth:`.assertNotAlmostEqual`   failIfAlmostEqual      assertNotAlmostEquals
+    :meth:`.assertRegex`                                   assertRegexpMatches
+    :meth:`.assertRaisesRegex`                             assertRaisesRegexp
+   ==============================  ====================== ======================
+
+   .. deprecated-removed:: 3.1 3.3
+         the fail* aliases listed in the second column.
+   .. deprecated:: 3.2
+         the assert* aliases listed in the third column.
+   .. deprecated:: 3.2
+         ``assertRegexpMatches`` and ``assertRaisesRegexp`` have been renamed to
+         :meth:`.assertRegex` and :meth:`.assertRaisesRegex`
 
 
 .. _testsuite-objects:
@@ -1686,14 +1764,14 @@
 
    .. method:: wasSuccessful()
 
-      Return :const:`True` if all tests run so far have passed, otherwise returns
-      :const:`False`.
+      Return ``True`` if all tests run so far have passed, otherwise returns
+      ``False``.
 
 
    .. method:: stop()
 
       This method can be called to signal that the set of tests being run should
-      be aborted by setting the :attr:`shouldStop` attribute to :const:`True`.
+      be aborted by setting the :attr:`shouldStop` attribute to ``True``.
       :class:`TestRunner` objects should respect this flag and return without
       running any additional tests.
 
@@ -1804,12 +1882,29 @@
    instead of repeatedly creating new instances.
 
 
-.. class:: TextTestRunner(stream=sys.stderr, descriptions=True, verbosity=1, runnerclass=None)
+.. class:: TextTestRunner(stream=None, descriptions=True, verbosity=1, runnerclass=None, warnings=None)
 
-   A basic test runner implementation which prints results on standard error.  It
+   A basic test runner implementation that outputs results to a stream. If *stream*
+   is `None`, the default, `sys.stderr` is used as the output stream. This class
    has a few configurable parameters, but is essentially very simple.  Graphical
    applications which run test suites should provide alternate implementations.
 
+   By default this runner shows :exc:`DeprecationWarning`,
+   :exc:`PendingDeprecationWarning`, and :exc:`ImportWarning` even if they are
+   :ref:`ignored by default <warning-ignored>`. Deprecation warnings caused by
+   :ref:`deprecated unittest methods <deprecated-aliases>` are also
+   special-cased and, when the warning filters are ``'default'`` or ``'always'``,
+   they will appear only once per-module, in order to avoid too many warning
+   messages.  This behavior can be overridden using the :option:`-Wd` or
+   :option:`-Wa` options and leaving *warnings* to ``None``.
+
+   .. versionchanged:: 3.2
+      Added the ``warnings`` argument.
+
+   .. versionchanged:: 3.2
+      The default stream is set to `sys.stderr` at instantiation time rather
+      than import time.
+
    .. method:: _makeResult()
 
       This method returns the instance of ``TestResult`` used by :meth:`run`.
@@ -1823,7 +1918,10 @@
 
         stream, descriptions, verbosity
 
-.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1, failfast=None, catchbreak=None, buffer=None)
+
+.. function:: main(module='__main__', defaultTest=None, argv=None, testRunner=None, \
+                   testLoader=unittest.loader.defaultTestLoader, exit=True, verbosity=1, \
+                   failfast=None, catchbreak=None, buffer=None, warnings=None)
 
    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
@@ -1850,23 +1948,29 @@
       >>> main(module='test_module', exit=False)
 
    The ``failfast``, ``catchbreak`` and ``buffer`` parameters have the same
-   effect as the `failfast, catch and buffer command line options`_.
+   effect as the same-name `command-line options`_.
+
+   The *warning* argument specifies the :ref:`warning filter <warning-filter>`
+   that should be used while running the tests.  If it's not specified, it will
+   remain ``None`` if a :option:`-W` option is passed to :program:`python`,
+   otherwise it will be set to ``'default'``.
 
    Calling ``main`` actually returns an instance of the ``TestProgram`` class.
    This stores the result of the tests run as the ``result`` attribute.
 
+   .. versionchanged:: 3.1
+      The ``exit`` parameter was added.
+
    .. versionchanged:: 3.2
-      The ``exit``, ``verbosity``, ``failfast``, ``catchbreak`` and ``buffer``
-      parameters were added.
+      The ``verbosity``, ``failfast``, ``catchbreak``, ``buffer``
+      and ``warnings`` parameters were added.
 
 
 load_tests Protocol
 ###################
 
-
 .. versionadded:: 3.2
 
-
 Modules or packages can customize how tests are loaded from them during normal
 test runs or test discovery by implementing a function called ``load_tests``.
 
@@ -2013,12 +2117,14 @@
 Signal Handling
 ---------------
 
-The :option:`-c`/:option:`--catch` command line option to unittest, along with the ``catchbreak``
-parameter to :func:`unittest.main()`, provide more friendly handling of
-control-C during a test run. With catch break behavior enabled control-C will
-allow the currently running test to complete, and the test run will then end
-and report all the results so far. A second control-c will raise a
-:exc:`KeyboardInterrupt` in the usual way.
+.. versionadded:: 3.2
+
+The :option:`-c/--catch <unittest -c>` command-line option to unittest,
+along with the ``catchbreak`` parameter to :func:`unittest.main()`, provide
+more friendly handling of control-C during a test run. With catch break
+behavior enabled control-C will allow the currently running test to complete,
+and the test run will then end and report all the results so far. A second
+control-c will raise a :exc:`KeyboardInterrupt` in the usual way.
 
 The control-c handling signal handler attempts to remain compatible with code or
 tests that install their own :const:`signal.SIGINT` handler. If the ``unittest``
@@ -2038,7 +2144,6 @@
    (usually in response to the user pressing control-c) all registered results
    have :meth:`~TestResult.stop` called.
 
-   .. versionadded:: 3.2
 
 .. function:: registerResult(result)
 
@@ -2050,7 +2155,6 @@
    handling is not enabled, so test frameworks can unconditionally register
    all results they create independently of whether or not handling is enabled.
 
-   .. versionadded:: 3.2
 
 .. function:: removeResult(result)
 
@@ -2058,7 +2162,6 @@
    :meth:`~TestResult.stop` will no longer be called on that result object in
    response to a control-c.
 
-   .. versionadded:: 3.2
 
 .. function:: removeHandler(function=None)
 
@@ -2069,6 +2172,3 @@
       @unittest.removeHandler
       def test_signal_handling(self):
           ...
-
-   .. versionadded:: 3.2
-

Modified: python/branches/pep-3151/Doc/library/urllib.parse.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/urllib.parse.rst	(original)
+++ python/branches/pep-3151/Doc/library/urllib.parse.rst	Sat Feb 26 08:16:32 2011
@@ -24,7 +24,15 @@
 ``rsync``, ``rtsp``, ``rtspu``, ``sftp``, ``shttp``, ``sip``, ``sips``,
 ``snews``, ``svn``, ``svn+ssh``, ``telnet``, ``wais``.
 
-The :mod:`urllib.parse` module defines the following functions:
+The :mod:`urllib.parse` module defines functions that fall into two broad
+categories: URL parsing and URL quoting. These are covered in detail in
+the following sections.
+
+URL Parsing
+-----------
+
+The URL parsing functions focus on splitting a URL string into its components,
+or on combining URL components into a URL string.
 
 .. function:: urlparse(urlstring, scheme='', allow_fragments=True)
 
@@ -108,7 +116,7 @@
       Added IPv6 URL parsing capabilities.
 
 
-.. function:: parse_qs(qs, keep_blank_values=False, strict_parsing=False)
+.. function:: parse_qs(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')
 
    Parse a query string given as a string argument (data of type
    :mimetype:`application/x-www-form-urlencoded`).  Data are returned as a
@@ -125,11 +133,19 @@
    parsing errors.  If false (the default), errors are silently ignored.  If true,
    errors raise a :exc:`ValueError` exception.
 
+   The optional *encoding* and *errors* parameters specify how to decode
+   percent-encoded sequences into Unicode characters, as accepted by the
+   :meth:`bytes.decode` method.
+
    Use the :func:`urllib.parse.urlencode` function to convert such
    dictionaries into query strings.
 
 
-.. function:: parse_qsl(qs, keep_blank_values=False, strict_parsing=False)
+   .. versionchanged:: 3.2
+      Add *encoding* and *errors* parameters.
+
+
+.. function:: parse_qsl(qs, keep_blank_values=False, strict_parsing=False, encoding='utf-8', errors='replace')
 
    Parse a query string given as a string argument (data of type
    :mimetype:`application/x-www-form-urlencoded`).  Data are returned as a list of
@@ -145,9 +161,16 @@
    parsing errors.  If false (the default), errors are silently ignored.  If true,
    errors raise a :exc:`ValueError` exception.
 
+   The optional *encoding* and *errors* parameters specify how to decode
+   percent-encoded sequences into Unicode characters, as accepted by the
+   :meth:`bytes.decode` method.
+
    Use the :func:`urllib.parse.urlencode` function to convert such lists of pairs into
    query strings.
 
+   .. versionchanged:: 3.2
+      Add *encoding* and *errors* parameters.
+
 
 .. function:: urlunparse(parts)
 
@@ -242,6 +265,162 @@
    string.  If there is no fragment identifier in *url*, return *url* unmodified
    and an empty string.
 
+   The return value is actually an instance of a subclass of :class:`tuple`.  This
+   class has the following additional read-only convenience attributes:
+
+   +------------------+-------+-------------------------+----------------------+
+   | Attribute        | Index | Value                   | Value if not present |
+   +==================+=======+=========================+======================+
+   | :attr:`url`      | 0     | URL with no fragment    | empty string         |
+   +------------------+-------+-------------------------+----------------------+
+   | :attr:`fragment` | 1     | Fragment identifier     | empty string         |
+   +------------------+-------+-------------------------+----------------------+
+
+   See section :ref:`urlparse-result-object` for more information on the result
+   object.
+
+   .. versionchanged:: 3.2
+      Result is a structured object rather than a simple 2-tuple.
+
+.. _parsing-ascii-encoded-bytes:
+
+Parsing ASCII Encoded Bytes
+---------------------------
+
+The URL parsing functions were originally designed to operate on character
+strings only. In practice, it is useful to be able to manipulate properly
+quoted and encoded URLs as sequences of ASCII bytes. Accordingly, the
+URL parsing functions in this module all operate on :class:`bytes` and
+:class:`bytearray` objects in addition to :class:`str` objects.
+
+If :class:`str` data is passed in, the result will also contain only
+:class:`str` data. If :class:`bytes` or :class:`bytearray` data is
+passed in, the result will contain only :class:`bytes` data.
+
+Attempting to mix :class:`str` data with :class:`bytes` or
+:class:`bytearray` in a single function call will result in a
+:exc:`TypeError` being raised, while attempting to pass in non-ASCII
+byte values will trigger :exc:`UnicodeDecodeError`.
+
+To support easier conversion of result objects between :class:`str` and
+:class:`bytes`, all return values from URL parsing functions provide
+either an :meth:`encode` method (when the result contains :class:`str`
+data) or a :meth:`decode` method (when the result contains :class:`bytes`
+data). The signatures of these methods match those of the corresponding
+:class:`str` and :class:`bytes` methods (except that the default encoding
+is ``'ascii'`` rather than ``'utf-8'``). Each produces a value of a
+corresponding type that contains either :class:`bytes` data (for
+:meth:`encode` methods) or :class:`str` data (for
+:meth:`decode` methods).
+
+Applications that need to operate on potentially improperly quoted URLs
+that may contain non-ASCII data will need to do their own decoding from
+bytes to characters before invoking the URL parsing methods.
+
+The behaviour described in this section applies only to the URL parsing
+functions. The URL quoting functions use their own rules when producing
+or consuming byte sequences as detailed in the documentation of the
+individual URL quoting functions.
+
+.. versionchanged:: 3.2
+   URL parsing functions now accept ASCII encoded byte sequences
+
+
+.. _urlparse-result-object:
+
+Structured Parse Results
+------------------------
+
+The result objects from the :func:`urlparse`, :func:`urlsplit`  and
+:func:`urldefrag` functions are subclasses of the :class:`tuple` type.
+These subclasses add the attributes listed in the documentation for
+those functions, the encoding and decoding support described in the
+previous section, as well as an additional method:
+
+.. method:: urllib.parse.SplitResult.geturl()
+
+   Return the re-combined version of the original URL as a string. This may
+   differ from the original URL in that the scheme may be normalized to lower
+   case and empty components may be dropped. Specifically, empty parameters,
+   queries, and fragment identifiers will be removed.
+
+   For :func:`urldefrag` results, only empty fragment identifiers will be removed.
+   For :func:`urlsplit` and :func:`urlparse` results, all noted changes will be
+   made to the URL returned by this method.
+
+   The result of this method remains unchanged if passed back through the original
+   parsing function:
+
+      >>> from urllib.parse import urlsplit
+      >>> url = 'HTTP://www.Python.org/doc/#'
+      >>> r1 = urlsplit(url)
+      >>> r1.geturl()
+      'http://www.Python.org/doc/'
+      >>> r2 = urlsplit(r1.geturl())
+      >>> r2.geturl()
+      'http://www.Python.org/doc/'
+
+
+The following classes provide the implementations of the structured parse
+results when operating on :class:`str` objects:
+
+.. class:: DefragResult(url, fragment)
+
+   Concrete class for :func:`urldefrag` results containing :class:`str`
+   data. The :meth:`encode` method returns a :class:`DefragResultBytes`
+   instance.
+
+   .. versionadded:: 3.2
+
+.. class:: ParseResult(scheme, netloc, path, params, query, fragment)
+
+   Concrete class for :func:`urlparse` results containing :class:`str`
+   data. The :meth:`encode` method returns a :class:`ParseResultBytes`
+   instance.
+
+.. class:: SplitResult(scheme, netloc, path, query, fragment)
+
+   Concrete class for :func:`urlsplit` results containing :class:`str`
+   data. The :meth:`encode` method returns a :class:`SplitResultBytes`
+   instance.
+
+
+The following classes provide the implementations of the parse results when
+operating on :class:`bytes` or :class:`bytearray` objects:
+
+.. class:: DefragResultBytes(url, fragment)
+
+   Concrete class for :func:`urldefrag` results containing :class:`bytes`
+   data. The :meth:`decode` method returns a :class:`DefragResult`
+   instance.
+
+   .. versionadded:: 3.2
+
+.. class:: ParseResultBytes(scheme, netloc, path, params, query, fragment)
+
+   Concrete class for :func:`urlparse` results containing :class:`bytes`
+   data. The :meth:`decode` method returns a :class:`ParseResult`
+   instance.
+
+   .. versionadded:: 3.2
+
+.. class:: SplitResultBytes(scheme, netloc, path, query, fragment)
+
+   Concrete class for :func:`urlsplit` results containing :class:`bytes`
+   data. The :meth:`decode` method returns a :class:`SplitResult`
+   instance.
+
+   .. versionadded:: 3.2
+
+
+URL Quoting
+-----------
+
+The URL quoting functions focus on taking program data and making it safe
+for use as URL components by quoting special characters and appropriately
+encoding non-ASCII text. They also support reversing these operations to
+recreate the original data from the contents of a URL component if that
+task isn't already covered by the URL parsing functions above.
 
 .. function:: quote(string, safe='/', encoding=None, errors=None)
 
@@ -322,16 +501,16 @@
    If it is a :class:`str`, unescaped non-ASCII characters in *string*
    are encoded into UTF-8 bytes.
 
-   Example: ``unquote_to_bytes('a%26%EF')`` yields
-   ``b'a&\xef'``.
+   Example: ``unquote_to_bytes('a%26%EF')`` yields ``b'a&\xef'``.
 
 
 .. function:: urlencode(query, doseq=False, safe='', encoding=None, errors=None)
 
    Convert a mapping object or a sequence of two-element tuples, which may
-   either be a :class:`str` or a :class:`bytes`,  to a "percent-encoded" string,
-   suitable to pass to :func:`urlopen` above as the optional *data* argument.
-   This is useful to pass a dictionary of form fields to a ``POST`` request.
+   either be a :class:`str` or a :class:`bytes`,  to a "percent-encoded"
+   string.  The resultant string must be converted to bytes using the
+   user-specified encoding before it is sent to :func:`urlopen` as the optional
+   *data* argument.
    The resulting string is a series of ``key=value`` pairs separated by ``'&'``
    characters, where both *key* and *value* are quoted using :func:`quote_plus`
    above. When a sequence of two-element tuples is used as the *query*
@@ -340,12 +519,16 @@
    the optional parameter *doseq* is evaluates to *True*, individual
    ``key=value`` pairs separated by ``'&'`` are generated for each element of
    the value sequence for the key.  The order of parameters in the encoded
-   string will match the order of parameter tuples in the sequence. This module
-   provides the functions :func:`parse_qs` and :func:`parse_qsl` which are used
-   to parse query strings into Python data structures.
+   string will match the order of parameter tuples in the sequence.
 
    When *query* parameter is a :class:`str`, the *safe*, *encoding* and *error*
-   parameters are sent the :func:`quote_plus` for encoding.
+   parameters are passed down to :func:`quote_plus` for encoding.
+
+   To reverse this encoding process, :func:`parse_qs` and :func:`parse_qsl` are
+   provided in this module to parse query strings into Python data structures.
+
+   Refer to :ref:`urllib examples <urllib-examples>` to find out how urlencode
+   method can be used for generating query string for a URL or data for POST.
 
    .. versionchanged:: 3.2
       Query parameter supports bytes and string objects.
@@ -376,57 +559,3 @@
 
    :rfc:`1738` - Uniform Resource Locators (URL)
       This specifies the formal syntax and semantics of absolute URLs.
-
-
-.. _urlparse-result-object:
-
-Results of :func:`urlparse` and :func:`urlsplit`
-------------------------------------------------
-
-The result objects from the :func:`urlparse` and :func:`urlsplit` functions are
-subclasses of the :class:`tuple` type.  These subclasses add the attributes
-described in those functions, as well as provide an additional method:
-
-.. method:: ParseResult.geturl()
-
-   Return the re-combined version of the original URL as a string. This may differ
-   from the original URL in that the scheme will always be normalized to lower case
-   and empty components may be dropped. Specifically, empty parameters, queries,
-   and fragment identifiers will be removed.
-
-   The result of this method is a fixpoint if passed back through the original
-   parsing function:
-
-      >>> import urllib.parse
-      >>> url = 'HTTP://www.Python.org/doc/#'
-
-      >>> r1 = urllib.parse.urlsplit(url)
-      >>> r1.geturl()
-      'http://www.Python.org/doc/'
-
-      >>> r2 = urllib.parse.urlsplit(r1.geturl())
-      >>> r2.geturl()
-      'http://www.Python.org/doc/'
-
-
-The following classes provide the implementations of the parse results:
-
-.. class:: BaseResult
-
-   Base class for the concrete result classes.  This provides most of the
-   attribute definitions.  It does not provide a :meth:`geturl` method.  It is
-   derived from :class:`tuple`, but does not override the :meth:`__init__` or
-   :meth:`__new__` methods.
-
-
-.. class:: ParseResult(scheme, netloc, path, params, query, fragment)
-
-   Concrete class for :func:`urlparse` results.  The :meth:`__new__` method is
-   overridden to support checking that the right number of arguments are passed.
-
-
-.. class:: SplitResult(scheme, netloc, path, query, fragment)
-
-   Concrete class for :func:`urlsplit` results.  The :meth:`__new__` method is
-   overridden to support checking that the right number of arguments are passed.
-

Modified: python/branches/pep-3151/Doc/library/urllib.request.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/urllib.request.rst	(original)
+++ python/branches/pep-3151/Doc/library/urllib.request.rst	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,4 @@
-:mod:`urllib.request` --- extensible library for opening URLs
+:mod:`urllib.request` --- Extensible library for opening URLs
 =============================================================
 
 .. module:: urllib.request
@@ -20,14 +20,15 @@
    Open the URL *url*, which can be either a string or a
    :class:`Request` object.
 
-   *data* may be a string specifying additional data to send to the
-   server, or ``None`` if no such data is needed.  Currently HTTP
-   requests are the only ones that use *data*; the HTTP request will
-   be a POST instead of a GET when the *data* parameter is provided.
-   *data* should be a buffer in the standard
+   *data* may be a bytes object specifying additional data to send to the
+   server, or ``None`` if no such data is needed. *data* may also be an
+   iterable object and in that case Content-Length value must be specified in
+   the headers. Currently HTTP requests are the only ones that use *data*; the
+   HTTP request will be a POST instead of a GET when the *data* parameter is
+   provided.  *data* should be a buffer in the standard
    :mimetype:`application/x-www-form-urlencoded` format.  The
-   :func:`urllib.parse.urlencode` function takes a mapping or sequence
-   of 2-tuples and returns a string in this format. urllib.request module uses
+   :func:`urllib.parse.urlencode` function takes a mapping or sequence of
+   2-tuples and returns a string in this format. urllib.request module uses
    HTTP/1.1 and includes ``Connection:close`` header in its HTTP requests.
 
    The optional *timeout* parameter specifies a timeout in seconds for
@@ -76,6 +77,9 @@
       HTTPS virtual hosts are now supported if possible (that is, if
       :data:`ssl.HAS_SNI` is true).
 
+   .. versionadded:: 3.2
+      *data* can be an iterable object.
+
 .. function:: install_opener(opener)
 
    Install an :class:`OpenerDirector` instance as the default global opener.
@@ -104,52 +108,6 @@
    member variable to modify its position in the handlers list.
 
 
-.. function:: urlretrieve(url, filename=None, reporthook=None, data=None)
-
-   Copy a network object denoted by a URL to a local file, if necessary. If the URL
-   points to a local file, or a valid cached copy of the object exists, the object
-   is not copied.  Return a tuple ``(filename, headers)`` where *filename* is the
-   local file name under which the object can be found, and *headers* is whatever
-   the :meth:`info` method of the object returned by :func:`urlopen` returned (for
-   a remote object, possibly cached). Exceptions are the same as for
-   :func:`urlopen`.
-
-   The second argument, if present, specifies the file location to copy to (if
-   absent, the location will be a tempfile with a generated name). The third
-   argument, if present, is a hook function that will be called once on
-   establishment of the network connection and once after each block read
-   thereafter.  The hook will be passed three arguments; a count of blocks
-   transferred so far, a block size in bytes, and the total size of the file.  The
-   third argument may be ``-1`` on older FTP servers which do not return a file
-   size in response to a retrieval request.
-
-   If the *url* uses the :file:`http:` scheme identifier, the optional *data*
-   argument may be given to specify a ``POST`` request (normally the request type
-   is ``GET``).  The *data* argument must in standard
-   :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
-   function below.
-
-   :func:`urlretrieve` will raise :exc:`ContentTooShortError` when it detects that
-   the amount of data available  was less than the expected amount (which is the
-   size reported by a  *Content-Length* header). This can occur, for example, when
-   the  download is interrupted.
-
-   The *Content-Length* is treated as a lower bound: if there's more data  to read,
-   urlretrieve reads more data, but if less data is available,  it raises the
-   exception.
-
-   You can still retrieve the downloaded data in this case, it is stored  in the
-   :attr:`content` attribute of the exception instance.
-
-   If no *Content-Length* header was supplied, urlretrieve can not check the size
-   of the data it has downloaded, and just returns it.  In this case you just have
-   to assume that the download was successful.
-
-.. function:: urlcleanup()
-
-   Clear the cache that may have been built up by previous calls to
-   :func:`urlretrieve`.
-
 .. function:: pathname2url(path)
 
    Convert the pathname *path* from the local syntax for a path to the form used in
@@ -218,115 +176,6 @@
    fetching of the image, this should be true.
 
 
-.. class:: URLopener(proxies=None, **x509)
-
-   Base class for opening and reading URLs.  Unless you need to support opening
-   objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`,
-   you probably want to use :class:`FancyURLopener`.
-
-   By default, the :class:`URLopener` class sends a :mailheader:`User-Agent` header
-   of ``urllib/VVV``, where *VVV* is the :mod:`urllib` version number.
-   Applications can define their own :mailheader:`User-Agent` header by subclassing
-   :class:`URLopener` or :class:`FancyURLopener` and setting the class attribute
-   :attr:`version` to an appropriate string value in the subclass definition.
-
-   The optional *proxies* parameter should be a dictionary mapping scheme names to
-   proxy URLs, where an empty dictionary turns proxies off completely.  Its default
-   value is ``None``, in which case environmental proxy settings will be used if
-   present, as discussed in the definition of :func:`urlopen`, above.
-
-   Additional keyword parameters, collected in *x509*, may be used for
-   authentication of the client when using the :file:`https:` scheme.  The keywords
-   *key_file* and *cert_file* are supported to provide an  SSL key and certificate;
-   both are needed to support client authentication.
-
-   :class:`URLopener` objects will raise an :exc:`IOError` exception if the server
-   returns an error code.
-
-    .. method:: open(fullurl, data=None)
-
-       Open *fullurl* using the appropriate protocol.  This method sets up cache and
-       proxy information, then calls the appropriate open method with its input
-       arguments.  If the scheme is not recognized, :meth:`open_unknown` is called.
-       The *data* argument has the same meaning as the *data* argument of
-       :func:`urlopen`.
-
-
-    .. method:: open_unknown(fullurl, data=None)
-
-       Overridable interface to open unknown URL types.
-
-
-    .. method:: retrieve(url, filename=None, reporthook=None, data=None)
-
-       Retrieves the contents of *url* and places it in *filename*.  The return value
-       is a tuple consisting of a local filename and either a
-       :class:`email.message.Message` object containing the response headers (for remote
-       URLs) or ``None`` (for local URLs).  The caller must then open and read the
-       contents of *filename*.  If *filename* is not given and the URL refers to a
-       local file, the input filename is returned.  If the URL is non-local and
-       *filename* is not given, the filename is the output of :func:`tempfile.mktemp`
-       with a suffix that matches the suffix of the last path component of the input
-       URL.  If *reporthook* is given, it must be a function accepting three numeric
-       parameters.  It will be called after each chunk of data is read from the
-       network.  *reporthook* is ignored for local URLs.
-
-       If the *url* uses the :file:`http:` scheme identifier, the optional *data*
-       argument may be given to specify a ``POST`` request (normally the request type
-       is ``GET``).  The *data* argument must in standard
-       :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
-       function below.
-
-
-    .. attribute:: version
-
-       Variable that specifies the user agent of the opener object.  To get
-       :mod:`urllib` to tell servers that it is a particular user agent, set this in a
-       subclass as a class variable or in the constructor before calling the base
-       constructor.
-
-
-.. class:: FancyURLopener(...)
-
-   :class:`FancyURLopener` subclasses :class:`URLopener` providing default handling
-   for the following HTTP response codes: 301, 302, 303, 307 and 401.  For the 30x
-   response codes listed above, the :mailheader:`Location` header is used to fetch
-   the actual URL.  For 401 response codes (authentication required), basic HTTP
-   authentication is performed.  For the 30x response codes, recursion is bounded
-   by the value of the *maxtries* attribute, which defaults to 10.
-
-   For all other response codes, the method :meth:`http_error_default` is called
-   which you can override in subclasses to handle the error appropriately.
-
-   .. note::
-
-      According to the letter of :rfc:`2616`, 301 and 302 responses to POST requests
-      must not be automatically redirected without confirmation by the user.  In
-      reality, browsers do allow automatic redirection of these responses, changing
-      the POST to a GET, and :mod:`urllib` reproduces this behaviour.
-
-   The parameters to the constructor are the same as those for :class:`URLopener`.
-
-   .. note::
-
-      When performing basic authentication, a :class:`FancyURLopener` instance calls
-      its :meth:`prompt_user_passwd` method.  The default implementation asks the
-      users for the required information on the controlling terminal.  A subclass may
-      override this method to support more appropriate behavior if needed.
-
-    The :class:`FancyURLopener` class offers one additional method that should be
-    overloaded to provide the appropriate behavior:
-
-    .. method:: prompt_user_passwd(host, realm)
-
-       Return information needed to authenticate the user at the given host in the
-       specified security realm.  The return value should be a tuple, ``(user,
-       password)``, which can be used for basic authentication.
-
-       The implementation prompts for this information on the terminal; an application
-       should override this method to use an appropriate interaction model in the local
-       environment.
-
 .. class:: OpenerDirector()
 
    The :class:`OpenerDirector` class opens URLs via :class:`BaseHandler`\ s chained
@@ -1118,7 +967,7 @@
 
    >>> import urllib.request
    >>> req = urllib.request.Request(url='https://localhost/cgi-bin/test.cgi',
-   ...                       data='This data is passed to stdin of the CGI')
+   ...                       data=b'This data is passed to stdin of the CGI')
    >>> f = urllib.request.urlopen(req)
    >>> print(f.read().decode('utf-8'))
    Got Data: "This data is passed to stdin of the CGI"
@@ -1194,11 +1043,13 @@
    >>> f = urllib.request.urlopen("http://www.musi-cal.com/cgi-bin/query?%s" % params)
    >>> print(f.read().decode('utf-8'))
 
-The following example uses the ``POST`` method instead::
+The following example uses the ``POST`` method instead. Note that params output
+from urlencode is encoded to bytes before it is sent to urlopen as data::
 
    >>> import urllib.request
    >>> import urllib.parse
    >>> params = urllib.parse.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
+   >>> params = params.encode('utf-8')
    >>> f = urllib.request.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
    >>> print(f.read().decode('utf-8'))
 
@@ -1219,6 +1070,170 @@
    >>> f.read().decode('utf-8')
 
 
+Legacy interface
+----------------
+
+The following functions and classes are ported from the Python 2 module
+``urllib`` (as opposed to ``urllib2``).  They might become deprecated at
+some point in the future.
+
+
+.. function:: urlretrieve(url, filename=None, reporthook=None, data=None)
+
+   Copy a network object denoted by a URL to a local file, if necessary. If the URL
+   points to a local file, or a valid cached copy of the object exists, the object
+   is not copied.  Return a tuple ``(filename, headers)`` where *filename* is the
+   local file name under which the object can be found, and *headers* is whatever
+   the :meth:`info` method of the object returned by :func:`urlopen` returned (for
+   a remote object, possibly cached). Exceptions are the same as for
+   :func:`urlopen`.
+
+   The second argument, if present, specifies the file location to copy to (if
+   absent, the location will be a tempfile with a generated name). The third
+   argument, if present, is a hook function that will be called once on
+   establishment of the network connection and once after each block read
+   thereafter.  The hook will be passed three arguments; a count of blocks
+   transferred so far, a block size in bytes, and the total size of the file.  The
+   third argument may be ``-1`` on older FTP servers which do not return a file
+   size in response to a retrieval request.
+
+   If the *url* uses the :file:`http:` scheme identifier, the optional *data*
+   argument may be given to specify a ``POST`` request (normally the request type
+   is ``GET``).  The *data* argument must in standard
+   :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
+   function below.
+
+   :func:`urlretrieve` will raise :exc:`ContentTooShortError` when it detects that
+   the amount of data available  was less than the expected amount (which is the
+   size reported by a  *Content-Length* header). This can occur, for example, when
+   the  download is interrupted.
+
+   The *Content-Length* is treated as a lower bound: if there's more data  to read,
+   urlretrieve reads more data, but if less data is available,  it raises the
+   exception.
+
+   You can still retrieve the downloaded data in this case, it is stored  in the
+   :attr:`content` attribute of the exception instance.
+
+   If no *Content-Length* header was supplied, urlretrieve can not check the size
+   of the data it has downloaded, and just returns it.  In this case you just have
+   to assume that the download was successful.
+
+.. function:: urlcleanup()
+
+   Clear the cache that may have been built up by previous calls to
+   :func:`urlretrieve`.
+
+.. class:: URLopener(proxies=None, **x509)
+
+   Base class for opening and reading URLs.  Unless you need to support opening
+   objects using schemes other than :file:`http:`, :file:`ftp:`, or :file:`file:`,
+   you probably want to use :class:`FancyURLopener`.
+
+   By default, the :class:`URLopener` class sends a :mailheader:`User-Agent` header
+   of ``urllib/VVV``, where *VVV* is the :mod:`urllib` version number.
+   Applications can define their own :mailheader:`User-Agent` header by subclassing
+   :class:`URLopener` or :class:`FancyURLopener` and setting the class attribute
+   :attr:`version` to an appropriate string value in the subclass definition.
+
+   The optional *proxies* parameter should be a dictionary mapping scheme names to
+   proxy URLs, where an empty dictionary turns proxies off completely.  Its default
+   value is ``None``, in which case environmental proxy settings will be used if
+   present, as discussed in the definition of :func:`urlopen`, above.
+
+   Additional keyword parameters, collected in *x509*, may be used for
+   authentication of the client when using the :file:`https:` scheme.  The keywords
+   *key_file* and *cert_file* are supported to provide an  SSL key and certificate;
+   both are needed to support client authentication.
+
+   :class:`URLopener` objects will raise an :exc:`IOError` exception if the server
+   returns an error code.
+
+    .. method:: open(fullurl, data=None)
+
+       Open *fullurl* using the appropriate protocol.  This method sets up cache and
+       proxy information, then calls the appropriate open method with its input
+       arguments.  If the scheme is not recognized, :meth:`open_unknown` is called.
+       The *data* argument has the same meaning as the *data* argument of
+       :func:`urlopen`.
+
+
+    .. method:: open_unknown(fullurl, data=None)
+
+       Overridable interface to open unknown URL types.
+
+
+    .. method:: retrieve(url, filename=None, reporthook=None, data=None)
+
+       Retrieves the contents of *url* and places it in *filename*.  The return value
+       is a tuple consisting of a local filename and either a
+       :class:`email.message.Message` object containing the response headers (for remote
+       URLs) or ``None`` (for local URLs).  The caller must then open and read the
+       contents of *filename*.  If *filename* is not given and the URL refers to a
+       local file, the input filename is returned.  If the URL is non-local and
+       *filename* is not given, the filename is the output of :func:`tempfile.mktemp`
+       with a suffix that matches the suffix of the last path component of the input
+       URL.  If *reporthook* is given, it must be a function accepting three numeric
+       parameters.  It will be called after each chunk of data is read from the
+       network.  *reporthook* is ignored for local URLs.
+
+       If the *url* uses the :file:`http:` scheme identifier, the optional *data*
+       argument may be given to specify a ``POST`` request (normally the request type
+       is ``GET``).  The *data* argument must in standard
+       :mimetype:`application/x-www-form-urlencoded` format; see the :func:`urlencode`
+       function below.
+
+
+    .. attribute:: version
+
+       Variable that specifies the user agent of the opener object.  To get
+       :mod:`urllib` to tell servers that it is a particular user agent, set this in a
+       subclass as a class variable or in the constructor before calling the base
+       constructor.
+
+
+.. class:: FancyURLopener(...)
+
+   :class:`FancyURLopener` subclasses :class:`URLopener` providing default handling
+   for the following HTTP response codes: 301, 302, 303, 307 and 401.  For the 30x
+   response codes listed above, the :mailheader:`Location` header is used to fetch
+   the actual URL.  For 401 response codes (authentication required), basic HTTP
+   authentication is performed.  For the 30x response codes, recursion is bounded
+   by the value of the *maxtries* attribute, which defaults to 10.
+
+   For all other response codes, the method :meth:`http_error_default` is called
+   which you can override in subclasses to handle the error appropriately.
+
+   .. note::
+
+      According to the letter of :rfc:`2616`, 301 and 302 responses to POST requests
+      must not be automatically redirected without confirmation by the user.  In
+      reality, browsers do allow automatic redirection of these responses, changing
+      the POST to a GET, and :mod:`urllib` reproduces this behaviour.
+
+   The parameters to the constructor are the same as those for :class:`URLopener`.
+
+   .. note::
+
+      When performing basic authentication, a :class:`FancyURLopener` instance calls
+      its :meth:`prompt_user_passwd` method.  The default implementation asks the
+      users for the required information on the controlling terminal.  A subclass may
+      override this method to support more appropriate behavior if needed.
+
+   The :class:`FancyURLopener` class offers one additional method that should be
+   overloaded to provide the appropriate behavior:
+
+   .. method:: prompt_user_passwd(host, realm)
+
+      Return information needed to authenticate the user at the given host in the
+      specified security realm.  The return value should be a tuple, ``(user,
+      password)``, which can be used for basic authentication.
+
+      The implementation prompts for this information on the terminal; an application
+      should override this method to use an appropriate interaction model in the local
+      environment.
+
+
 :mod:`urllib.request` Restrictions
 ----------------------------------
 
@@ -1272,15 +1287,15 @@
 
 
 
-:mod:`urllib.response` --- Response classes used by urllib.
-===========================================================
+:mod:`urllib.response` --- Response classes used by urllib
+==========================================================
 
 .. module:: urllib.response
    :synopsis: Response classes used by urllib.
 
 The :mod:`urllib.response` module defines functions and classes which define a
 minimal file like interface, including ``read()`` and ``readline()``. The
-typical response object is an addinfourl instance, which defines and ``info()``
+typical response object is an addinfourl instance, which defines an ``info()``
 method and that returns headers and a ``geturl()`` method that returns the url.
 Functions defined by this module are used internally by the
 :mod:`urllib.request` module.

Modified: python/branches/pep-3151/Doc/library/uu.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/uu.rst	(original)
+++ python/branches/pep-3151/Doc/library/uu.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Encode and decode files in uuencode format.
 .. moduleauthor:: Lance Ellinghouse
 
+**Source code:** :source:`Lib/uu.py`
+
+--------------
 
 This module encodes and decodes files in uuencode format, allowing arbitrary
 binary data to be transferred over ASCII-only connections. Wherever a file
@@ -56,4 +59,3 @@
 
    Module :mod:`binascii`
       Support module containing ASCII-to-binary and binary-to-ASCII conversions.
-

Modified: python/branches/pep-3151/Doc/library/warnings.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/warnings.rst	(original)
+++ python/branches/pep-3151/Doc/library/warnings.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. module:: warnings
    :synopsis: Issue warning messages and control their disposition.
 
+**Source code:** :source:`Lib/warnings.py`
+
+--------------
 
 Warning messages are typically issued in situations where it is useful to alert
 the user of some condition in a program, where that condition (normally) doesn't
@@ -249,6 +252,8 @@
 entries from the warnings list before each new operation).
 
 
+.. _warning-ignored:
+
 Updating Code For New Versions of Python
 ----------------------------------------
 
@@ -279,6 +284,9 @@
 developer want to be notified that your code is using a deprecated module, to a
 user this information is essentially noise and provides no benefit to them.
 
+The :mod:`unittest` module has been also updated to use the ``'default'``
+filter while running tests.
+
 
 .. _warning-functions:
 

Modified: python/branches/pep-3151/Doc/library/wave.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/wave.rst	(original)
+++ python/branches/pep-3151/Doc/library/wave.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,10 @@
 .. sectionauthor:: Moshe Zadka <moshez at zadka.site.co.il>
 .. Documentations stolen from comments in file.
 
+**Source code:** :source:`Lib/wave.py`
+
+--------------
+
 The :mod:`wave` module provides a convenient interface to the WAV sound format.
 It does not support compression/decompression, but it does support mono/stereo.
 
@@ -14,8 +18,8 @@
 
 .. function:: open(file, mode=None)
 
-   If *file* is a string, open the file by that name, other treat it as a seekable
-   file-like object. *mode* can be any of
+   If *file* is a string, open the file by that name, otherwise treat it as a
+   seekable file-like object.  *mode* can be any of
 
    ``'r'``, ``'rb'``
       Read only mode.
@@ -26,9 +30,14 @@
    Note that it does not allow read/write WAV files.
 
    A *mode* of ``'r'`` or ``'rb'`` returns a :class:`Wave_read` object, while a
-   *mode* of ``'w'`` or ``'wb'`` returns a :class:`Wave_write` object.  If *mode*
-   is omitted and a file-like  object is passed as *file*, ``file.mode`` is used as
-   the default value for *mode* (the ``'b'`` flag is still added if  necessary).
+   *mode* of ``'w'`` or ``'wb'`` returns a :class:`Wave_write` object.  If
+   *mode* is omitted and a file-like object is passed as *file*, ``file.mode``
+   is used as the default value for *mode* (the ``'b'`` flag is still added if
+   necessary).
+
+   If you pass in a file-like object, the wave object will not close it when its
+   :meth:`close` method is called; it is the caller's responsibility to close
+   the file object.
 
 
 .. function:: openfp(file, mode)
@@ -52,8 +61,8 @@
 
 .. method:: Wave_read.close()
 
-   Close the stream, and make the instance unusable. This is called automatically
-   on object collection.
+   Close the stream if it was opened by :mod:`wave`, and make the instance
+   unusable.  This is called automatically on object collection.
 
 
 .. method:: Wave_read.getnchannels()
@@ -139,8 +148,8 @@
 
 .. method:: Wave_write.close()
 
-   Make sure *nframes* is correct, and close the file. This method is called upon
-   deletion.
+   Make sure *nframes* is correct, and close the file if it was opened by
+   :mod:`wave`.  This method is called upon object collection.
 
 
 .. method:: Wave_write.setnchannels(n)
@@ -196,6 +205,7 @@
 
    Write audio frames and make sure *nframes* is correct.
 
+
 Note that it is invalid to set any parameters after calling :meth:`writeframes`
 or :meth:`writeframesraw`, and any attempt to do so will raise
 :exc:`wave.Error`.

Modified: python/branches/pep-3151/Doc/library/weakref.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/weakref.rst	(original)
+++ python/branches/pep-3151/Doc/library/weakref.rst	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,9 @@
 .. moduleauthor:: Martin von Löwis <martin at loewis.home.cs.tu-berlin.de>
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/weakref.py`
+
+--------------
 
 The :mod:`weakref` module allows the Python programmer to create :dfn:`weak
 references` to objects.

Modified: python/branches/pep-3151/Doc/library/webbrowser.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/webbrowser.rst	(original)
+++ python/branches/pep-3151/Doc/library/webbrowser.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/webbrowser.py`
+
+--------------
 
 The :mod:`webbrowser` module provides a high-level interface to allow displaying
 Web-based documents to users. Under most circumstances, simply calling the
@@ -31,8 +34,8 @@
 
 The script :program:`webbrowser` can be used as a command-line interface for the
 module. It accepts an URL as the argument. It accepts the following optional
-parameters: :option:`-n` opens the URL in a new browser window, if possible;
-:option:`-t` opens the URL in a new browser page ("tab"). The options are,
+parameters: ``-n`` opens the URL in a new browser window, if possible;
+``-t`` opens the URL in a new browser page ("tab"). The options are,
 naturally, mutually exclusive.
 
 The following exception is defined:
@@ -64,7 +67,6 @@
    Open *url* in a new window of the default browser, if possible, otherwise, open
    *url* in the only browser window.
 
-
 .. function:: open_new_tab(url)
 
    Open *url* in a new page ("tab") of the default browser, if possible, otherwise

Modified: python/branches/pep-3151/Doc/library/xdrlib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/xdrlib.rst	(original)
+++ python/branches/pep-3151/Doc/library/xdrlib.rst	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,10 @@
    single: XDR
    single: External Data Representation
 
+**Source code:** :source:`Lib/xdrlib.py`
+
+--------------
+
 The :mod:`xdrlib` module supports the External Data Representation Standard as
 described in :rfc:`1014`, written by Sun Microsystems, Inc. June 1987.  It
 supports most of the data types described in the RFC.

Modified: python/branches/pep-3151/Doc/library/xml.dom.minidom.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/xml.dom.minidom.rst	(original)
+++ python/branches/pep-3151/Doc/library/xml.dom.minidom.rst	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,9 @@
 .. sectionauthor:: Paul Prescod <paul at prescod.net>
 .. sectionauthor:: Martin v. Löwis <martin at v.loewis.de>
 
+**Source code:** :source:`Lib/xml/dom/minidom.py`
+
+--------------
 
 :mod:`xml.dom.minidom` is a light-weight implementation of the Document Object
 Model interface.  It is intended to be simpler than the full DOM and also
@@ -122,7 +125,7 @@
           ... # Work with dom.
 
 
-.. method:: Node.writexml(writer, indent="", addindent="", newl="", encoding="")
+.. method:: Node.writexml(writer, indent="", addindent="", newl="")
 
    Write XML to the writer object.  The writer should have a :meth:`write` method
    which matches that of the file object interface.  The *indent* parameter is the
@@ -130,8 +133,8 @@
    indentation to use for subnodes of the current one.  The *newl* parameter
    specifies the string to use to terminate newlines.
 
-   For the :class:`Document` node, an additional keyword argument *encoding* can be
-   used to specify the encoding field of the XML header.
+   For the :class:`Document` node, an additional keyword argument *encoding* can
+   be used to specify the encoding field of the XML header.
 
 
 .. method:: Node.toxml(encoding=None)

Modified: python/branches/pep-3151/Doc/library/xml.dom.pulldom.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/xml.dom.pulldom.rst	(original)
+++ python/branches/pep-3151/Doc/library/xml.dom.pulldom.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Support for building partial DOM trees from SAX events.
 .. moduleauthor:: Paul Prescod <paul at prescod.net>
 
+**Source code:** :source:`Lib/xml/dom/pulldom.py`
+
+--------------
 
 :mod:`xml.dom.pulldom` allows building only selected portions of a Document
 Object Model representation of a document from SAX events.

Modified: python/branches/pep-3151/Doc/library/xml.etree.elementtree.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/xml.etree.elementtree.rst	(original)
+++ python/branches/pep-3151/Doc/library/xml.etree.elementtree.rst	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,9 @@
    :synopsis: Implementation of the ElementTree API.
 .. moduleauthor:: Fredrik Lundh <fredrik at pythonware.com>
 
+**Source code:** :source:`Lib/xml/etree/ElementTree.py`
+
+--------------
 
 The :class:`Element` type is a flexible container object, designed to store
 hierarchical data structures in memory.  The type can be described as a cross

Modified: python/branches/pep-3151/Doc/library/xmlrpc.client.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/xmlrpc.client.rst	(original)
+++ python/branches/pep-3151/Doc/library/xmlrpc.client.rst	Sat Feb 26 08:16:32 2011
@@ -10,6 +10,10 @@
 .. XXX Not everything is documented yet.  It might be good to describe
    Marshaller, Unmarshaller, getparser, dumps, loads, and Transport.
 
+**Source code:** :source:`Lib/xmlrpc/client.py`
+
+--------------
+
 XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a
 transport.  With it, a client can call methods with parameters on a remote
 server (the server is named by a URI) and get back structured data.  This module

Modified: python/branches/pep-3151/Doc/library/xmlrpc.server.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/xmlrpc.server.rst	(original)
+++ python/branches/pep-3151/Doc/library/xmlrpc.server.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,9 @@
 .. moduleauthor:: Brian Quinlan <brianq at activestate.com>
 .. sectionauthor:: Fred L. Drake, Jr. <fdrake at acm.org>
 
+**Source code:** :source:`Lib/xmlrpc/server.py`
+
+--------------
 
 The :mod:`xmlrpc.server` module provides a basic server framework for XML-RPC
 servers written in Python.  Servers can either be free standing, using

Modified: python/branches/pep-3151/Doc/library/zipfile.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/zipfile.rst	(original)
+++ python/branches/pep-3151/Doc/library/zipfile.rst	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,10 @@
 .. moduleauthor:: James C. Ahlstrom <jim at interet.com>
 .. sectionauthor:: James C. Ahlstrom <jim at interet.com>
 
+**Source code:** :source:`Lib/zipfile.py`
+
+--------------
+
 The ZIP file format is a common archive and compression standard. This module
 provides tools to create, read, write, append, and list a ZIP file.  Any
 advanced use of this module will require an understanding of the format, as
@@ -44,12 +48,14 @@
 
 
 .. class:: ZipFile
+   :noindex:
 
    The class for reading and writing ZIP files.  See section
    :ref:`zipfile-objects` for constructor details.
 
 
 .. class:: PyZipFile
+   :noindex:
 
    Class for creating ZIP archives containing Python libraries.
 
@@ -177,8 +183,8 @@
    .. note::
 
       The file-like object is read-only and provides the following methods:
-      :meth:`read`, :meth:`readline`, :meth:`readlines`, :meth:`__iter__`,
-      :meth:`__next__`.
+      :meth:`!read`, :meth:`!readline`, :meth:`!readlines`, :meth:`!__iter__`,
+      :meth:`!__next__`.
 
    .. note::
 
@@ -293,7 +299,7 @@
 
    .. note::
 
-      When passing a :class:`ZipInfo` instance as the *zinfo_or_acrname* parameter,
+      When passing a :class:`ZipInfo` instance as the *zinfo_or_arcname* parameter,
       the compression method used will be that specified in the *compress_type*
       member of the given :class:`ZipInfo` instance.  By default, the
       :class:`ZipInfo` constructor sets this member to :const:`ZIP_STORED`.
@@ -317,37 +323,53 @@
    string no longer than 65535 bytes.  Comments longer than this will be
    truncated in the written archive when :meth:`ZipFile.close` is called.
 
+
 .. _pyzipfile-objects:
 
 PyZipFile Objects
 -----------------
 
 The :class:`PyZipFile` constructor takes the same parameters as the
-:class:`ZipFile` constructor.  Instances have one method in addition to those of
-:class:`ZipFile` objects.
+:class:`ZipFile` constructor, and one additional parameter, *optimize*.
+
+.. class:: PyZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=False, \
+                     optimize=-1)
+
+   .. versionadded:: 3.2
+      The *optimize* parameter.
+
+   Instances have one method in addition to those of :class:`ZipFile` objects:
 
+   .. method:: PyZipFile.writepy(pathname, basename='')
 
-.. method:: PyZipFile.writepy(pathname, basename='')
+      Search for files :file:`\*.py` and add the corresponding file to the
+      archive.
 
-   Search for files :file:`\*.py` and add the corresponding file to the archive.
-   The corresponding file is a :file:`\*.pyo` file if available, else a
-   :file:`\*.pyc` file, compiling if necessary.  If the pathname is a file, the
-   filename must end with :file:`.py`, and just the (corresponding
-   :file:`\*.py[co]`) file is added at the top level (no path information).  If the
-   pathname is a file that does not end with :file:`.py`, a :exc:`RuntimeError`
-   will be raised.  If it is a directory, and the directory is not a package
-   directory, then all the files :file:`\*.py[co]` are added at the top level.  If
-   the directory is a package directory, then all :file:`\*.py[co]` are added under
-   the package name as a file path, and if any subdirectories are package
-   directories, all of these are added recursively.  *basename* is intended for
-   internal use only.  The :meth:`writepy` method makes archives with file names
-   like this::
-
-      string.pyc                                # Top level name
-      test/__init__.pyc                         # Package directory
-      test/testall.pyc                          # Module test.testall
-      test/bogus/__init__.pyc                   # Subpackage directory
-      test/bogus/myfile.pyc                     # Submodule test.bogus.myfile
+      If the *optimize* parameter to :class:`PyZipFile` was not given or ``-1``,
+      the corresponding file is a :file:`\*.pyo` file if available, else a
+      :file:`\*.pyc` file, compiling if necessary.
+
+      If the *optimize* parameter to :class:`PyZipFile` was ``0``, ``1`` or
+      ``2``, only files with that optimization level (see :func:`compile`) are
+      added to the archive, compiling if necessary.
+
+      If the pathname is a file, the filename must end with :file:`.py`, and
+      just the (corresponding :file:`\*.py[co]`) file is added at the top level
+      (no path information).  If the pathname is a file that does not end with
+      :file:`.py`, a :exc:`RuntimeError` will be raised.  If it is a directory,
+      and the directory is not a package directory, then all the files
+      :file:`\*.py[co]` are added at the top level.  If the directory is a
+      package directory, then all :file:`\*.py[co]` are added under the package
+      name as a file path, and if any subdirectories are package directories,
+      all of these are added recursively.  *basename* is intended for internal
+      use only.  The :meth:`writepy` method makes archives with file names like
+      this::
+
+         string.pyc                   # Top level name
+         test/__init__.pyc            # Package directory
+         test/testall.pyc             # Module test.testall
+         test/bogus/__init__.pyc      # Subpackage directory
+         test/bogus/myfile.pyc        # Submodule test.bogus.myfile
 
 
 .. _zipinfo-objects:

Modified: python/branches/pep-3151/Doc/library/zlib.rst
==============================================================================
--- python/branches/pep-3151/Doc/library/zlib.rst	(original)
+++ python/branches/pep-3151/Doc/library/zlib.rst	Sat Feb 26 08:16:32 2011
@@ -51,9 +51,9 @@
    regardless of sign.
 
 
-.. function:: compress(string[, level])
+.. function:: compress(data[, level])
 
-   Compresses the data in *string*, returning a string contained compressed data.
+   Compresses the bytes in *data*, returning a bytes object containing compressed data.
    *level* is an integer from ``1`` to ``9`` controlling the level of compression;
    ``1`` is fastest and produces the least compression, ``9`` is slowest and
    produces the most.  The default value is ``6``.  Raises the :exc:`error`
@@ -92,9 +92,9 @@
    regardless of sign.
 
 
-.. function:: decompress(string[, wbits[, bufsize]])
+.. function:: decompress(data[, wbits[, bufsize]])
 
-   Decompresses the data in *string*, returning a string containing the
+   Decompresses the bytes in *data*, returning a bytes object containing the
    uncompressed data.  The *wbits* parameter controls the size of the window
    buffer, and is discussed further below.
    If *bufsize* is given, it is used as the initial size of the output
@@ -125,21 +125,21 @@
 Compression objects support the following methods:
 
 
-.. method:: Compress.compress(string)
+.. method:: Compress.compress(data)
 
-   Compress *string*, returning a string containing compressed data for at least
-   part of the data in *string*.  This data should be concatenated to the output
+   Compress *data*, returning a bytes object containing compressed data for at least
+   part of the data in *data*.  This data should be concatenated to the output
    produced by any preceding calls to the :meth:`compress` method.  Some input may
    be kept in internal buffers for later processing.
 
 
 .. method:: Compress.flush([mode])
 
-   All pending input is processed, and a string containing the remaining compressed
+   All pending input is processed, and a bytes object containing the remaining compressed
    output is returned.  *mode* can be selected from the constants
    :const:`Z_SYNC_FLUSH`,  :const:`Z_FULL_FLUSH`,  or  :const:`Z_FINISH`,
    defaulting to :const:`Z_FINISH`.  :const:`Z_SYNC_FLUSH` and
-   :const:`Z_FULL_FLUSH` allow compressing further strings of data, while
+   :const:`Z_FULL_FLUSH` allow compressing further bytestrings of data, while
    :const:`Z_FINISH` finishes the compressed stream and  prevents compressing any
    more data.  After calling :meth:`flush` with *mode* set to :const:`Z_FINISH`,
    the :meth:`compress` method cannot be called again; the only realistic action is
@@ -157,31 +157,31 @@
 
 .. attribute:: Decompress.unused_data
 
-   A string which contains any bytes past the end of the compressed data. That is,
+   A bytes object which contains any bytes past the end of the compressed data. That is,
    this remains ``""`` until the last byte that contains compression data is
-   available.  If the whole string turned out to contain compressed data, this is
-   ``""``, the empty string.
+   available.  If the whole bytestring turned out to contain compressed data, this is
+   ``b""``, an empty bytes object.
 
-   The only way to determine where a string of compressed data ends is by actually
+   The only way to determine where a bytestring of compressed data ends is by actually
    decompressing it.  This means that when compressed data is contained part of a
    larger file, you can only find the end of it by reading data and feeding it
-   followed by some non-empty string into a decompression object's
+   followed by some non-empty bytestring into a decompression object's
    :meth:`decompress` method until the :attr:`unused_data` attribute is no longer
-   the empty string.
+   empty.
 
 
 .. attribute:: Decompress.unconsumed_tail
 
-   A string that contains any data that was not consumed by the last
+   A bytes object that contains any data that was not consumed by the last
    :meth:`decompress` call because it exceeded the limit for the uncompressed data
    buffer.  This data has not yet been seen by the zlib machinery, so you must feed
    it (possibly with further data concatenated to it) back to a subsequent
    :meth:`decompress` method call in order to get correct output.
 
 
-.. method:: Decompress.decompress(string[, max_length])
+.. method:: Decompress.decompress(data[, max_length])
 
-   Decompress *string*, returning a string containing the uncompressed data
+   Decompress *data*, returning a bytes object containing the uncompressed data
    corresponding to at least part of the data in *string*.  This data should be
    concatenated to the output produced by any preceding calls to the
    :meth:`decompress` method.  Some of the input data may be preserved in internal
@@ -190,15 +190,15 @@
    If the optional parameter *max_length* is supplied then the return value will be
    no longer than *max_length*. This may mean that not all of the compressed input
    can be processed; and unconsumed data will be stored in the attribute
-   :attr:`unconsumed_tail`. This string must be passed to a subsequent call to
+   :attr:`unconsumed_tail`. This bytestring must be passed to a subsequent call to
    :meth:`decompress` if decompression is to continue.  If *max_length* is not
-   supplied then the whole input is decompressed, and :attr:`unconsumed_tail` is an
-   empty string.
+   supplied then the whole input is decompressed, and :attr:`unconsumed_tail` is
+   empty.
 
 
 .. method:: Decompress.flush([length])
 
-   All pending input is processed, and a string containing the remaining
+   All pending input is processed, and a bytes object containing the remaining
    uncompressed output is returned.  After calling :meth:`flush`, the
    :meth:`decompress` method cannot be called again; the only realistic action is
    to delete the object.

Modified: python/branches/pep-3151/Doc/license.rst
==============================================================================
--- python/branches/pep-3151/Doc/license.rst	(original)
+++ python/branches/pep-3151/Doc/license.rst	Sat Feb 26 08:16:32 2011
@@ -108,7 +108,9 @@
 +----------------+--------------+------------+------------+-----------------+
 | 3.1.2          | 3.1          | 2010       | PSF        | yes             |
 +----------------+--------------+------------+------------+-----------------+
-| 3.2            | 3.1          | 2010       | PSF        | yes             |
+| 3.2            | 3.1          | 2011       | PSF        | yes             |
++----------------+--------------+------------+------------+-----------------+
+| 3.3            | 3.2          | 2012       | PSF        | yes             |
 +----------------+--------------+------------+------------+-----------------+
 
 .. note::
@@ -138,7 +140,7 @@
    analyze, test, perform and/or display publicly, prepare derivative works,
    distribute, and otherwise use Python |release| alone or in any derivative
    version, provided, however, that PSF's License Agreement and PSF's notice of
-   copyright, i.e., "Copyright © 2001-2010 Python Software Foundation; All Rights
+   copyright, i.e., "Copyright © 2001-2011 Python Software Foundation; All Rights
    Reserved" are retained in Python |release| alone or in any derivative version
    prepared by Licensee.
 
@@ -906,7 +908,7 @@
 sources unless the zlib version found on the system is too old to be
 used for the build::
 
-  Copyright (C) 1995-2010 Jean-loup Gailly and Mark Adler
+  Copyright (C) 1995-2011 Jean-loup Gailly and Mark Adler
 
   This software is provided 'as-is', without any express or implied
   warranty.  In no event will the authors be held liable for any damages

Modified: python/branches/pep-3151/Doc/make.bat
==============================================================================
--- python/branches/pep-3151/Doc/make.bat	(original)
+++ python/branches/pep-3151/Doc/make.bat	Sat Feb 26 08:16:32 2011
@@ -1,59 +1,59 @@
-@@echo off
-setlocal
-
-set SVNROOT=http://svn.python.org/projects
-if "%PYTHON%" EQU "" set PYTHON=..\pcbuild\python
-if "%HTMLHELP%" EQU "" set HTMLHELP=%ProgramFiles%\HTML Help Workshop\hhc.exe
-if "%DISTVERSION%" EQU "" for /f "usebackq" %%v in (`%PYTHON% tools/sphinxext/patchlevel.py`) do set DISTVERSION=%%v
-
-if "%1" EQU "" goto help
-if "%1" EQU "html" goto build
-if "%1" EQU "htmlhelp" goto build
-if "%1" EQU "latex" goto build
-if "%1" EQU "text" goto build
-if "%1" EQU "suspicious" goto build
-if "%1" EQU "linkcheck" goto build
-if "%1" EQU "changes" goto build
-if "%1" EQU "checkout" goto checkout
-if "%1" EQU "update" goto update
-
-:help
-set this=%~n0
-echo HELP
-echo.
-echo %this% checkout
-echo %this% update
-echo %this% html
-echo %this% htmlhelp
-echo %this% latex
-echo %this% text
-echo %this% suspicious
-echo %this% linkcheck
-echo %this% changes
-echo.
-goto end
-
-:checkout
-svn co %SVNROOT%/external/Sphinx-1.0.4/sphinx tools/sphinx
-svn co %SVNROOT%/external/docutils-0.6/docutils tools/docutils
-svn co %SVNROOT%/external/Jinja-2.3.1/jinja2 tools/jinja2
-svn co %SVNROOT%/external/Pygments-1.3.1/pygments tools/pygments
-goto end
-
-:update
-svn update tools/sphinx
-svn update tools/docutils
-svn update tools/jinja2
-svn update tools/pygments
-goto end
-
-:build
-if not exist build mkdir build
-if not exist build\%1 mkdir build\%1
-if not exist build\doctrees mkdir build\doctrees
-cmd /C %PYTHON% --version
-cmd /C %PYTHON% tools\sphinx-build.py -b%1 -dbuild\doctrees . build\%*
-if "%1" EQU "htmlhelp" "%HTMLHELP%" build\htmlhelp\python%DISTVERSION:.=%.hhp
-goto end
-
-:end
+@@echo off
+setlocal
+
+set SVNROOT=http://svn.python.org/projects
+if "%PYTHON%" EQU "" set PYTHON=..\pcbuild\python
+if "%HTMLHELP%" EQU "" set HTMLHELP=%ProgramFiles%\HTML Help Workshop\hhc.exe
+if "%DISTVERSION%" EQU "" for /f "usebackq" %%v in (`%PYTHON% tools/sphinxext/patchlevel.py`) do set DISTVERSION=%%v
+
+if "%1" EQU "" goto help
+if "%1" EQU "html" goto build
+if "%1" EQU "htmlhelp" goto build
+if "%1" EQU "latex" goto build
+if "%1" EQU "text" goto build
+if "%1" EQU "suspicious" goto build
+if "%1" EQU "linkcheck" goto build
+if "%1" EQU "changes" goto build
+if "%1" EQU "checkout" goto checkout
+if "%1" EQU "update" goto update
+
+:help
+set this=%~n0
+echo HELP
+echo.
+echo %this% checkout
+echo %this% update
+echo %this% html
+echo %this% htmlhelp
+echo %this% latex
+echo %this% text
+echo %this% suspicious
+echo %this% linkcheck
+echo %this% changes
+echo.
+goto end
+
+:checkout
+svn co %SVNROOT%/external/Sphinx-1.0.7/sphinx tools/sphinx
+svn co %SVNROOT%/external/docutils-0.6/docutils tools/docutils
+svn co %SVNROOT%/external/Jinja-2.3.1/jinja2 tools/jinja2
+svn co %SVNROOT%/external/Pygments-1.3.1/pygments tools/pygments
+goto end
+
+:update
+svn update tools/sphinx
+svn update tools/docutils
+svn update tools/jinja2
+svn update tools/pygments
+goto end
+
+:build
+if not exist build mkdir build
+if not exist build\%1 mkdir build\%1
+if not exist build\doctrees mkdir build\doctrees
+cmd /C %PYTHON% --version
+cmd /C %PYTHON% tools\sphinx-build.py -b%1 -dbuild\doctrees . build\%*
+if "%1" EQU "htmlhelp" "%HTMLHELP%" build\htmlhelp\python%DISTVERSION:.=%.hhp
+goto end
+
+:end

Modified: python/branches/pep-3151/Doc/reference/compound_stmts.rst
==============================================================================
--- python/branches/pep-3151/Doc/reference/compound_stmts.rst	(original)
+++ python/branches/pep-3151/Doc/reference/compound_stmts.rst	Sat Feb 26 08:16:32 2011
@@ -285,12 +285,11 @@
 
 Before an except clause's suite is executed, details about the exception are
 stored in the :mod:`sys` module and can be access via :func:`sys.exc_info`.
-:func:`sys.exc_info` returns a 3-tuple consisting of: ``exc_type``, the
-exception class; ``exc_value``, the exception instance; ``exc_traceback``, a
-traceback object (see section :ref:`types`) identifying the point in the program
-where the exception occurred. :func:`sys.exc_info` values are restored to their
-previous values (before the call) when returning from a function that handled an
-exception.
+:func:`sys.exc_info` returns a 3-tuple consisting of the exception class, the
+exception instance and a traceback object (see section :ref:`types`) identifying
+the point in the program where the exception occurred.  :func:`sys.exc_info`
+values are restored to their previous values (before the call) when returning
+from a function that handled an exception.
 
 .. index::
    keyword: else
@@ -561,7 +560,16 @@
 A class definition is an executable statement.  The inheritance list usually
 gives a list of base classes (see :ref:`metaclasses` for more advanced uses), so
 each item in the list should evaluate to a class object which allows
-subclassing.
+subclassing.  Classes without an inheritance list inherit, by default, from the
+base class :class:`object`; hence, ::
+
+   class Foo:
+       pass
+
+is equivalent to ::
+
+   class Foo(object):
+       pass
 
 The class's suite is then executed in a new execution frame (see :ref:`naming`),
 using a newly created local namespace and the original global namespace.

Modified: python/branches/pep-3151/Doc/reference/datamodel.rst
==============================================================================
--- python/branches/pep-3151/Doc/reference/datamodel.rst	(original)
+++ python/branches/pep-3151/Doc/reference/datamodel.rst	Sat Feb 26 08:16:32 2011
@@ -618,7 +618,7 @@
       an object passed to the C function as an implicit extra argument.  An example of
       a built-in method is ``alist.append()``, assuming *alist* is a list object. In
       this case, the special read-only attribute :attr:`__self__` is set to the object
-      denoted by *list*.
+      denoted by *alist*.
 
    Classes
       Classes are callable.  These objects normally act as factories for new
@@ -1591,7 +1591,7 @@
 Once those definitions are executed, the ordered dictionary is fully populated
 and the metaclass's :meth:`__new__` method gets invoked.  That method builds
 the new type and it saves the ordered dictionary keys in an attribute
-called *members*.
+called ``members``.
 
 
 Customizing instance and subclass checks
@@ -1987,7 +1987,7 @@
 dictionary.  That behaviour is the reason why the following code raises an
 exception::
 
-   >>> class C(object):
+   >>> class C:
    ...     pass
    ...
    >>> c = C()

Modified: python/branches/pep-3151/Doc/reference/executionmodel.rst
==============================================================================
--- python/branches/pep-3151/Doc/reference/executionmodel.rst	(original)
+++ python/branches/pep-3151/Doc/reference/executionmodel.rst	Sat Feb 26 08:16:32 2011
@@ -141,9 +141,9 @@
 The namespace for a module is automatically created the first time a module is
 imported.  The main module for a script is always called :mod:`__main__`.
 
-The global statement has the same scope as a name binding operation in the same
-block.  If the nearest enclosing scope for a free variable contains a global
-statement, the free variable is treated as a global.
+The :keyword:`global` statement has the same scope as a name binding operation
+in the same block.  If the nearest enclosing scope for a free variable contains
+a global statement, the free variable is treated as a global.
 
 A class definition is an executable statement that may use and define names.
 These references follow the normal rules for name resolution.  The namespace of

Modified: python/branches/pep-3151/Doc/reference/expressions.rst
==============================================================================
--- python/branches/pep-3151/Doc/reference/expressions.rst	(original)
+++ python/branches/pep-3151/Doc/reference/expressions.rst	Sat Feb 26 08:16:32 2011
@@ -963,9 +963,9 @@
 
 .. _comparisons:
 .. _is:
-.. _isnot:
+.. _is not:
 .. _in:
-.. _notin:
+.. _not in:
 
 Comparisons
 ===========
@@ -1161,7 +1161,7 @@
 'foo'`` yields ``False``, not ``''``.)
 
 
-Conditional Expressions
+Conditional expressions
 =======================
 
 .. index::
@@ -1312,6 +1312,7 @@
 | ``(expressions...)``,                         | Binding or tuple display,           |
 | ``[expressions...]``,                         | list display,                       |
 | ``{key:datum...}``,                           | dictionary display,                 |
+| ``{expressions...}``                          | set display                         |
 +-----------------------------------------------+-------------------------------------+
 
 
@@ -1321,8 +1322,8 @@
    true numerically due to roundoff.  For example, and assuming a platform on which
    a Python float is an IEEE 754 double-precision number, in order that ``-1e-100 %
    1e100`` have the same sign as ``1e100``, the computed result is ``-1e-100 +
-   1e100``, which is numerically exactly equal to ``1e100``.  Function :func:`fmod`
-   in the :mod:`math` module returns a result whose sign matches the sign of the
+   1e100``, which is numerically exactly equal to ``1e100``.  The function
+   :func:`math.fmod` returns a result whose sign matches the sign of the
    first argument instead, and so returns ``-1e-100`` in this case. Which approach
    is more appropriate depends on the application.
 
@@ -1343,7 +1344,8 @@
    the :keyword:`is` operator, like those involving comparisons between instance
    methods, or constants.  Check their documentation for more info.
 
-.. [#] The ``%`` is also used for string formatting; the same precedence applies.
+.. [#] The ``%`` operator is also used for string formatting; the same
+   precedence applies.
 
 .. [#] The power operator ``**`` binds less tightly than an arithmetic or
    bitwise unary operator on its right, that is, ``2**-1`` is ``0.5``.

Modified: python/branches/pep-3151/Doc/reference/lexical_analysis.rst
==============================================================================
--- python/branches/pep-3151/Doc/reference/lexical_analysis.rst	(original)
+++ python/branches/pep-3151/Doc/reference/lexical_analysis.rst	Sat Feb 26 08:16:32 2011
@@ -292,9 +292,11 @@
 Identifiers are unlimited in length.  Case is significant.
 
 .. productionlist::
-   identifier: `id_start` `id_continue`*
+   identifier: `xid_start` `xid_continue`*
    id_start: <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>
    id_continue: <all characters in `id_start`, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
+   xid_start: <all characters in `id_start` whose NFKC normalization is in "id_start xid_continue*">
+   xid_continue: <all characters in `id_continue` whose NFKC normalization is in "id_continue*">
 
 The Unicode category codes mentioned above stand for:
 
@@ -308,9 +310,11 @@
 * *Mc* - spacing combining marks
 * *Nd* - decimal numbers
 * *Pc* - connector punctuations
+* *Other_ID_Start* - explicit list of characters in `PropList.txt <http://unicode.org/Public/UNIDATA/PropList.txt>`_ to support backwards compatibility
+* *Other_ID_Continue* - likewise
 
-All identifiers are converted into the normal form NFC while parsing; comparison
-of identifiers is based on NFC.
+All identifiers are converted into the normal form NFKC while parsing; comparison
+of identifiers is based on NFKC.
 
 A non-normative HTML file listing all valid identifier characters for Unicode
 4.1 can be found at

Modified: python/branches/pep-3151/Doc/reference/simple_stmts.rst
==============================================================================
--- python/branches/pep-3151/Doc/reference/simple_stmts.rst	(original)
+++ python/branches/pep-3151/Doc/reference/simple_stmts.rst	Sat Feb 26 08:16:32 2011
@@ -678,7 +678,7 @@
 for the module or package can begin. The first place checked is
 :data:`sys.modules`, the cache of all modules that have been imported
 previously. If the module is found there then it is used in step (2) of import
-unless :keyword:`None` is found in :data:`sys.modules`, in which case
+unless ``None`` is found in :data:`sys.modules`, in which case
 :exc:`ImportError` is raised.
 
 .. index::
@@ -696,7 +696,7 @@
 second argument to :meth:`find_module` is given as the value of the
 :attr:`__path__` attribute from the parent package (everything up to the last
 dot in the name of the module being imported). If a finder can find the module
-it returns a :term:`loader` (discussed later) or returns :keyword:`None`.
+it returns a :term:`loader` (discussed later) or returns ``None``.
 
 .. index::
     single: sys.path_hooks
@@ -723,11 +723,11 @@
 the list with a single argument of the path, returning a finder or raises
 :exc:`ImportError`. If a finder is returned then it is cached in
 :data:`sys.path_importer_cache` and then used for that path entry. If no finder
-can be found but the path exists then a value of :keyword:`None` is
+can be found but the path exists then a value of ``None`` is
 stored in :data:`sys.path_importer_cache` to signify that an implicit,
 file-based finder that handles modules stored as individual files should be
 used for that path. If the path does not exist then a finder which always
-returns :keyword:`None` is placed in the cache for the path.
+returns ``None`` is placed in the cache for the path.
 
 .. index::
     single: loader
@@ -791,7 +791,7 @@
 specifying ":keyword:`as` localname".  If a name is not found,
 :exc:`ImportError` is raised.  If the list of identifiers is replaced by a star
 (``'*'``), all public names defined in the module are bound in the local
-namespace of the :keyword:`import` statement..
+namespace of the :keyword:`import` statement.
 
 .. index:: single: __all__ (optional module attribute)
 

Modified: python/branches/pep-3151/Doc/tools/sphinxext/download.html
==============================================================================
--- python/branches/pep-3151/Doc/tools/sphinxext/download.html	(original)
+++ python/branches/pep-3151/Doc/tools/sphinxext/download.html	Sat Feb 26 08:16:32 2011
@@ -33,6 +33,10 @@
     <td><a href="{{ dlbase }}/python-{{ release }}-docs-text.zip">Download</a> (ca. 2 MB)</td>
     <td><a href="{{ dlbase }}/python-{{ release }}-docs-text.tar.bz2">Download</a> (ca. 1.5 MB)</td>
   </tr>
+ <tr><td>EPUB</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-epub.zip">Download</a> (ca. 3.5 MB)</td>
+    <td><a href="{{ dlbase }}/python-{{ release }}-docs-epub.tar.bz2">Download</a> (ca. 3.5 MB)</td>
+  </tr>
 </table>
 
 

Modified: python/branches/pep-3151/Doc/tools/sphinxext/indexcontent.html
==============================================================================
--- python/branches/pep-3151/Doc/tools/sphinxext/indexcontent.html	(original)
+++ python/branches/pep-3151/Doc/tools/sphinxext/indexcontent.html	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,7 @@
   <table class="contentstable" align="center"><tr>
     <td width="50%">
       <p class="biglink"><a class="biglink" href="{{ pathto("whatsnew/" + version) }}">What's new in Python {{ version }}?</a><br/>
-         <span class="linkdescr">or <a href="{{ pathto("whatsnew/index") }}">all "What's new" documents</a> since 2.0</span></span></p>
+         <span class="linkdescr">or <a href="{{ pathto("whatsnew/index") }}">all "What's new" documents</a> since 2.0</span></p>
       <p class="biglink"><a class="biglink" href="{{ pathto("tutorial/index") }}">Tutorial</a><br/>
          <span class="linkdescr">start here</span></p>
       <p class="biglink"><a class="biglink" href="{{ pathto("library/index") }}">Library Reference</a><br/>

Modified: python/branches/pep-3151/Doc/tools/sphinxext/indexsidebar.html
==============================================================================
--- python/branches/pep-3151/Doc/tools/sphinxext/indexsidebar.html	(original)
+++ python/branches/pep-3151/Doc/tools/sphinxext/indexsidebar.html	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,7 @@
 	    <h3>Docs for other versions</h3>
 	    <ul>
 	      <li><a href="http://docs.python.org/2.7/">Python 2.7 (stable)</a></li>
-	      <li><a href="http://docs.python.org/3.1/">Python 3.1 (stable)</a></li>
+	      <li><a href="http://docs.python.org/3.2/">Python 3.2 (stable)</a></li>
               <li><a href="http://www.python.org/doc/versions/">Old versions</a></li>
             </ul>
 

Modified: python/branches/pep-3151/Doc/tools/sphinxext/pyspecific.py
==============================================================================
--- python/branches/pep-3151/Doc/tools/sphinxext/pyspecific.py	(original)
+++ python/branches/pep-3151/Doc/tools/sphinxext/pyspecific.py	Sat Feb 26 08:16:32 2011
@@ -110,6 +110,41 @@
         return PyClassmember.run(self)
 
 
+# Support for documenting version of removal in deprecations
+
+from sphinx.locale import versionlabels
+from sphinx.util.compat import Directive
+
+versionlabels['deprecated-removed'] = \
+    'Deprecated since version %s, will be removed in version %s'
+
+class DeprecatedRemoved(Directive):
+    has_content = True
+    required_arguments = 2
+    optional_arguments = 1
+    final_argument_whitespace = True
+    option_spec = {}
+
+    def run(self):
+        node = addnodes.versionmodified()
+        node.document = self.state.document
+        node['type'] = 'deprecated-removed'
+        version = (self.arguments[0], self.arguments[1])
+        node['version'] = version
+        if len(self.arguments) == 3:
+            inodes, messages = self.state.inline_text(self.arguments[2],
+                                                      self.lineno+1)
+            node.extend(inodes)
+            if self.content:
+                self.state.nested_parse(self.content, self.content_offset, node)
+            ret = [node] + messages
+        else:
+            ret = [node]
+        env = self.state.document.settings.env
+        env.note_versionchange('deprecated', version[0], node, self.lineno)
+        return ret
+
+
 # Support for building "topic help" for pydoc
 
 pydoc_topic_labels = [
@@ -202,6 +237,8 @@
     return opname.strip()
 
 
+# Support for documenting pdb commands
+
 pdbcmd_sig_re = re.compile(r'([a-z()!]+)\s*(.*)')
 
 # later...
@@ -228,6 +265,7 @@
     app.add_role('issue', issue_role)
     app.add_role('source', source_role)
     app.add_directive('impl-detail', ImplementationDetail)
+    app.add_directive('deprecated-removed', DeprecatedRemoved)
     app.add_builder(PydocTopicsBuilder)
     app.add_builder(suspicious.CheckSuspiciousMarkupBuilder)
     app.add_description_unit('opcode', 'opcode', '%s (opcode)',

Modified: python/branches/pep-3151/Doc/tools/sphinxext/static/basic.css
==============================================================================
--- python/branches/pep-3151/Doc/tools/sphinxext/static/basic.css	(original)
+++ python/branches/pep-3151/Doc/tools/sphinxext/static/basic.css	Sat Feb 26 08:16:32 2011
@@ -253,8 +253,12 @@
 
 table.docutils td, table.docutils th {
     padding: 2px 5px 2px 5px;
-    border-left: 0;    
-    background-color: #eef;    
+    border-left: 0;
+    background-color: #eef;
+}
+
+table.docutils td p.last, table.docutils th p.last {
+    margin-bottom: 0;
 }
 
 table.field-list td, table.field-list th {
@@ -266,7 +270,7 @@
 }
 
 table.docutils th {
-    border-top: 1px solid #cac;    
+    border-top: 1px solid #cac;
     background-color: #ede;
 }
 
@@ -276,7 +280,7 @@
 }
 
 th.head {
-    text-align: center;    
+    text-align: center;
 }
 
 /* -- other body styles ----------------------------------------------------- */
@@ -329,7 +333,7 @@
     font-style: italic;
 }
 
-p.deprecated {
+p.deprecated, p.deprecated-removed {
     background-color: #ffe4e4;
     border: 1px solid #f66;
     padding: 7px
@@ -342,7 +346,7 @@
 }
 
 .footnote:target  {
-    background-color: #ffa
+    background-color: #ffa;
 }
 
 .impl-detail {
@@ -364,6 +368,7 @@
 
 pre {
     overflow: auto;
+    overflow-y: hidden;
 }
 
 td.linenos pre {

Modified: python/branches/pep-3151/Doc/tools/sphinxext/susp-ignored.csv
==============================================================================
--- python/branches/pep-3151/Doc/tools/sphinxext/susp-ignored.csv	(original)
+++ python/branches/pep-3151/Doc/tools/sphinxext/susp-ignored.csv	Sat Feb 26 08:16:32 2011
@@ -296,15 +296,15 @@
 library/bisect,32,:hi,all(val >= x for val in a[i:hi])
 library/bisect,42,:hi,all(val > x for val in a[i:hi])
 library/http.client,52,:port,host:port
-library/nntplib,272,:bytes,:bytes
-library/nntplib,272,:lines,:lines
-library/nntplib,272,:lines,"['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject']"
-library/nntplib,272,:bytes,"['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject']"
+library/nntplib,,:bytes,:bytes
+library/nntplib,,:lines,:lines
+library/nntplib,,:lines,"['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject']"
+library/nntplib,,:bytes,"['xref', 'from', ':lines', ':bytes', 'references', 'date', 'message-id', 'subject']"
 library/pickle,,:memory,"conn = sqlite3.connect("":memory:"")"
 library/profile,,:lineno,"(sort by filename:lineno),"
 library/socket,,::,"(10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]"
-library/stdtypes,1026,:end,s[start:end]
-library/stdtypes,1195,:end,s[start:end]
+library/stdtypes,,:end,s[start:end]
+library/stdtypes,,:end,s[start:end]
 library/urllib.request,,:close,Connection:close
 library/urllib.request,,:password,"""joe:password at python.org"""
 library/urllib.request,,:lang,"xmlns=""http://www.w3.org/1999/xhtml"" xml:lang=""en"" lang=""en"">\n\n<head>\n"
@@ -321,3 +321,68 @@
 whatsnew/2.7,862,:Cookie,"export PYTHONWARNINGS=all,error:::Cookie:0"
 whatsnew/2.7,1619,::,>>> urlparse.urlparse('http://[1080::8:800:200C:417A]/foo')
 whatsnew/2.7,1619,::,"ParseResult(scheme='http', netloc='[1080::8:800:200C:417A]',"
+library/configparser,,`,# Set the optional `raw` argument of get() to True if you wish to disable
+library/configparser,,`,# The optional `vars` argument is a dict with members that will take
+library/configparser,,`,# The optional `fallback` argument can be used to provide a fallback value
+library/configparser,,:option,${section:option}
+library/configparser,,:system,path: ${Common:system_dir}/Library/Frameworks/
+library/configparser,,:home,my_dir: ${Common:home_dir}/twosheds
+library/configparser,,:path,python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
+library/configparser,,:Python,python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
+library/pdb,,:lineno,[filename:lineno | bpnumber [bpnumber ...]]
+library/pdb,,:lineno,filename:lineno
+library/logging,,:Watch,WARNING:root:Watch out!
+library/logging,,:So,INFO:root:So should this
+library/logging,,:Started,INFO:root:Started
+library/logging,,:Doing,INFO:root:Doing something
+library/logging,,:Finished,INFO:root:Finished
+library/logging,,:Look,WARNING:root:Look before you leap!
+library/logging,,:So,INFO:So should this
+library/logging,,:logger,severity:logger name:message
+library/logging,,:message,severity:logger name:message
+whatsnew/3.2,,:directory,...   ${buildout:directory}/downloads/dist
+whatsnew/3.2,,:location,... zope9-location = ${zope9:location}
+whatsnew/3.2,,:prefix,... zope-conf = ${custom:prefix}/etc/zope.conf
+howto/logging,,:root,WARNING:root:Watch out!
+howto/logging,,:Watch,WARNING:root:Watch out!
+howto/logging,,:root,DEBUG:root:This message should go to the log file
+howto/logging,,:This,DEBUG:root:This message should go to the log file
+howto/logging,,:root,INFO:root:So should this
+howto/logging,,:So,INFO:root:So should this
+howto/logging,,:root,"WARNING:root:And this, too"
+howto/logging,,:And,"WARNING:root:And this, too"
+howto/logging,,:root,INFO:root:Started
+howto/logging,,:Started,INFO:root:Started
+howto/logging,,:root,INFO:root:Doing something
+howto/logging,,:Doing,INFO:root:Doing something
+howto/logging,,:root,INFO:root:Finished
+howto/logging,,:Finished,INFO:root:Finished
+howto/logging,,:root,WARNING:root:Look before you leap!
+howto/logging,,:Look,WARNING:root:Look before you leap!
+howto/logging,,:This,DEBUG:This message should appear on the console
+howto/logging,,:So,INFO:So should this
+howto/logging,,:And,"WARNING:And this, too"
+howto/logging,,:logger,severity:logger name:message
+howto/logging,,:message,severity:logger name:message
+library/logging.handlers,,:port,host:port
+documenting/markup,613,`,:ref:`link text <reference-label>`
+library/imaplib,116,:MM,"""DD-Mmm-YYYY HH:MM:SS"
+library/imaplib,116,:SS,"""DD-Mmm-YYYY HH:MM:SS"
+whatsnew/3.2,,::,"$ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'"
+howto/pyporting,75,::,# make sure to use :: Python *and* :: Python :: 3 so
+howto/pyporting,75,::,"'Programming Language :: Python',"
+howto/pyporting,75,::,'Programming Language :: Python :: 3'
+whatsnew/3.2,,:gz,">>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:"
+whatsnew/3.2,,:directory,${buildout:directory}/downloads/dist
+whatsnew/3.2,,:location,zope9-location = ${zope9:location}
+whatsnew/3.2,,:prefix,zope-conf = ${custom:prefix}/etc/zope.conf
+whatsnew/3.2,,:beef,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
+whatsnew/3.2,,:cafe,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
+whatsnew/3.2,,:affe,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
+whatsnew/3.2,,:deaf,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
+whatsnew/3.2,,:feed,>>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
+whatsnew/3.2,,:beef,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',"
+whatsnew/3.2,,:cafe,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',"
+whatsnew/3.2,,:affe,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',"
+whatsnew/3.2,,:deaf,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',"
+whatsnew/3.2,,:feed,"netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',"

Modified: python/branches/pep-3151/Doc/tutorial/inputoutput.rst
==============================================================================
--- python/branches/pep-3151/Doc/tutorial/inputoutput.rst	(original)
+++ python/branches/pep-3151/Doc/tutorial/inputoutput.rst	Sat Feb 26 08:16:32 2011
@@ -163,7 +163,7 @@
 
 An optional ``':'`` and format specifier can follow the field name. This allows
 greater control over how the value is formatted.  The following example
-truncates Pi to three places after the decimal.
+rounds Pi to three places after the decimal.
 
    >>> import math
    >>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))

Modified: python/branches/pep-3151/Doc/tutorial/interpreter.rst
==============================================================================
--- python/branches/pep-3151/Doc/tutorial/interpreter.rst	(original)
+++ python/branches/pep-3151/Doc/tutorial/interpreter.rst	Sat Feb 26 08:16:32 2011
@@ -10,11 +10,11 @@
 Invoking the Interpreter
 ========================
 
-The Python interpreter is usually installed as :file:`/usr/local/bin/python3.2`
+The Python interpreter is usually installed as :file:`/usr/local/bin/python3.3`
 on those machines where it is available; putting :file:`/usr/local/bin` in your
 Unix shell's search path makes it possible to start it by typing the command ::
 
-   python3.2
+   python3.3
 
 to the shell. [#]_ Since the choice of the directory where the interpreter lives
 is an installation option, other places are possible; check with your local
@@ -22,11 +22,11 @@
 popular alternative location.)
 
 On Windows machines, the Python installation is usually placed in
-:file:`C:\\Python32`, though you can change this when you're running the
+:file:`C:\\Python33`, 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::
 
-   set path=%path%;C:\python32
+   set path=%path%;C:\python33
 
 Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on
 Windows) at the primary prompt causes the interpreter to exit with a zero exit
@@ -58,14 +58,6 @@
 ``python -m module [arg] ...``, which executes the source file for *module* as
 if you had spelled out its full name on the command line.
 
-Note that there is a difference between ``python file`` and ``python
-<file``.  In the latter case, input requests from the program, such as calling
-``sys.stdin.read()``, are satisfied from *file*.  Since this file has already
-been read until the end by the parser before the program starts executing, the
-program will encounter end-of-file immediately.  In the former case (which is
-usually what you want) they are satisfied from whatever file or device is
-connected to standard input of the Python interpreter.
-
 When a script file is used, it is sometimes useful to be able to run the script
 and enter interactive mode afterwards.  This can be done by passing :option:`-i`
 before the script.  (This does not work if the script is read from standard
@@ -78,8 +70,9 @@
 ----------------
 
 When known to the interpreter, the script name and additional arguments
-thereafter are passed to the script in the variable ``sys.argv``, which is a
-list of strings.  Its length is at least one; when no script and no arguments
+thereafter are turned into a list of strings and assigned to the ``argv``
+variable in the ``sys`` module.  You can access this list by executing ``import
+sys``.  The length of the list is at least one; when no script and no arguments
 are given, ``sys.argv[0]`` is an empty string.  When the script name is given as
 ``'-'`` (meaning  standard input), ``sys.argv[0]`` is set to ``'-'``.  When
 :option:`-c` *command* is used, ``sys.argv[0]`` is set to ``'-c'``.  When
@@ -101,8 +94,8 @@
 prints a welcome message stating its version number and a copyright notice
 before printing the first prompt::
 
-   $ python3.2
-   Python 3.2 (py3k, Sep 12 2007, 12:21:02)
+   $ python3.3
+   Python 3.3 (py3k, Sep 12 2007, 12:21:02)
    [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>>
@@ -155,7 +148,7 @@
 On BSD'ish Unix systems, Python scripts can be made directly executable, like
 shell scripts, by putting the line ::
 
-   #! /usr/bin/env python3.2
+   #! /usr/bin/env python3.3
 
 (assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning
 of the script and giving the file an executable mode.  The ``#!`` must be the

Modified: python/branches/pep-3151/Doc/tutorial/introduction.rst
==============================================================================
--- python/branches/pep-3151/Doc/tutorial/introduction.rst	(original)
+++ python/branches/pep-3151/Doc/tutorial/introduction.rst	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,4 @@
-.. _tut-informal:
+.. _tut-informal:
 
 **********************************
 An Informal Introduction to Python
@@ -220,9 +220,10 @@
 
 Or, strings can be surrounded in a pair of matching triple-quotes: ``"""`` or
 ``'''``.  End of lines do not need to be escaped when using triple-quotes, but
-they will be included in the string. ::
+they will be included in the string.  So the following uses one escape to
+avoid an unwanted initial blank line.  ::
 
-   print("""
+   print("""\
    Usage: thingy [OPTIONS]
         -h                        Display this usage message
         -H hostname               Hostname to connect to
@@ -616,7 +617,7 @@
 
      >>> a, b = 0, 1
      >>> while b < 1000:
-     ...     print(b, end=' ')
+     ...     print(b, end=',')
      ...     a, b = b, a+b
      ...
-     1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
+     1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

Modified: python/branches/pep-3151/Doc/tutorial/stdlib.rst
==============================================================================
--- python/branches/pep-3151/Doc/tutorial/stdlib.rst	(original)
+++ python/branches/pep-3151/Doc/tutorial/stdlib.rst	Sat Feb 26 08:16:32 2011
@@ -14,11 +14,11 @@
 operating system::
 
    >>> import os
-   >>> os.system('time 0:02')
-   0
    >>> os.getcwd()      # Return the current working directory
-   'C:\\Python31'
-   >>> os.chdir('/server/accesslogs')
+   'C:\\Python33'
+   >>> os.chdir('/server/accesslogs')   # Change current working directory
+   >>> os.system('mkdir today')   # Run the command mkdir in the system shell
+   0
 
 Be sure to use the ``import os`` style instead of ``from os import *``.  This
 will keep :func:`os.open` from shadowing the built-in :func:`open` function which
@@ -207,14 +207,14 @@
 :mod:`tarfile`. ::
 
    >>> import zlib
-   >>> s = 'witch which has which witches wrist watch'
+   >>> s = b'witch which has which witches wrist watch'
    >>> len(s)
    41
    >>> t = zlib.compress(s)
    >>> len(t)
    37
    >>> zlib.decompress(t)
-   'witch which has which witches wrist watch'
+   b'witch which has which witches wrist watch'
    >>> zlib.crc32(s)
    226805979
 

Modified: python/branches/pep-3151/Doc/tutorial/stdlib2.rst
==============================================================================
--- python/branches/pep-3151/Doc/tutorial/stdlib2.rst	(original)
+++ python/branches/pep-3151/Doc/tutorial/stdlib2.rst	Sat Feb 26 08:16:32 2011
@@ -271,7 +271,7 @@
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
        d['primary']                # entry was automatically removed
-     File "C:/python31/lib/weakref.py", line 46, in __getitem__
+     File "C:/python33/lib/weakref.py", line 46, in __getitem__
        o = self.data[key]()
    KeyError: 'primary'
 

Modified: python/branches/pep-3151/Doc/using/cmdline.rst
==============================================================================
--- python/branches/pep-3151/Doc/using/cmdline.rst	(original)
+++ python/branches/pep-3151/Doc/using/cmdline.rst	Sat Feb 26 08:16:32 2011
@@ -220,6 +220,13 @@
    Discard docstrings in addition to the :option:`-O` optimizations.
 
 
+.. cmdoption:: -q
+
+   Don't display the copyright and version messages even in interactive mode.
+
+   .. versionadded:: 3.2
+
+
 .. cmdoption:: -s
 
    Don't add user site directory to sys.path

Modified: python/branches/pep-3151/Doc/whatsnew/2.0.rst
==============================================================================
--- python/branches/pep-3151/Doc/whatsnew/2.0.rst	(original)
+++ python/branches/pep-3151/Doc/whatsnew/2.0.rst	Sat Feb 26 08:16:32 2011
@@ -189,7 +189,7 @@
   ignored and ``'replace'`` uses U+FFFD, the official replacement character, in
   case of any problems.
 
-* The :keyword:`exec` statement, and various built-ins such as ``eval()``,
+* The ``exec`` statement, and various built-ins such as ``eval()``,
   ``getattr()``, and ``setattr()`` will also accept Unicode strings as well as
   regular strings.  (It's possible that the process of fixing this missed some
   built-ins; if you find a built-in function that accepts strings but doesn't
@@ -515,11 +515,11 @@
        # kw is a dictionary of keyword args
        ...
 
-The :keyword:`print` statement can now have its output directed to a file-like
-object by following the :keyword:`print` with  ``>> file``, similar to the
+The ``print`` statement can now have its output directed to a file-like
+object by following the ``print`` with  ``>> file``, similar to the
 redirection operator in Unix shells. Previously you'd either have to use the
 :meth:`write` method of the file-like object, which lacks the convenience and
-simplicity of :keyword:`print`, or you could assign a new value to
+simplicity of ``print``, or you could assign a new value to
 ``sys.stdout`` and then restore the old value.  For sending output to standard
 error, it's much easier to write this::
 
@@ -581,7 +581,7 @@
 An attempt has been made to alleviate one of Python's warts, the often-confusing
 :exc:`NameError` exception when code refers to a local variable before the
 variable has been assigned a value.  For example, the following code raises an
-exception on the :keyword:`print` statement in both 1.5.2 and 2.0; in 1.5.2 a
+exception on the ``print`` statement in both 1.5.2 and 2.0; in 1.5.2 a
 :exc:`NameError` exception is raised, while 2.0 raises a new
 :exc:`UnboundLocalError` exception. :exc:`UnboundLocalError` is a subclass of
 :exc:`NameError`, so any existing code that expects :exc:`NameError` to be

Modified: python/branches/pep-3151/Doc/whatsnew/2.1.rst
==============================================================================
--- python/branches/pep-3151/Doc/whatsnew/2.1.rst	(original)
+++ python/branches/pep-3151/Doc/whatsnew/2.1.rst	Sat Feb 26 08:16:32 2011
@@ -81,13 +81,13 @@
 place.
 
 One side effect of the change is that the ``from module import *`` and
-:keyword:`exec` statements have been made illegal inside a function scope under
+``exec`` statements have been made illegal inside a function scope under
 certain conditions.  The Python reference manual has said all along that ``from
 module import *`` is only legal at the top level of a module, but the CPython
 interpreter has never enforced this before.  As part of the implementation of
 nested scopes, the compiler which turns Python source into bytecodes has to
 generate different code to access variables in a containing scope.  ``from
-module import *`` and :keyword:`exec` make it impossible for the compiler to
+module import *`` and ``exec`` make it impossible for the compiler to
 figure this out, because they add names to the local namespace that are
 unknowable at compile time. Therefore, if a function contains function
 definitions or :keyword:`lambda` expressions with free variables, the compiler
@@ -102,11 +102,11 @@
        def g():
            return x
 
-Line 4 containing the :keyword:`exec` statement is a syntax error, since
-:keyword:`exec` would define a new local variable named ``x`` whose value should
+Line 4 containing the ``exec`` statement is a syntax error, since
+``exec`` would define a new local variable named ``x`` whose value should
 be accessed by :func:`g`.
 
-This shouldn't be much of a limitation, since :keyword:`exec` is rarely used in
+This shouldn't be much of a limitation, since ``exec`` is rarely used in
 most Python code (and when it is used, it's often a sign of a poor design
 anyway).
 

Modified: python/branches/pep-3151/Doc/whatsnew/2.2.rst
==============================================================================
--- python/branches/pep-3151/Doc/whatsnew/2.2.rst	(original)
+++ python/branches/pep-3151/Doc/whatsnew/2.2.rst	Sat Feb 26 08:16:32 2011
@@ -892,13 +892,13 @@
 place.
 
 One side effect of the change is that the ``from module import *`` and
-:keyword:`exec` statements have been made illegal inside a function scope under
+``exec`` statements have been made illegal inside a function scope under
 certain conditions.  The Python reference manual has said all along that ``from
 module import *`` is only legal at the top level of a module, but the CPython
 interpreter has never enforced this before.  As part of the implementation of
 nested scopes, the compiler which turns Python source into bytecodes has to
 generate different code to access variables in a containing scope.  ``from
-module import *`` and :keyword:`exec` make it impossible for the compiler to
+module import *`` and ``exec`` make it impossible for the compiler to
 figure this out, because they add names to the local namespace that are
 unknowable at compile time. Therefore, if a function contains function
 definitions or :keyword:`lambda` expressions with free variables, the compiler
@@ -913,11 +913,11 @@
        def g():
            return x
 
-Line 4 containing the :keyword:`exec` statement is a syntax error, since
-:keyword:`exec` would define a new local variable named ``x`` whose value should
+Line 4 containing the ``exec`` statement is a syntax error, since
+``exec`` would define a new local variable named ``x`` whose value should
 be accessed by :func:`g`.
 
-This shouldn't be much of a limitation, since :keyword:`exec` is rarely used in
+This shouldn't be much of a limitation, since ``exec`` is rarely used in
 most Python code (and when it is used, it's often a sign of a poor design
 anyway).
 

Modified: python/branches/pep-3151/Doc/whatsnew/2.4.rst
==============================================================================
--- python/branches/pep-3151/Doc/whatsnew/2.4.rst	(original)
+++ python/branches/pep-3151/Doc/whatsnew/2.4.rst	Sat Feb 26 08:16:32 2011
@@ -896,7 +896,7 @@
   (Contributed by Nick Coghlan.)
 
 * The :func:`eval(expr, globals, locals)` and :func:`execfile(filename, globals,
-  locals)` functions and the :keyword:`exec` statement now accept any mapping type
+  locals)` functions and the ``exec`` statement now accept any mapping type
   for the *locals* parameter.  Previously this had to be a regular Python
   dictionary.  (Contributed by Raymond Hettinger.)
 

Modified: python/branches/pep-3151/Doc/whatsnew/2.7.rst
==============================================================================
--- python/branches/pep-3151/Doc/whatsnew/2.7.rst	(original)
+++ python/branches/pep-3151/Doc/whatsnew/2.7.rst	Sat Feb 26 08:16:32 2011
@@ -246,7 +246,7 @@
 modules.
 
 * The :mod:`ConfigParser` module uses them by default, meaning that
-  configuration files can now read, modified, and then written back
+  configuration files can now be read, modified, and then written back
   in their original order.
 
 * The :meth:`~collections.somenamedtuple._asdict()` method for

Modified: python/branches/pep-3151/Doc/whatsnew/3.0.rst
==============================================================================
--- python/branches/pep-3151/Doc/whatsnew/3.0.rst	(original)
+++ python/branches/pep-3151/Doc/whatsnew/3.0.rst	Sat Feb 26 08:16:32 2011
@@ -96,9 +96,9 @@
 Print Is A Function
 -------------------
 
-The :keyword:`print` statement has been replaced with a :func:`print`
+The ``print`` statement has been replaced with a :func:`print`
 function, with keyword arguments to replace most of the special syntax
-of the old :keyword:`print` statement (:pep:`3105`).  Examples::
+of the old ``print`` statement (:pep:`3105`).  Examples::
 
   Old: print "The answer is", 2*2
   New: print("The answer is", 2*2)
@@ -126,7 +126,7 @@
 Note:
 
 * The :func:`print` function doesn't support the "softspace" feature of
-  the old :keyword:`print` statement.  For example, in Python 2.x,
+  the old ``print`` statement.  For example, in Python 2.x,
   ``print "A\n", "B"`` would write ``"A\nB\n"``; but in Python 3.0,
   ``print("A\n", "B")`` writes ``"A\n B\n"``.
 
@@ -135,7 +135,7 @@
   ``print(x)`` instead!
 
 * When using the ``2to3`` source-to-source conversion tool, all
-  :keyword:`print` statements are automatically converted to
+  ``print`` statements are automatically converted to
   :func:`print` function calls, so this is mostly a non-issue for
   larger projects.
 
@@ -178,7 +178,7 @@
   meaningful natural ordering.  Thus, expressions like ``1 < ''``, ``0
   > None`` or ``len <= len`` are no longer valid, and e.g. ``None <
   None`` raises :exc:`TypeError` instead of returning
-  :keyword:`False`.  A corollary is that sorting a heterogeneous list
+  ``False``.  A corollary is that sorting a heterogeneous list
   no longer makes sense -- all the elements must be comparable to each
   other.  Note that this does not apply to the ``==`` and ``!=``
   operators: objects of different incomparable types always compare
@@ -397,9 +397,8 @@
 * :keyword:`as` and :keyword:`with` are now reserved words.  (Since
   2.6, actually.)
 
-* :keyword:`True`, :keyword:`False`, and :keyword:`None` are reserved
-  words.  (2.6 partially enforced the restrictions on :keyword:`None`
-  already.)
+* ``True``, ``False``, and ``None`` are reserved words.  (2.6 partially enforced
+  the restrictions on ``None`` already.)
 
 * Change from :keyword:`except` *exc*, *var* to
   :keyword:`except` *exc* :keyword:`as` *var*.  See :pep:`3110`.
@@ -906,7 +905,7 @@
 
 It is not recommended to try to write source code that runs unchanged
 under both Python 2.6 and 3.0; you'd have to use a very contorted
-coding style, e.g. avoiding :keyword:`print` statements, metaclasses,
+coding style, e.g. avoiding ``print`` statements, metaclasses,
 and much more.  If you are maintaining a library that needs to support
 both Python 2.6 and Python 3.0, the best approach is to modify step 3
 above by editing the 2.6 version of the source code and running the

Modified: python/branches/pep-3151/Doc/whatsnew/3.2.rst
==============================================================================
--- python/branches/pep-3151/Doc/whatsnew/3.2.rst	(original)
+++ python/branches/pep-3151/Doc/whatsnew/3.2.rst	Sat Feb 26 08:16:32 2011
@@ -11,7 +11,10 @@
 
    * 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.
+   get rewritten.  (Note, during release candidate phase or just before
+   a beta release, please use the tracker instead -- this helps avoid
+   merge conflicts.   If you must add a suggested entry directly,
+   please put it in an XXX comment and the maintainer will take notice).
 
    * The maintainer will go through Misc/NEWS periodically and add
    changes; it's therefore more important to add your changes to
@@ -47,7 +50,129 @@
    This saves the maintainer the effort of going through the SVN log
    when researching a change.
 
-This article explains the new features in Python 3.2, compared to 3.1.
+This article explains the new features in Python 3.2 as compared to 3.1.  It
+focuses on a few highlights and gives a few examples.  For full details, see the
+:source:`Misc/NEWS <Misc/NEWS>` file.
+
+.. seealso::
+
+   :pep:`392` - Python 3.2 Release Schedule
+
+
+PEP 384: Defining a Stable ABI
+==============================
+
+In the past, extension modules built for one Python version were often
+not usable with other Python versions. Particularly on Windows, every
+feature release of Python required rebuilding all extension modules that
+one wanted to use. This requirement was the result of the free access to
+Python interpreter internals that extension modules could use.
+
+With Python 3.2, an alternative approach becomes available: extension
+modules which restrict themselves to a limited API (by defining
+Py_LIMITED_API) cannot use many of the internals, but are constrained
+to a set of API functions that are promised to be stable for several
+releases. As a consequence, extension modules built for 3.2 in that
+mode will also work with 3.3, 3.4, and so on. Extension modules that
+make use of details of memory structures can still be built, but will
+need to be recompiled for every feature release.
+
+.. seealso::
+
+   :pep:`384` - Defining a Stable ABI
+      PEP written by Martin von Löwis.
+
+
+PEP 389: Argparse Command Line Parsing Module
+=============================================
+
+A new module for command line parsing, :mod:`argparse`, was introduced to
+overcome the limitations of :mod:`optparse` which did not provide support for
+positional arguments (not just options), subcommands, required options and other
+common patterns of specifying and validating options.
+
+This module has already had widespread success in the community as a
+third-party module.  Being more fully featured than its predecessor, the
+:mod:`argparse` module is now the preferred module for command-line processing.
+The older module is still being kept available because of the substantial amount
+of legacy code that depends on it.
+
+Here's an annotated example parser showing features like limiting results to a
+set of choices, specifying a *metavar* in the help screen, validating that one
+or more positional arguments is present, and making a required option::
+
+    import argparse
+    parser = argparse.ArgumentParser(
+                description = 'Manage servers',         # main description for help
+                epilog = 'Tested on Solaris and Linux') # displayed after help
+    parser.add_argument('action',                       # argument name
+                choices = ['deploy', 'start', 'stop'],  # three allowed values
+                help = 'action on each target')         # help msg
+    parser.add_argument('targets',
+                metavar = 'HOSTNAME',                   # var name used in help msg
+                nargs = '+',                            # require one or more targets
+                help = 'url for target machines')       # help msg explanation
+    parser.add_argument('-u', '--user',                 # -u or --user option
+                required = True,                        # make it a required argument
+                help = 'login as user')
+
+Example of calling the parser on a command string::
+
+    >>> cmd  = 'deploy sneezy.example.com sleepy.example.com -u skycaptain'
+    >>> result = parser.parse_args(cmd.split())
+    >>> result.action
+    'deploy'
+    >>> result.targets
+    ['sneezy.example.com', 'sleepy.example.com']
+    >>> result.user
+    'skycaptain'
+
+Example of the parser's automatically generated help::
+
+    >>> parser.parse_args('-h'.split())
+
+    usage: manage_cloud.py [-h] -u USER
+                           {deploy,start,stop} HOSTNAME [HOSTNAME ...]
+
+    Manage servers
+
+    positional arguments:
+      {deploy,start,stop}   action on each target
+      HOSTNAME              url for target machines
+
+    optional arguments:
+      -h, --help            show this help message and exit
+      -u USER, --user USER  login as user
+
+    Tested on Solaris and Linux
+
+An especially nice :mod:`argparse` feature is the ability to define subparsers,
+each with their own argument patterns and help displays::
+
+    import argparse
+    parser = argparse.ArgumentParser(prog='HELM')
+    subparsers = parser.add_subparsers()
+
+    parser_l = subparsers.add_parser('launch', help='Launch Control')   # first subgroup
+    parser_l.add_argument('-m', '--missiles', action='store_true')
+    parser_l.add_argument('-t', '--torpedos', action='store_true')
+
+    parser_m = subparsers.add_parser('move', help='Move Vessel',        # second subgroup
+                                     aliases=('steer', 'turn'))         # equivalent names
+    parser_m.add_argument('-c', '--course', type=int, required=True)
+    parser_m.add_argument('-s', '--speed', type=int, default=0)
+
+    $ ./helm.py --help                         # top level help (launch and move)
+    $ ./helm.py launch --help                  # help for launch options
+    $ ./helm.py launch --missiles              # set missiles=True and torpedos=False
+    $ ./helm.py steer --course 180 --speed 5   # set movement parameters
+
+.. seealso::
+
+   :pep:`389` - New Command Line Parsing Module
+      PEP written by Steven Bethard.
+
+   :ref:`upgrading-optparse-code` for details on the differences from :mod:`optparse`.
 
 
 PEP 391:  Dictionary Based Configuration for Logging
@@ -68,7 +193,7 @@
 
    {"version": 1,
     "formatters": {"brief": {"format": "%(levelname)-8s: %(name)-15s: %(message)s"},
-                   "full": {"format": "%(asctime)s %(name)-15s %(levelname)-8s %(message)s"},
+                   "full": {"format": "%(asctime)s %(name)-15s %(levelname)-8s %(message)s"}
                    },
     "handlers": {"console": {
                       "class": "logging.StreamHandler",
@@ -79,18 +204,22 @@
                       "class": "logging.StreamHandler",
                       "formatter": "full",
                       "level": "ERROR",
-                      "stream": "ext://sys.stderr"},
+                      "stream": "ext://sys.stderr"}
                  },
     "root": {"level": "DEBUG", "handlers": ["console", "console_priority"]}}
 
 
-If that dictionary is stored in a file called "conf.json", it can loaded
-and called with code like this::
+If that dictionary is stored in a file called :file:`conf.json`, it can be
+loaded and called with code like this::
 
-   >>> import logging.config
-   >>> logging.config.dictConfig(json.load(open('conf.json', 'rb')))
+   >>> import json, logging.config
+   >>> with open('conf.json') as f:
+           conf = json.load(f)
+   >>> logging.config.dictConfig(conf)
    >>> logging.info("Transaction completed normally")
+   INFO    : root           : Transaction completed normally
    >>> logging.critical("Abnormal termination")
+   2011-02-17 11:14:36,694 root            CRITICAL Abnormal termination
 
 .. seealso::
 
@@ -98,11 +227,69 @@
       PEP written by Vinay Sajip.
 
 
+PEP 3148:  The ``concurrent.futures`` module
+============================================
+
+Code for creating and managing concurrency is being collected in a new top-level
+namespace, *concurrent*.  Its first member is a *futures* package which provides
+a uniform high-level interface for managing threads and processes.
+
+The design for :mod:`concurrent.futures` was inspired by
+*java.util.concurrent.package*.  In that model, a running call and its result
+are represented by a :class:`~concurrent.futures.Future` object that abstracts
+features common to threads, processes, and remote procedure calls.  That object
+supports status checks (running or done), timeouts, cancellations, adding
+callbacks, and access to results or exceptions.
+
+The primary offering of the new module is a pair of executor classes for
+launching and managing calls.  The goal of the executors is to make it easier to
+use existing tools for making parallel calls. They save the effort needed to
+setup a pool of resources, launch the calls, create a results queue, add
+time-out handling, and limit the total number of threads, processes, or remote
+procedure calls.
+
+Ideally, each application should share a single executor across multiple
+components so that process and thread limits can be centrally managed.  This
+solves the design challenge that arises when each component has its own
+competing strategy for resource management.
+
+Both classes share a common interface with three methods:
+:meth:`~concurrent.futures.Executor.submit` for scheduling a callable and
+returning a :class:`~concurrent.futures.Future` object;
+:meth:`~concurrent.futures.Executor.map` for scheduling many asynchronous calls
+at a time, and :meth:`~concurrent.futures.Executor.shutdown` for freeing
+resources.  The class is a :term:`context manager` and can be used in a
+:keyword:`with` statement to assure that resources are automatically released
+when currently pending futures are done executing.
+
+A simple of example of :class:`~concurrent.futures.ThreadPoolExecutor` is a
+launch of four parallel threads for copying files::
+
+  import concurrent.futures, shutil
+  with concurrent.futures.ThreadPoolExecutor(max_workers=4) as e:
+      e.submit(shutil.copy, 'src1.txt', 'dest1.txt')
+      e.submit(shutil.copy, 'src2.txt', 'dest2.txt')
+      e.submit(shutil.copy, 'src3.txt', 'dest3.txt')
+      e.submit(shutil.copy, 'src3.txt', 'dest4.txt')
+
+.. seealso::
+
+   :pep:`3148` - Futures -- Execute Computations Asynchronously
+      PEP written by Brian Quinlan.
+
+   :ref:`Code for Threaded Parallel URL reads<threadpoolexecutor-example>`, an
+   example using threads to fetch multiple web pages in parallel.
+
+   :ref:`Code for computing prime numbers in
+   parallel<processpoolexecutor-example>`, an example demonstrating
+   :class:`~concurrent.futures.ProcessPoolExecutor`.
+
+
 PEP 3147:  PYC Repository Directories
 =====================================
 
 Python's scheme for caching bytecode in *.pyc* files did not work well in
-environments with multiple python interpreters.  If one interpreter encountered
+environments with multiple Python interpreters.  If one interpreter encountered
 a cached file created by another interpreter, it would recompile the source and
 overwrite the cached file, thus losing the benefits of caching.
 
@@ -145,7 +332,17 @@
   'c:/py32/lib/__pycache__/collections.cpython-32.pyc'
 
 * The :mod:`py_compile` and :mod:`compileall` modules have been updated to
-  reflect the new naming convention and target directory.
+  reflect the new naming convention and target directory.  The command-line
+  invocation of *compileall* has new options: ``-i`` for
+  specifying a list of files and directories to compile and ``-b`` which causes
+  bytecode files to be written to their legacy location rather than
+  *__pycache__*.
+
+* The :mod:`importlib.abc` module has been updated with new :term:`abstract base
+  classes <abstract base class>` for loading bytecode files.  The obsolete
+  ABCs, :class:`~importlib.abc.PyLoader` and
+  :class:`~importlib.abc.PyPycLoader`, have been deprecated (instructions on how
+  to stay Python 3.1 compatible are included with the documentation).
 
 .. seealso::
 
@@ -153,8 +350,8 @@
       PEP written by Barry Warsaw.
 
 
-PEP 3149 ABI Version Tagged .so Files
-=====================================
+PEP 3149: ABI Version Tagged .so Files
+======================================
 
 The PYC repository directory allows multiple bytecode cache files to be
 co-located.  This PEP implements a similar mechanism for shared object files by
@@ -176,7 +373,7 @@
    >>> sysconfig.get_config_var('SOABI')    # find the version tag
    'cpython-32mu'
    >>> sysconfig.get_config_var('SO')       # find the full filename extension
-   'cpython-32mu.so'
+   '.cpython-32mu.so'
 
 .. seealso::
 
@@ -184,32 +381,51 @@
       PEP written by Barry Warsaw.
 
 
-Email 5.1
-=========
-
-The email package is extended to be able to parse and generate email messages
-in bytes format.
+PEP 3333: Python Web Server Gateway Interface v1.0.1
+=====================================================
 
-* New functions :func:`~email.message_from_bytes` and
-  :func:`~email.message_from_binary_file`, and new classes
-  :class:`~email.parser.BytesFeedParser` and :class:`~email.parser.BytesParser`
-  allow binary message data to be parsed into model objects.
+This informational PEP clarifies how bytes/text issues are to be handled by the
+WGSI protocol.  The challenge is that string handling in Python 3 is most
+conveniently handled with the :class:`str` type even though the HTTP protocol
+is itself bytes oriented.
+
+The PEP differentiates so-called *native strings* that are used for
+request/response headers and metadata versus *byte strings* which are used for
+the bodies of requests and responses.
+
+The *native strings* are always of type :class:`str` but are restricted to code
+points between *U+0000* through *U+00FF* which are translatable to bytes using
+*Latin-1* encoding.  These strings are used for the keys and values in the
+environment dictionary and for response headers and statuses in the
+:func:`start_response` function.  They must follow :rfc:`2616` with respect to
+encoding. That is, they must either be *ISO-8859-1* characters or use
+:rfc:`2047` MIME encoding.
+
+For developers porting WSGI applications from Python 2, here are the salient
+points:
+
+* If the app already used strings for headers in Python 2, no change is needed.
+
+* If instead, the app encoded output headers or decoded input headers, then the
+  headers will need to be re-encoded to Latin-1.  For example, an output header
+  encoded in utf-8 was using ``h.encode('utf-8')`` now needs to convert from
+  bytes to native strings using ``h.encode('utf-8').decode('latin-1')``.
+
+* Values yielded by an application or sent using the :meth:`write` method
+  must be byte strings.  The :func:`start_response` function and environ
+  must use native strings.  The two cannot be mixed.
+
+For server implementers writing CGI-to-WSGI pathways or other CGI-style
+protocols, the users must to be able access the environment using native strings
+even though the underlying platform may have a different convention.  To bridge
+this gap, the :mod:`wsgiref` module has a new function,
+:func:`wsgiref.handlers.read_environ` for transcoding CGI variables from
+:attr:`os.environ` into native strings and returning a new dictionary.
 
-* Given bytes input to the model, :meth:`~email.message.Message.get_payload`
-  will by default decode a message body that has a
-  :mailheader:`Content-Transfer-Encoding` of ``8bit`` using the charset
-  specified in the MIME headers and return the resulting string.
-
-* Given bytes input to the model, :class:`~email.generator.Generator` will
-  convert message bodies that have a :mailheader:`Content-Transfer-Encoding` of
-  8bit to instead have a 7bit Content-Transfer-Encoding.
-
-* New class :class:`~email.generator.BytesGenerator` produces bytes
-  as output, preserving any unchanged non-ASCII data that was
-  present in the input used to build the model, including message bodies
-  with a :mailheader:`Content-Transfer-Encoding` of 8bit.
+.. seealso::
 
-  (Proposed and implemented by R. David Murray, :issue:`4661`.)
+   :pep:`3333` - Python Web Server Gateway Interface v1.0.1
+      PEP written by Phillip Eby.
 
 
 Other Language Changes
@@ -217,13 +433,80 @@
 
 Some smaller changes made to the core Python language are:
 
-* The :func:`hasattr` function used to catch and suppress any Exception.  Now,
-  it only catches :exc:`AttributeError`.  Under the hood, :func:`hasattr` works
-  by calling :func:`getattr` and throwing away the results.  This is necessary
-  because dynamic attribute creation is possible using :meth:`__getattribute__`
-  or :meth:`__getattr__`.  If :func:`hasattr` were to just scan instance and class
-  dictionaries it would miss the dynamic methods and make it difficult to
-  implement proxy objects.
+* String formatting for :func:`format` and :meth:`str.format` gained new
+  capabilities for the format character **#**.  Previously, for integers in
+  binary, octal, or hexadecimal, it caused the output to be prefixed with '0b',
+  '0o', or '0x' respectively.  Now it can also handle floats, complex, and
+  Decimal, causing the output to always have a decimal point even when no digits
+  follow it.
+
+  >>> format(20, '#o')
+  '0o24'
+  >>> format(12.34, '#5.0f')
+  '  12.'
+
+  (Suggested by Mark Dickinson and implemented by Eric Smith in :issue:`7094`.)
+
+* There is also a new :meth:`str.format_map` method that extends the
+  capabilities of the existing :meth:`str.format` method by accepting arbitrary
+  :term:`mapping` objects.  This new method makes it possible to use string
+  formatting with any of Python's many dictionary-like objects such as
+  :class:`~collections.defaultdict`, :class:`~shelve.Shelf`,
+  :class:`~configparser.ConfigParser`, or :mod:`dbm`.  It is also useful with
+  custom :class:`dict` subclasses that normalize keys before look-up or that
+  supply a :meth:`__missing__` method for unknown keys::
+
+    >>> import shelve
+    >>> d = shelve.open('tmp.shl')
+    >>> 'The {project_name} status is {status} as of {date}'.format_map(d)
+    'The testing project status is green as of February 15, 2011'
+
+    >>> class LowerCasedDict(dict):
+            def __getitem__(self, key):
+                return dict.__getitem__(self, key.lower())
+    >>> lcd = LowerCasedDict(part='widgets', quantity=10)
+    >>> 'There are {QUANTITY} {Part} in stock'.format_map(lcd)
+    'There are 10 widgets in stock'
+
+    >>> class PlaceholderDict(dict):
+            def __missing__(self, key):
+                return '<{}>'.format(key)
+    >>> 'Hello {name}, welcome to {location}'.format_map(PlaceholderDict())
+    'Hello <name>, welcome to <location>'
+
+ (Suggested by Raymond Hettinger and implemented by Eric Smith in
+ :issue:`6081`.)
+
+* The interpreter can now be started with a quiet option, ``-q``, to prevent
+  the copyright and version information from being displayed in the interactive
+  mode.  The option can be introspected using the :attr:`sys.flags` attribute::
+
+    $ python -q
+    >>> sys.flags
+    sys.flags(debug=0, division_warning=0, inspect=0, interactive=0,
+    optimize=0, dont_write_bytecode=0, no_user_site=0, no_site=0,
+    ignore_environment=0, verbose=0, bytes_warning=0, quiet=1)
+
+  (Contributed by Marcin Wojdyr in :issue:`1772833`).
+
+* The :func:`hasattr` function works by calling :func:`getattr` and detecting
+  whether an exception is raised.  This technique allows it to detect methods
+  created dynamically by :meth:`__getattr__` or :meth:`__getattribute__` which
+  would otherwise be absent from the class dictionary.  Formerly, *hasattr*
+  would catch any exception, possibly masking genuine errors.  Now, *hasattr*
+  has been tightened to only catch :exc:`AttributeError` and let other
+  exceptions pass through::
+
+    >>> class A:
+            @property
+            def f(self):
+                return 1 // 0
+
+    >>> a = A()
+    >>> hasattr(a, 'f')
+    Traceback (most recent call last):
+      ...
+    ZeroDivisionError: integer division or modulo by zero
 
   (Discovered by Yury Selivanov and fixed by Benjamin Peterson; :issue:`9666`.)
 
@@ -232,6 +515,7 @@
   caused confusion and is no longer needed now that the shortest possible
   :func:`repr` is displayed by default:
 
+   >>> import math
    >>> repr(math.pi)
    '3.141592653589793'
    >>> str(math.pi)
@@ -239,108 +523,257 @@
 
   (Proposed and implemented by Mark Dickinson; :issue:`9337`.)
 
-* :class:`memoryview` objects now have a :meth:`release()` method and support
-  the context manager protocol.  This allows timely release of any resources
-  that were acquired when requesting a buffer from the original object.
+* :class:`memoryview` objects now have a :meth:`~memoryview.release()` method
+  and they also now support the context manager protocol.  This allows timely
+  release of any resources that were acquired when requesting a buffer from the
+  original object.
+
+  >>> with memoryview(b'abcdefgh') as v:
+          print(v.tolist())
+  [97, 98, 99, 100, 101, 102, 103, 104]
 
   (Added by Antoine Pitrou; :issue:`9757`.)
 
-* Mark Dickinson crafted an elegant and efficient scheme for assuring that
-  different numeric datatypes will have the same hash value whenever their
-  actual values are equal::
-
-   >>> assert hash(Fraction(3, 2)) == hash(1.5) == \
-              hash(Decimal("1.5")) == hash(complex(1.5, 0))
-
-  (See :issue:`8188`.)
-
 * Previously it was illegal to delete a name from the local namespace if it
   occurs as a free variable in a nested block::
 
-   >>> def outer(x):
-   ...     def inner():
-   ...        return x
-   ...     inner()
-   ...     del x
+       def outer(x):
+           def inner():
+              return x
+           inner()
+           del x
 
   This is now allowed.  Remember that the target of an :keyword:`except` clause
   is cleared, so this code which used to work with Python 2.6, raised a
   :exc:`SyntaxError` with Python 3.1 and now works again::
 
-   >>> def f():
-   ...     def print_error():
-   ...        print(e)
-   ...     try:
-   ...        something
-   ...     except Exception as e:
-   ...        print_error()
-   ...        # implicit "del e" here
+       def f():
+           def print_error():
+              print(e)
+           try:
+              something
+           except Exception as e:
+              print_error()
+              # implicit "del e" here
 
   (See :issue:`4617`.)
 
+* The internal :c:type:`structsequence` tool now creates subclasses of tuple.
+  This means that C structures like those returned by :func:`os.stat`,
+  :func:`time.gmtime`, and :attr:`sys.version_info` now work like a
+  :term:`named tuple` and now work with functions and methods that
+  expect a tuple as an argument.  This is a big step forward in making the C
+  structures as flexible as their pure Python counterparts:
+
+  >>> isinstance(sys.version_info, tuple)
+  True
+  >>> 'Version %d.%d.%d %s(%d)' % sys.version_info
+  'Version 3.2.0 final(0)'
+
+  (Suggested by Arfrever Frehtes Taifersar Arahesis and implemented
+  by Benjamin Peterson in :issue:`8413`.)
+
+* Warnings are now easier to control using the :envvar:`PYTHONWARNINGS`
+  environment variable as an alternative to using ``-W`` at the command line::
+
+    $ export PYTHONWARNINGS='ignore::RuntimeWarning::,once::UnicodeWarning::'
+
+  (Suggested by Barry Warsaw and implemented by Philip Jenvey in :issue:`7301`.)
+
 * A new warning category, :exc:`ResourceWarning`, has been added.  It is
-  emitted when certain potential issues with resource consumption or cleanup
-  are detected.  It is silenced by default in normal release builds, but
-  can be easily enabled through the means provided by the :mod:`warnings`
+  emitted when potential issues with resource consumption or cleanup
+  are detected.  It is silenced by default in normal release builds but
+  can be enabled through the means provided by the :mod:`warnings`
   module, or on the command line.
 
-  :exc:`ResourceWarning` is issued at interpreter shutdown if the
-  :data:`gc.garbage` list isn't empty.  This is meant to make the programmer
-  aware that their code contains object finalization issues.
-
-  (Added by Antoine Pitrou and Georg Brandl; :issue:`477863`.)
+  A :exc:`ResourceWarning` is issued at interpreter shutdown if the
+  :data:`gc.garbage` list isn't empty, and if :attr:`gc.DEBUG_UNCOLLECTABLE` is
+  set, all uncollectable objects are printed.  This is meant to make the
+  programmer aware that their code contains object finalization issues.
 
-  :exc:`ResourceWarning` is also issued when a :term:`file object` is destroyed
+  A :exc:`ResourceWarning` is also issued when a :term:`file object` is destroyed
   without having been explicitly closed.  While the deallocator for such
   object ensures it closes the underlying operating system resource
   (usually, a file descriptor), the delay in deallocating the object could
   produce various issues, especially under Windows.  Here is an example
   of enabling the warning from the command line::
 
-      $ ./python -Wdefault
-      Python 3.2a3+ (py3k, Nov  5 2010, 22:58:04)
-      [GCC 4.4.3] on linux2
-      Type "help", "copyright", "credits" or "license" for more information.
+      $ python -q -Wdefault
       >>> f = open("foo", "wb")
       >>> del f
       __main__:1: ResourceWarning: unclosed file <_io.BufferedWriter name='foo'>
-      >>>
 
-  (Added by Antoine Pitrou, :issue:`10093`.)
+  (Added by Antoine Pitrou and Georg Brandl in :issue:`10093` and :issue:`477863`.)
+
+* :class:`range` objects now support *index* and *count* methods. This is part
+  of an effort to make more objects fully implement the
+  :class:`collections.Sequence` :term:`abstract base class`.  As a result, the
+  language will have a more uniform API.  In addition, :class:`range` objects
+  now support slicing and negative indices, even with values larger than
+  :attr:`sys.maxsize`.  This makes *range* more interoperable with lists::
+
+      >>> range(0, 100, 2).count(10)
+      1
+      >>> range(0, 100, 2).index(10)
+      5
+      >>> range(0, 100, 2)[5]
+      10
+      >>> range(0, 100, 2)[0:5]
+      range(0, 10, 2)
+
+  (Contributed by Daniel Stutzbach in :issue:`9213`, by Alexander Belopolsky
+  in :issue:`2690`, and by Nick Coghlan in :issue:`10889`.)
+
+* The :func:`callable` builtin function from Py2.x was resurrected.  It provides
+  a concise, readable alternative to using an :term:`abstract base class` in an
+  expression like ``isinstance(x, collections.Callable)``:
+
+  >>> callable(max)
+  True
+  >>> callable(20)
+  False
+
+  (See :issue:`10518`.)
+
+* Python's import mechanism can now load modules installed in directories with
+  non-ASCII characters in the path name.  This solved an aggravating problem
+  with home directories for users with non-ASCII characters in their usernames.
+
+ (Required extensive work by Victor Stinner in :issue:`9425`.)
 
 
 New, Improved, and Deprecated Modules
 =====================================
 
-* XXX mention :mod:`argparse`.
+Python's standard library has undergone significant maintenance efforts and
+quality improvements.
+
+The biggest news for Python 3.2 is that the :mod:`email` package, :mod:`mailbox`
+module, and :mod:`nntplib` modules now work correctly with the bytes/text model
+in Python 3.  For the first time, there is correct handling of messages with
+mixed encodings.
+
+Throughout the standard library, there has been more careful attention to
+encodings and text versus bytes issues.  In particular, interactions with the
+operating system are now better able to exchange non-ASCII data using the
+Windows MBCS encoding, locale-aware encodings, or UTF-8.
+
+Another significant win is the addition of substantially better support for
+*SSL* connections and security certificates.
+
+In addition, more classes now implement a :term:`context manager` to support
+convenient and reliable resource clean-up using a :keyword:`with` statement.
+
+email
+-----
+
+The usability of the :mod:`email` package in Python 3 has been mostly fixed by
+the extensive efforts of R. David Murray.  The problem was that emails are
+typically read and stored in the form of :class:`bytes` rather than :class:`str`
+text, and they may contain multiple encodings within a single email.  So, the
+email package had to be extended to parse and generate email messages in bytes
+format.
+
+* New functions :func:`~email.message_from_bytes` and
+  :func:`~email.message_from_binary_file`, and new classes
+  :class:`~email.parser.BytesFeedParser` and :class:`~email.parser.BytesParser`
+  allow binary message data to be parsed into model objects.
+
+* Given bytes input to the model, :meth:`~email.message.Message.get_payload`
+  will by default decode a message body that has a
+  :mailheader:`Content-Transfer-Encoding` of *8bit* using the charset
+  specified in the MIME headers and return the resulting string.
+
+* Given bytes input to the model, :class:`~email.generator.Generator` will
+  convert message bodies that have a :mailheader:`Content-Transfer-Encoding` of
+  *8bit* to instead have a *7bit* :mailheader:`Content-Transfer-Encoding`.
+
+  Headers with unencoded non-ASCII bytes are deemed to be :rfc:`2047`\ -encoded
+  using the *unknown-8bit* character set.
+
+* A new class :class:`~email.generator.BytesGenerator` produces bytes as output,
+  preserving any unchanged non-ASCII data that was present in the input used to
+  build the model, including message bodies with a
+  :mailheader:`Content-Transfer-Encoding` of *8bit*.
+
+* The :mod:`smtplib` :class:`~smtplib.SMTP` class now accepts a byte string
+  for the *msg* argument to the :meth:`~smtplib.SMTP.sendmail` method,
+  and a new method, :meth:`~smtplib.SMTP.send_message` accepts a
+  :class:`~email.message.Message` object and can optionally obtain the
+  *from_addr* and *to_addrs* addresses directly from the object.
+
+(Proposed and implemented by R. David Murray, :issue:`4661` and :issue:`10321`.)
+
+elementtree
+-----------
+
+The :mod:`xml.etree.ElementTree` package and its :mod:`xml.etree.cElementTree`
+counterpart have been updated to version 1.3.
+
+Several new and useful functions and methods have been added:
+
+* :func:`xml.etree.ElementTree.fromstringlist` which builds an XML document
+  from a sequence of fragments
+* :func:`xml.etree.ElementTree.register_namespace` for registering a global
+  namespace prefix
+* :func:`xml.etree.ElementTree.tostringlist` for string representation
+  including all sublists
+* :meth:`xml.etree.ElementTree.Element.extend` for appending a sequence of zero
+  or more elements
+* :meth:`xml.etree.ElementTree.Element.iterfind` searches an element and
+  subelements
+* :meth:`xml.etree.ElementTree.Element.itertext` creates a text iterator over
+  an element and its subelements
+* :meth:`xml.etree.ElementTree.TreeBuilder.end` closes the current element
+* :meth:`xml.etree.ElementTree.TreeBuilder.doctype` handles a doctype
+  declaration
+
+Two methods have been deprecated:
+
+* :meth:`xml.etree.ElementTree.getchildren` use ``list(elem)`` instead.
+* :meth:`xml.etree.ElementTree.getiterator` use ``Element.iter`` instead.
+
+For details of the update, see `Introducing ElementTree
+<http://effbot.org/zone/elementtree-13-intro.htm>`_ on Fredrik Lundh's website.
+
+(Contributed by Florent Xicluna and Fredrik Lundh, :issue:`6472`.)
+
+functools
+---------
 
 * The :mod:`functools` module includes a new decorator for caching function
   calls.  :func:`functools.lru_cache` can save repeated queries to an external
   resource whenever the results are expected to be the same.
 
   For example, adding a caching decorator to a database query function can save
-  database accesses for popular searches::
+  database accesses for popular searches:
+
+  >>> import functools
+  >>> @functools.lru_cache(maxsize=300)
+  >>> def get_phone_number(name):
+          c = conn.cursor()
+          c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
+          return c.fetchone()[0]
 
-     @functools.lru_cache(maxsize=300)
-     def get_phone_number(name):
-         c = conn.cursor()
-         c.execute('SELECT phonenumber FROM phonelist WHERE name=?', (name,))
-         return c.fetchone()[0]
+  >>> for name in user_requests:
+          get_phone_number(name)        # cached lookup
 
   To help with choosing an effective cache size, the wrapped function is
-  instrumented with two attributes *cache_hits* and *cache_misses*:
+  instrumented for tracking cache statistics:
 
-  >>> for name in user_requests:
-  ...     get_phone_number(name)
-  >>> print(get_phone_number.cache_hits, get_phone_number.cache_misses)
-  4805 980
+  >>> get_phone_number.cache_info()
+  CacheInfo(hits=4805, misses=980, maxsize=300, currsize=300)
 
   If the phonelist table gets updated, the outdated contents of the cache can be
   cleared with:
 
   >>> get_phone_number.cache_clear()
 
-  (Contributed by Raymond Hettinger.)
+  (Contributed by Raymond Hettinger and incorporating design ideas from Jim
+  Baker, Miki Tebeka, and Nick Coghlan; see `recipe 498245
+  <http://code.activestate.com/recipes/498245>`_\, `recipe 577479
+  <http://code.activestate.com/recipes/577479>`_\, :issue:`10586`, and
+  :issue:`10593`.)
 
 * The :func:`functools.wraps` decorator now adds a :attr:`__wrapped__` attribute
   pointing to the original callable function.  This allows wrapped functions to
@@ -348,218 +781,1507 @@
   it also gracefully skips over missing attributes such as :attr:`__doc__` which
   might not be defined for the wrapped callable.
 
+  In the above example, the cache can be removed by recovering the original
+  function:
+
+  >>> get_phone_number = get_phone_number.__wrapped__    # uncached function
+
   (By Nick Coghlan and Terrence Cole; :issue:`9567`, :issue:`3445`, and
   :issue:`8814`.)
 
-* The :mod:`nntplib` module gets a revamped implementation with better
-  bytes / unicode semantics as well as more practical APIs.  These improvements
-  break compatibility with the nntplib version in Python 3.1, which was
-  partly dysfunctional in itself.
+* To help write classes with rich comparison methods, a new decorator
+  :func:`functools.total_ordering` will use a existing equality and inequality
+  methods to fill in the remaining methods.
+
+  For example, supplying *__eq__* and *__lt__* will enable
+  :func:`~functools.total_ordering` to fill-in *__le__*, *__gt__* and *__ge__*::
+
+    @total_ordering
+    class Student:
+        def __eq__(self, other):
+            return ((self.lastname.lower(), self.firstname.lower()) ==
+                    (other.lastname.lower(), other.firstname.lower()))
+        def __lt__(self, other):
+            return ((self.lastname.lower(), self.firstname.lower()) <
+                    (other.lastname.lower(), other.firstname.lower()))
 
-  (Contributed by Antoine Pitrou in :issue:`9360`)
+  With the *total_ordering* decorator, the remaining comparison methods
+  are filled in automatically.
 
-* The :mod:`abc` module now supports :func:`~abc.abstractclassmethod` and
-  :func:`~abc.abstractstaticmethod`.
+  (Contributed by Raymond Hettinger.)
 
-  (Patch submitted by Daniel Urban; :issue:`5867`.)
+* To aid in porting programs from Python 2, the :func:`functools.cmp_to_key`
+  function converts an old-style comparison function to
+  modern :term:`key function`:
 
-* The previously deprecated :func:`contextlib.nested` function has been removed
-  in favor of a plain :keyword:`with` statement which can accept multiple
-  context managers.  The latter technique is faster (because it is built-in),
-  and it does a better job finalizing multiple context managers when one of them
-  raises an exception.
+  >>> # locale-aware sort order
+  >>> sorted(iterable, key=cmp_to_key(locale.strcoll))
 
-  (Contributed by Georg Brandl and Mattias Brändström;
-  `appspot issue 53094 <http://codereview.appspot.com/53094>`_.)
+  For sorting examples and a brief sorting tutorial, see the `Sorting HowTo
+  <http://wiki.python.org/moin/HowTo/Sorting/>`_ tutorial.
 
-* The :class:`ftplib.FTP` class now supports the context manager protocol to
-  unconditionally consume :exc:`socket.error` exceptions and to close the FTP
-  connection when done::
+  (Contributed by Raymond Hettinger.)
 
-   >>> from ftplib import FTP
-   >>> with FTP("ftp1.at.proftpd.org") as ftp:
-   ...     ftp.login()
-   ...     ftp.dir()
-   ...
-   '230 Anonymous login ok, restrictions apply.'
-   dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
-   dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
-   dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
-   dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
+itertools
+---------
 
-  Other file-like objects such as :class:`mmap.mmap` and :func:`fileinput.input`
-  also grew auto-closing context managers::
+* The :mod:`itertools` module has a new :func:`~itertools.accumulate` function
+  modeled on APL's *scan* operator and Numpy's *accumulate* function:
 
-      with fileinput.input(files=('log1.txt', 'log2.txt')) as f:
-          for line in f:
-              process(line)
+  >>> from itertools import accumulate
+  >>> list(accumulate([8, 2, 50]))
+  [8, 10, 60]
+
+  >>> prob_dist = [0.1, 0.4, 0.2, 0.3]
+  >>> list(accumulate(prob_dist))      # cumulative probability distribution
+  [0.1, 0.5, 0.7, 1.0]
+
+  For an example using :func:`~itertools.accumulate`, see the :ref:`examples for
+  the random module <random-examples>`.
+
+  (Contributed by Raymond Hettinger and incorporating design suggestions
+  from Mark Dickinson.)
+
+collections
+-----------
+
+* The :class:`collections.Counter` class now has two forms of in-place
+  subtraction, the existing *-=* operator for `saturating subtraction
+  <http://en.wikipedia.org/wiki/Saturation_arithmetic>`_ and the new
+  :meth:`~collections.Counter.subtract` method for regular subtraction.  The
+  former is suitable for `multisets <http://en.wikipedia.org/wiki/Multiset>`_
+  which only have positive counts, and the latter is more suitable for use cases
+  that allow negative counts:
+
+  >>> tally = Counter(dogs=5, cat=3)
+  >>> tally -= Counter(dogs=2, cats=8)    # saturating subtraction
+  >>> tally
+  Counter({'dogs': 3})
+
+  >>> tally = Counter(dogs=5, cats=3)
+  >>> tally.subtract(dogs=2, cats=8)      # regular subtraction
+  >>> tally
+  Counter({'dogs': 3, 'cats': -5})
 
-  (Contributed by Tarek Ziadé and Giampaolo Rodolà in :issue:`4972`, and
-  by Georg Brandl in :issue:`8046` and :issue:`1286`.)
+  (Contributed by Raymond Hettinger.)
 
-* :class:`gzip.GzipFile` now implements the :class:`io.BufferedIOBase` ABC
-  (except for ``truncate()``), has a :meth:`~gzip.GzipFile.peek` method,
-  and supports unseekable as well as zero-padded file objects.
+* The :class:`collections.OrderedDict` class has a new method
+  :meth:`~collections.OrderedDict.move_to_end` which takes an existing key and
+  moves it to either the first or last position in the ordered sequence.
+
+  The default is to move an item to the last position.  This is equivalent of
+  renewing an entry with ``od[k] = od.pop(k)``.
+
+  A fast move-to-end operation is useful for resequencing entries.  For example,
+  an ordered dictionary can be used to track order of access by aging entries
+  from the oldest to the most recently accessed.
+
+  >>> d = OrderedDict.fromkeys(['a', 'b', 'X', 'd', 'e'])
+  >>> list(d)
+  ['a', 'b', 'X', 'd', 'e']
+  >>> d.move_to_end('X')
+  >>> list(d)
+  ['a', 'b', 'd', 'e', 'X']
 
-  (Contributed by Antoine Pitrou, Nir Aides and Brian Curtin in :issue:`9962`,
-  :issue:`1675951`, :issue:`7471` and :issue:`2846`.)
+  (Contributed by Raymond Hettinger.)
 
-  The :mod:`gzip` module also gains the :func:`~gzip.compress` and
-  :func:`~gzip.decompress` functions for easier in-memory compression and
-  decompression.
+* The :class:`collections.deque` class grew two new methods
+  :meth:`~collections.deque.count` and :meth:`~collections.deque.reverse` that
+  make them more substitutable for :class:`list` objects:
+
+  >>> d = deque('simsalabim')
+  >>> d.count('s')
+  2
+  >>> d.reverse()
+  >>> d
+  deque(['m', 'i', 'b', 'a', 'l', 'a', 's', 'm', 'i', 's'])
 
-  (Contributed by Anand B. Pillai in :issue:`3488`.)
+  (Contributed by Raymond Hettinger.)
 
-* The :mod:`os` module now has the :const:`ST_RDONLY` and :const:`ST_NOSUID`
-  constants, for use with the :func:`~os.statvfs` function.
+threading
+---------
 
-  (Patch by Adam Jackson; :issue:`7647`.)
+The :mod:`threading` module has a new :class:`~threading.Barrier`
+synchronization class for making multiple threads wait until all of them have
+reached a common barrier point.  Barriers are useful for making sure that a task
+with multiple preconditions does not run until all of the predecessor tasks are
+complete.
+
+Barriers can work with an arbitrary number of threads.  This is a generalization
+of a `Rendezvous <http://en.wikipedia.org/wiki/Synchronous_rendezvous>`_ which
+is defined for only two threads.
+
+Implemented as a two-phase cyclic barrier, :class:`~threading.Barrier` objects
+are suitable for use in loops.  The separate *filling* and *draining* phases
+assure that all threads get released (drained) before any one of them can loop
+back and re-enter the barrier.  The barrier fully resets after each cycle.
+
+Example of using barriers::
+
+    from threading import Barrier, Thread
+
+    def get_votes(site):
+        ballots = conduct_election(site)
+        all_polls_closed.wait()        # do not count until all polls are closed
+        totals = summarize(ballots)
+        publish(site, totals)
+
+    all_polls_closed = Barrier(len(sites))
+    for site in sites:
+        Thread(target=get_votes, args=(site,)).start()
+
+In this example, the barrier enforces a rule that votes cannot be counted at any
+polling site until all polls are closed.  Notice how a solution with a barrier
+is similar to one with :meth:`threading.Thread.join`, but the threads stay alive
+and continue to do work (summarizing ballots) after the barrier point is
+crossed.
+
+If any of the predecessor tasks can hang or be delayed, a barrier can be created
+with an optional *timeout* parameter.  Then if the timeout period elapses before
+all the predecessor tasks reach the barrier point, all waiting threads are
+released and a :exc:`~threading.BrokenBarrierError` exception is raised::
+
+    def get_votes(site):
+        ballots = conduct_election(site)
+        try:
+            all_polls_closed.wait(timeout = midnight - time.now())
+        except BrokenBarrierError:
+            lockbox = seal_ballots(ballots)
+            queue.put(lockbox)
+        else:
+            totals = summarize(ballots)
+            publish(site, totals)
+
+In this example, the barrier enforces a more robust rule.  If some election
+sites do not finish before midnight, the barrier times-out and the ballots are
+sealed and deposited in a queue for later handling.
+
+See `Barrier Synchronization Patterns
+<http://parlab.eecs.berkeley.edu/wiki/_media/patterns/paraplop_g1_3.pdf>`_ for
+more examples of how barriers can be used in parallel computing.  Also, there is
+a simple but thorough explanation of barriers in `The Little Book of Semaphores
+<http://greenteapress.com/semaphores/downey08semaphores.pdf>`_, *section 3.6*.
+
+(Contributed by Kristján Valur Jónsson with an API review by Jeffrey Yasskin in
+:issue:`8777`.)
+
+datetime and time
+-----------------
+
+* The :mod:`datetime` module has a new type :class:`~datetime.timezone` that
+  implements the :class:`~datetime.tzinfo` interface by returning a fixed UTC
+  offset and timezone name. This makes it easier to create timezone-aware
+  datetime objects::
+
+    >>> from datetime import datetime, timezone
+
+    >>> datetime.now(timezone.utc)
+    datetime.datetime(2010, 12, 8, 21, 4, 2, 923754, tzinfo=datetime.timezone.utc)
+
+    >>> datetime.strptime("01/01/2000 12:00 +0000", "%m/%d/%Y %H:%M %z")
+    datetime.datetime(2000, 1, 1, 12, 0, tzinfo=datetime.timezone.utc)
+
+* Also, :class:`~datetime.timedelta` objects can now be multiplied by
+  :class:`float` and divided by :class:`float` and :class:`int` objects.
+  And :class:`~datetime.timedelta` objects can now divide one another.
+
+* The :meth:`datetime.date.strftime` method is no longer restricted to years
+  after 1900.  The new supported year range is from 1000 to 9999 inclusive.
+
+* Whenever a two-digit year is used in a time tuple, the interpretation has been
+  governed by :attr:`time.accept2dyear`.  The default is *True* which means that
+  for a two-digit year, the century is guessed according to the POSIX rules
+  governing the ``%y`` strptime format.
+
+  Starting with Py3.2, use of the century guessing heuristic will emit a
+  :exc:`DeprecationWarning`.  Instead, it is recommended that
+  :attr:`time.accept2dyear` be set to *False* so that large date ranges
+  can be used without guesswork::
+
+    >>> import time, warnings
+    >>> warnings.resetwarnings()      # remove the default warning filters
+
+    >>> time.accept2dyear = True      # guess whether 11 means 11 or 2011
+    >>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
+    Warning (from warnings module):
+      ...
+    DeprecationWarning: Century info guessed for a 2-digit year.
+    'Fri Jan  1 12:34:56 2011'
+
+    >>> time.accept2dyear = False     # use the full range of allowable dates
+    >>> time.asctime((11, 1, 1, 12, 34, 56, 4, 1, 0))
+    'Fri Jan  1 12:34:56 11'
+
+  Several functions now have significantly expanded date ranges.  When
+  :attr:`time.accept2dyear` is false, the :func:`time.asctime` function will
+  accept any year that fits in a C int, while the :func:`time.mktime` and
+  :func:`time.strftime` functions will accept the full range supported by the
+  corresponding operating system functions.
+
+(Contributed by Alexander Belopolsky and Victor Stinner in :issue:`1289118`,
+:issue:`5094`, :issue:`6641`, :issue:`2706`, :issue:`1777412`, :issue:`8013`,
+and :issue:`10827`.)
+
+.. XXX http://bugs.python.org/issue?%40search_text=datetime&%40sort=-activity
+
+math
+----
+
+The :mod:`math` module has been updated with six new functions inspired by the
+C99 standard.
+
+The :func:`~math.isfinite` function provides a reliable and fast way to detect
+special values.  It returns *True* for regular numbers and *False* for *Nan* or
+*Infinity*:
+
+>>> [isfinite(x) for x in (123, 4.56, float('Nan'), float('Inf'))]
+[True, True, False, False]
+
+The :func:`~math.expm1` function computes ``e**x-1`` for small values of *x*
+without incurring the loss of precision that usually accompanies the subtraction
+of nearly equal quantities:
+
+>>> expm1(0.013671875)   # more accurate way to compute e**x-1 for a small x
+0.013765762467652909
+
+The :func:`~math.erf` function computes a probability integral or `Gaussian
+error function <http://en.wikipedia.org/wiki/Error_function>`_.  The
+complementary error function, :func:`~math.erfc`, is ``1 - erf(x)``:
+
+>>> erf(1.0/sqrt(2.0))   # portion of normal distribution within 1 standard deviation
+0.682689492137086
+>>> erfc(1.0/sqrt(2.0))  # portion of normal distribution outside 1 standard deviation
+0.31731050786291404
+>>> erf(1.0/sqrt(2.0)) + erfc(1.0/sqrt(2.0))
+1.0
+
+The :func:`~math.gamma` function is a continuous extension of the factorial
+function.  See http://en.wikipedia.org/wiki/Gamma_function for details.  Because
+the function is related to factorials, it grows large even for small values of
+*x*, so there is also a :func:`~math.lgamma` function for computing the natural
+logarithm of the gamma function:
+
+>>> gamma(7.0)           # six factorial
+720.0
+>>> lgamma(801.0)        # log(800 factorial)
+4551.950730698041
+
+(Contributed by Mark Dickinson.)
+
+abc
+---
+
+The :mod:`abc` module now supports :func:`~abc.abstractclassmethod` and
+:func:`~abc.abstractstaticmethod`.
+
+These tools make it possible to define an :term:`abstract base class` that
+requires a particular :func:`classmethod` or :func:`staticmethod` to be
+implemented::
+
+    class Temperature(metaclass=abc.ABCMeta):
+        @abc.abstractclassmethod
+        def from_fahrenheit(cls, t):
+            ...
+        @abc.abstractclassmethod
+        def from_celsius(cls, t):
+            ...
+
+(Patch submitted by Daniel Urban; :issue:`5867`.)
+
+io
+--
+
+The :class:`io.BytesIO` has a new method, :meth:`~io.BytesIO.getbuffer`, which
+provides functionality similar to :func:`memoryview`.  It creates an editable
+view of the data without making a copy.  The buffer's random access and support
+for slice notation are well-suited to in-place editing::
+
+    >>> REC_LEN, LOC_START, LOC_LEN = 34, 7, 11
+
+    >>> def change_location(buffer, record_number, location):
+            start = record_number * REC_LEN + LOC_START
+            buffer[start: start+LOC_LEN] = location
+
+    >>> import io
+
+    >>> byte_stream = io.BytesIO(
+        b'G3805  storeroom  Main chassis    '
+        b'X7899  shipping   Reserve cog     '
+        b'L6988  receiving  Primary sprocket'
+    )
+    >>> buffer = byte_stream.getbuffer()
+    >>> change_location(buffer, 1, b'warehouse  ')
+    >>> change_location(buffer, 0, b'showroom   ')
+    >>> print(byte_stream.getvalue())
+    b'G3805  showroom   Main chassis    '
+    b'X7899  warehouse  Reserve cog     '
+    b'L6988  receiving  Primary sprocket'
+
+(Contributed by Antoine Pitrou in :issue:`5506`.)
+
+reprlib
+-------
+
+When writing a :meth:`__repr__` method for a custom container, it is easy to
+forget to handle the case where a member refers back to the container itself.
+Python's builtin objects such as :class:`list` and :class:`set` handle
+self-reference by displaying "..." in the recursive part of the representation
+string.
+
+To help write such :meth:`__repr__` methods, the :mod:`reprlib` module has a new
+decorator, :func:`~reprlib.recursive_repr`, for detecting recursive calls to
+:meth:`__repr__` and substituting a placeholder string instead::
+
+        >>> class MyList(list):
+                @recursive_repr()
+                def __repr__(self):
+                    return '<' + '|'.join(map(repr, self)) + '>'
+
+        >>> m = MyList('abc')
+        >>> m.append(m)
+        >>> m.append('x')
+        >>> print(m)
+        <'a'|'b'|'c'|...|'x'>
+
+(Contributed by Raymond Hettinger in :issue:`9826` and :issue:`9840`.)
+
+logging
+-------
+
+In addition to dictionary-based configuration described above, the
+:mod:`logging` package has many other improvements.
+
+The logging documentation has been augmented by a :ref:`basic tutorial
+<logging-basic-tutorial>`\, an :ref:`advanced tutorial
+<logging-advanced-tutorial>`\, and a :ref:`cookbook <logging-cookbook>` of
+logging recipes.  These documents are the fastest way to learn about logging.
+
+The :func:`logging.basicConfig` set-up function gained a *style* argument to
+support three different types of string formatting.  It defaults to "%" for
+traditional %-formatting, can be set to "{" for the new :meth:`str.format` style, or
+can be set to "$" for the shell-style formatting provided by
+:class:`string.Template`.  The following three configurations are equivalent::
+
+    >>> from logging import basicConfig
+    >>> basicConfig(style='%', format="%(name)s -> %(levelname)s: %(message)s")
+    >>> basicConfig(style='{', format="{name} -> {levelname} {message}")
+    >>> basicConfig(style='$', format="$name -> $levelname: $message")
+
+If no configuration is set-up before a logging event occurs, there is now a
+default configuration using a :class:`~logging.StreamHandler` directed to
+:attr:`sys.stderr` for events of ``WARNING`` level or higher.  Formerly, an
+event occurring before a configuration was set-up would either raise an
+exception or silently drop the event depending on the value of
+:attr:`logging.raiseExceptions`.  The new default handler is stored in
+:attr:`logging.lastResort`.
+
+The use of filters has been simplified.  Instead of creating a
+:class:`~logging.Filter` object, the predicate can be any Python callable that
+returns *True* or *False*.
+
+There were a number of other improvements that add flexibility and simplify
+configuration.  See the module documentation for a full listing of changes in
+Python 3.2.
+
+csv
+---
+
+The :mod:`csv` module now supports a new dialect, :class:`~csv.unix_dialect`,
+which applies quoting for all fields and a traditional Unix style with ``'\n'`` as
+the line terminator.  The registered dialect name is ``unix``.
+
+The :class:`csv.DictWriter` has a new method,
+:meth:`~csv.DictWriter.writeheader` for writing-out an initial row to document
+the field names::
+
+    >>> import csv, sys
+    >>> w = csv.DictWriter(sys.stdout, ['name', 'dept'], dialect='unix')
+    >>> w.writeheader()
+    "name","dept"
+    >>> w.writerows([
+            {'name': 'tom', 'dept': 'accounting'},
+            {'name': 'susan', 'dept': 'Salesl'}])
+    "tom","accounting"
+    "susan","sales"
+
+(New dialect suggested by Jay Talbot in :issue:`5975`, and the new method
+suggested by Ed Abraham in :issue:`1537721`.)
+
+contextlib
+----------
+
+There is a new and slightly mind-blowing tool
+:class:`~contextlib.ContextDecorator` that is helpful for creating a
+:term:`context manager` that does double duty as a function decorator.
+
+As a convenience, this new functionality is used by
+:func:`~contextlib.contextmanager` so that no extra effort is needed to support
+both roles.
+
+The basic idea is that both context managers and function decorators can be used
+for pre-action and post-action wrappers.  Context managers wrap a group of
+statements using a :keyword:`with` statement, and function decorators wrap a
+group of statements enclosed in a function.  So, occasionally there is a need to
+write a pre-action or post-action wrapper that can be used in either role.
+
+For example, it is sometimes useful to wrap functions or groups of statements
+with a logger that can track the time of entry and time of exit.  Rather than
+writing both a function decorator and a context manager for the task, the
+:func:`~contextlib.contextmanager` provides both capabilities in a single
+definition::
+
+    from contextlib import contextmanager
+    import logging
+
+    logging.basicConfig(level=logging.INFO)
+
+    @contextmanager
+    def track_entry_and_exit(name):
+        logging.info('Entering: {}'.format(name))
+        yield
+        logging.info('Exiting: {}'.format(name))
+
+Formerly, this would have only been usable as a context manager::
+
+    with track_entry_and_exit('widget loader'):
+        print('Some time consuming activity goes here')
+        load_widget()
+
+Now, it can be used as a decorator as well::
+
+    @track_entry_and_exit('widget loader')
+    def activity():
+        print('Some time consuming activity goes here')
+        load_widget()
+
+Trying to fulfill two roles at once places some limitations on the technique.
+Context managers normally have the flexibility to return an argument usable by
+a :keyword:`with` statement, but there is no parallel for function decorators.
+
+In the above example, there is not a clean way for the *track_entry_and_exit*
+context manager to return a logging instance for use in the body of enclosed
+statements.
+
+(Contributed by Michael Foord in :issue:`9110`.)
+
+decimal and fractions
+---------------------
+
+Mark Dickinson crafted an elegant and efficient scheme for assuring that
+different numeric datatypes will have the same hash value whenever their actual
+values are equal (:issue:`8188`)::
+
+   assert hash(Fraction(3, 2)) == hash(1.5) == \
+          hash(Decimal("1.5")) == hash(complex(1.5, 0))
+
+Some of the hashing details are exposed through a new attribute,
+:attr:`sys.hash_info`, which describes the bit width of the hash value, the
+prime modulus, the hash values for *infinity* and *nan*, and the multiplier
+used for the imaginary part of a number:
+
+>>> sys.hash_info
+sys.hash_info(width=64, modulus=2305843009213693951, inf=314159, nan=0, imag=1000003)
+
+An early decision to limit the inter-operability of various numeric types has
+been relaxed.  It is still unsupported (and ill-advised) to have implicit
+mixing in arithmetic expressions such as ``Decimal('1.1') + float('1.1')``
+because the latter loses information in the process of constructing the binary
+float.  However, since existing floating point value can be converted losslessly
+to either a decimal or rational representation, it makes sense to add them to
+the constructor and to support mixed-type comparisons.
+
+* The :class:`decimal.Decimal` constructor now accepts :class:`float` objects
+  directly so there in no longer a need to use the :meth:`~decimal.Decimal.from_float`
+  method (:issue:`8257`).
+
+* Mixed type comparisons are now fully supported so that
+  :class:`~decimal.Decimal` objects can be directly compared with :class:`float`
+  and :class:`fractions.Fraction` (:issue:`2531` and :issue:`8188`).
+
+Similar changes were made to :class:`fractions.Fraction` so that the
+:meth:`~fractions.Fraction.from_float()` and :meth:`~fractions.Fraction.from_decimal`
+methods are no longer needed (:issue:`8294`):
+
+>>> Decimal(1.1)
+Decimal('1.100000000000000088817841970012523233890533447265625')
+>>> Fraction(1.1)
+Fraction(2476979795053773, 2251799813685248)
+
+Another useful change for the :mod:`decimal` module is that the
+:attr:`Context.clamp` attribute is now public.  This is useful in creating
+contexts that correspond to the decimal interchange formats specified in IEEE
+754 (see :issue:`8540`).
+
+(Contributed by Mark Dickinson and Raymond Hettinger.)
+
+ftp
+---
+
+The :class:`ftplib.FTP` class now supports the context manager protocol to
+unconditionally consume :exc:`socket.error` exceptions and to close the FTP
+connection when done::
+
+ >>> from ftplib import FTP
+ >>> with FTP("ftp1.at.proftpd.org") as ftp:
+         ftp.login()
+         ftp.dir()
+
+ '230 Anonymous login ok, restrictions apply.'
+ dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 .
+ dr-xr-xr-x   9 ftp      ftp           154 May  6 10:43 ..
+ dr-xr-xr-x   5 ftp      ftp          4096 May  6 10:43 CentOS
+ dr-xr-xr-x   3 ftp      ftp            18 Jul 10  2008 Fedora
+
+Other file-like objects such as :class:`mmap.mmap` and :func:`fileinput.input`
+also grew auto-closing context managers::
+
+    with fileinput.input(files=('log1.txt', 'log2.txt')) as f:
+        for line in f:
+            process(line)
+
+(Contributed by Tarek Ziadé and Giampaolo Rodolà in :issue:`4972`, and
+by Georg Brandl in :issue:`8046` and :issue:`1286`.)
+
+The :class:`~ftplib.FTP_TLS` class now accepts a *context* parameter, which is a
+:class:`ssl.SSLContext` object allowing bundling SSL configuration options,
+certificates and private keys into a single (potentially long-lived) structure.
+
+(Contributed by Giampaolo Rodolà; :issue:`8806`.)
+
+popen
+-----
+
+The :func:`os.popen` and :func:`subprocess.Popen` functions now support
+:keyword:`with` statements for auto-closing of the file descriptors.
+
+(Contributed by Antoine Pitrou and Brian Curtin in :issue:`7461` and
+:issue:`10554`.)
+
+select
+------
+
+The :mod:`select` module now exposes a new, constant attribute,
+:attr:`~select.PIPE_BUF`, which gives the minimum number of bytes which are
+guaranteed not to block when :func:`select.select` says a pipe is ready
+for writing.
+
+>>> import select
+>>> select.PIPE_BUF
+512
+
+(Available on Unix systems. Patch by Sébastien Sablé in :issue:`9862`)
+
+gzip and zipfile
+----------------
+
+:class:`gzip.GzipFile` now implements the :class:`io.BufferedIOBase`
+:term:`abstract base class` (except for ``truncate()``).  It also has a
+:meth:`~gzip.GzipFile.peek` method and supports unseekable as well as
+zero-padded file objects.
+
+The :mod:`gzip` module also gains the :func:`~gzip.compress` and
+:func:`~gzip.decompress` functions for easier in-memory compression and
+decompression.  Keep in mind that text needs to be encoded as :class:`bytes`
+before compressing and decompressing:
+
+>>> s = 'Three shall be the number thou shalt count, '
+>>> s += 'and the number of the counting shall be three'
+>>> b = s.encode()                        # convert to utf-8
+>>> len(b)
+89
+>>> c = gzip.compress(b)
+>>> len(c)
+77
+>>> gzip.decompress(c).decode()[:42]      # decompress and convert to text
+'Three shall be the number thou shalt count,'
+
+(Contributed by Anand B. Pillai in :issue:`3488`; and by Antoine Pitrou, Nir
+Aides and Brian Curtin in :issue:`9962`, :issue:`1675951`, :issue:`7471` and
+:issue:`2846`.)
+
+Also, the :class:`zipfile.ZipExtFile` class was reworked internally to represent
+files stored inside an archive.  The new implementation is significantly faster
+and can be wrapped in a :class:`io.BufferedReader` object for more speedups.  It
+also solves an issue where interleaved calls to *read* and *readline* gave the
+wrong results.
+
+(Patch submitted by Nir Aides in :issue:`7610`.)
+
+tarfile
+-------
+
+The :class:`~tarfile.TarFile` class can now be used as a context manager.  In
+addition, its :meth:`~tarfile.TarFile.add` method has a new option, *filter*,
+that controls which files are added to the archive and allows the file metadata
+to be edited.
+
+The new *filter* option replaces the older, less flexible *exclude* parameter
+which is now deprecated.  If specified, the optional *filter* parameter needs to
+be a :term:`keyword argument`.  The user-supplied filter function accepts a
+:class:`~tarfile.TarInfo` object and returns an updated
+:class:`~tarfile.TarInfo` object, or if it wants the file to be excluded, the
+function can return *None*::
+
+    >>> import tarfile, glob
+
+    >>> def myfilter(tarinfo):
+           if tarinfo.isfile():             # only save real files
+                tarinfo.uname = 'monty'     # redact the user name
+                return tarinfo
+
+    >>> with tarfile.open(name='myarchive.tar.gz', mode='w:gz') as tf:
+            for filename in glob.glob('*.txt'):
+                tf.add(filename, filter=myfilter)
+            tf.list()
+    -rw-r--r-- monty/501        902 2011-01-26 17:59:11 annotations.txt
+    -rw-r--r-- monty/501        123 2011-01-26 17:59:11 general_questions.txt
+    -rw-r--r-- monty/501       3514 2011-01-26 17:59:11 prion.txt
+    -rw-r--r-- monty/501        124 2011-01-26 17:59:11 py_todo.txt
+    -rw-r--r-- monty/501       1399 2011-01-26 17:59:11 semaphore_notes.txt
+
+(Proposed by Tarek Ziadé and implemented by Lars Gustäbel in :issue:`6856`.)
+
+hashlib
+-------
+
+The :mod:`hashlib` module has two new constant attributes listing the hashing
+algorithms guaranteed to be present in all implementations and those available
+on the current implementation::
+
+    >>> import hashlib
+
+    >>> hashlib.algorithms_guaranteed
+    {'sha1', 'sha224', 'sha384', 'sha256', 'sha512', 'md5'}
+
+    >>> hashlib.algorithms_available
+    {'md2', 'SHA256', 'SHA512', 'dsaWithSHA', 'mdc2', 'SHA224', 'MD4', 'sha256',
+    'sha512', 'ripemd160', 'SHA1', 'MDC2', 'SHA', 'SHA384', 'MD2',
+    'ecdsa-with-SHA1','md4', 'md5', 'sha1', 'DSA-SHA', 'sha224',
+    'dsaEncryption', 'DSA', 'RIPEMD160', 'sha', 'MD5', 'sha384'}
+
+(Suggested by Carl Chenet in :issue:`7418`.)
+
+ast
+---
+
+The :mod:`ast` module has a wonderful a general-purpose tool for safely
+evaluating expression strings using the Python literal
+syntax.  The :func:`ast.literal_eval` function serves as a secure alternative to
+the builtin :func:`eval` function which is easily abused.  Python 3.2 adds
+:class:`bytes` and :class:`set` literals to the list of supported types:
+strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.
+
+::
+
+    >>> from ast import literal_eval
+
+    >>> request = "{'req': 3, 'func': 'pow', 'args': (2, 0.5)}"
+    >>> literal_eval(request)
+    {'args': (2, 0.5), 'req': 3, 'func': 'pow'}
+
+    >>> request = "os.system('do something harmful')"
+    >>> literal_eval(request)
+    Traceback (most recent call last):
+      ...
+    ValueError: malformed node or string: <_ast.Call object at 0x101739a10>
+
+(Implemented by Benjamin Peterson and Georg Brandl.)
+
+os
+--
+
+Different operating systems use various encodings for filenames and environment
+variables.  The :mod:`os` module provides two new functions,
+:func:`~os.fsencode` and :func:`~os.fsdecode`, for encoding and decoding
+filenames:
+
+>>> filename = 'Sehenswürdigkeiten'
+>>> os.fsencode(filename)
+b'Sehensw\xc3\xbcrdigkeiten'
+
+Some operating systems allow direct access to the unencoded bytes in the
+environment.  If so, the :attr:`os.supports_bytes_environ` constant will be
+true.
+
+For direct access to unencoded environment variables (if available),
+use the new :func:`os.getenvb` function or use :data:`os.environb`
+which is a bytes version of :data:`os.environ`.
+
+(Contributed by Victor Stinner.)
+
+shutil
+------
+
+The :func:`shutil.copytree` function has two new options:
+
+* *ignore_dangling_symlinks*: when ``symlinks=False`` so that the function
+  copies a file pointed to by a symlink, not the symlink itself. This option
+  will silence the error raised if the file doesn't exist.
+
+* *copy_function*: is a callable that will be used to copy files.
+  :func:`shutil.copy2` is used by default.
+
+(Contributed by Tarek Ziadé.)
+
+In addition, the :mod:`shutil` module now supports :ref:`archiving operations
+<archiving-operations>` for zipfiles, uncompressed tarfiles, gzipped tarfiles,
+and bzipped tarfiles.  And there are functions for registering additional
+archiving file formats (such as xz compressed tarfiles or custom formats).
+
+The principal functions are :func:`~shutil.make_archive` and
+:func:`~shutil.unpack_archive`.  By default, both operate on the current
+directory (which can be set by :func:`os.chdir`) and on any sub-directories.
+The archive filename needs to be specified with a full pathname.  The archiving
+step is non-destructive (the original files are left unchanged).
+
+::
+
+    >>> import shutil, pprint
+
+    >>> os.chdir('mydata')                               # change to the source directory
+    >>> f = shutil.make_archive('/var/backup/mydata',
+                                'zip')                   # archive the current directory
+    >>> f                                                # show the name of archive
+    '/var/backup/mydata.zip'
+    >>> os.chdir('tmp')                                  # change to an unpacking
+    >>> shutil.unpack_archive('/var/backup/mydata.zip')  # recover the data
+
+    >>> pprint.pprint(shutil.get_archive_formats())      # display known formats
+    [('bztar', "bzip2'ed tar-file"),
+     ('gztar', "gzip'ed tar-file"),
+     ('tar', 'uncompressed tar file'),
+     ('zip', 'ZIP file')]
+
+    >>> shutil.register_archive_format(                  # register a new archive format
+            name = 'xz',
+            function = xz.compress,                      # callable archiving function
+            extra_args = [('level', 8)],                 # arguments to the function
+            description = 'xz compression'
+    )
+
+(Contributed by Tarek Ziadé.)
+
+sqlite3
+-------
+
+The :mod:`sqlite3` module was updated to pysqlite version 2.6.0.  It has two new capabilities.
+
+* The :attr:`sqlite3.Connection.in_transit` attribute is true if there is an
+  active transaction for uncommitted changes.
+
+* The :meth:`sqlite3.Connection.enable_load_extension` and
+  :meth:`sqlite3.Connection.load_extension` methods allows you to load SQLite
+  extensions from ".so" files.  One well-known extension is the fulltext-search
+  extension distributed with SQLite.
+
+(Contributed by R. David Murray and Shashwat Anand; :issue:`8845`.)
+
+html
+----
+
+A new :mod:`html` module was introduced with only a single function,
+:func:`~html.escape`, which is used for escaping reserved characters from HTML
+markup:
+
+>>> import html
+>>> html.escape('x > 2 && x < 7')
+'x &gt; 2 &amp;&amp; x &lt; 7'
 
-* :func:`os.getppid` is now supported on Windows.  Note that it will continue to
-  return the same pid even after the parent process has exited.
+socket
+------
 
-  (Patch by Jon Anglin; :issue:`6394`.)
+The :mod:`socket` module has two new improvements.
 
-* The :func:`shutil.copytree` function has two new options:
+* Socket objects now have a :meth:`~socket.socket.detach()` method which puts
+  the socket into closed state without actually closing the underlying file
+  descriptor.  The latter can then be reused for other purposes.
+  (Added by Antoine Pitrou; :issue:`8524`.)
 
-  * *ignore_dangling_symlinks*: when ``symlinks=False`` so that the function
-    copies the file pointed to by the symlink, not the symlink itself. This
-    option will silence the error raised if the file doesn't exist.
+* :func:`socket.create_connection` now supports the context manager protocol
+  to unconditionally consume :exc:`socket.error` exceptions and to close the
+  socket when done.
+  (Contributed by Giampaolo Rodolà; :issue:`9794`.)
 
-  * *copy_function*: is a callable that will be used to copy files.
-    :func:`shutil.copy2` is used by default.
+ssl
+---
 
-  (Contributed by Tarek Ziadé.)
+The :mod:`ssl` module added a number of features to satisfy common requirements
+for secure (encrypted, authenticated) internet connections:
 
-* Socket objects now have a :meth:`~socket.socket.detach()` method which puts
-  the socket into closed state without actually closing the underlying file
-  descriptor.  The latter can then be reused for other purposes.
+* A new class, :class:`~ssl.SSLContext`, serves as a container for persistent
+  SSL data, such as protocol settings, certificates, private keys, and various
+  other options. It includes a :meth:`~ssl.SSLContext.wrap_socket` for creating
+  an SSL socket from an SSL context.
 
-  (Added by Antoine Pitrou; :issue:`8524`.)
+* A new function, :func:`ssl.match_hostname`, supports server identity
+  verification for higher-level protocols by implementing the rules of HTTPS
+  (from :rfc:`2818`) which are also suitable for other protocols.
 
-* The :mod:`sqlite3` module has two new capabilities.
+* The :func:`ssl.wrap_socket` constructor function now takes a *ciphers*
+  argument.  The *ciphers* string lists the allowed encryption algorithms using
+  the format described in the `OpenSSL documentation
+  <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__.
 
-  The :attr:`Connection.in_transit` attribute is true if there is an active
-  transaction for uncommitted changes.
+* When linked against recent versions of OpenSSL, the :mod:`ssl` module now
+  supports the Server Name Indication extension to the TLS protocol, allowing
+  multiple "virtual hosts" using different certificates on a single IP port.
+  This extension is only supported in client mode, and is activated by passing
+  the *server_hostname* argument to :meth:`ssl.SSLContext.wrap_socket`.
 
-  The :meth:`Connection.enable_load_extension` and
-  :meth:`Connection.load_extension` methods allows you to load SQLite extensions
-  from ".so" files.  One well-known extension is the fulltext-search extension
-  distributed with SQLite.
-
-  (Contributed by R. David Murray and Shashwat Anand; :issue:`8845`.)
-
-* The :mod:`ssl` module has a new class, :class:`~ssl.SSLContext` which serves
-  as a container for various persistent SSL data, such as protocol settings,
-  certificates, private keys, and various other options.  The
-  :meth:`~ssl.SSLContext.wrap_socket` method allows to create an SSL socket from
-  such an SSL context.  (Added by Antoine Pitrou; :issue:`8550`.)
-
-  A new function, :func:`ssl.match_hostname`, helps implement server identity
-  verification for higher-level protocols by implementing the rules of
-  HTTPS (from :rfc:`2818`), which are also suitable for other protocols.
-  (Added by Antoine Pitrou, :issue:`1589`).
-
-  The :func:`ssl.wrap_socket` constructor function now takes a *ciphers*
-  argument that's a string listing the encryption algorithms to be allowed; the
-  format of the string is described `in the OpenSSL documentation
-  <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>`__.  (Added
-  by Antoine Pitrou; :issue:`8322`.)
-
-  When linked against a recent enough version of OpenSSL, the :mod:`ssl`
-  module now supports the Server Name Indication extension to the TLS
-  protocol, allowing for several "virtual hosts" using different certificates
-  on a single IP/port.  This extension is only supported in client mode,
-  and is activated by passing the *server_hostname* argument to
-  :meth:`SSLContext.wrap_socket`.
-  (Added by Antoine Pitrou, :issue:`5639`.)
-
-  Various options have been added to the :mod:`ssl` module, such as
-  :data:`~ssl.OP_NO_SSLv2` which allows to force disabling of the insecure and
-  obsolete SSLv2 protocol.  (Added by Antoine Pitrou; :issue:`4870`.)
-
-  Another change makes the extension load all of OpenSSL's ciphers and digest
-  algorithms so that they're all available.  Some SSL certificates couldn't be
-  verified, reporting an "unknown algorithm" error.  (Reported by Beda Kosata,
-  and fixed by Antoine Pitrou; :issue:`8484`.)
-
-  The version of OpenSSL being used is now available as the module attributes
-  :data:`ssl.OPENSSL_VERSION` (a string), :data:`ssl.OPENSSL_VERSION_INFO` (a
-  5-tuple), and :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer).  (Added by
-  Antoine Pitrou; :issue:`8321`.)
-
-* :class:`http.client.HTTPSConnection`, :class:`urllib.request.HTTPSHandler`
-  and :func:`urllib.request.urlopen` now take optional arguments to allow for
-  server certificate checking against a set of Certificate Authorities,
-  as recommended in public uses of HTTPS.
-  (Added by Antoine Pitrou, :issue:`9003`.)
-
-* Instances of :class:`unittest.TestCase` have two new methods
-  :meth:`~unittest.TestCase.assertWarns` and :meth:`~unittest.TestCase.assertWarnsRegexp`
-  to check that a given warning type was triggered by the code under test::
+* Various options have been added to the :mod:`ssl` module, such as
+  :data:`~ssl.OP_NO_SSLv2` which disables the insecure and obsolete SSLv2
+  protocol.
 
-      with self.assertWarns(DeprecationWarning):
-          legacy_function('XYZ')
+* The extension now loads all the OpenSSL ciphers and digest algorithms.  If
+  some SSL certificates cannot be verified, they are reported as an "unknown
+  algorithm" error.
 
+* The version of OpenSSL being used is now accessible using the module
+  attributes :data:`ssl.OPENSSL_VERSION` (a string),
+  :data:`ssl.OPENSSL_VERSION_INFO` (a 5-tuple), and
+  :data:`ssl.OPENSSL_VERSION_NUMBER` (an integer).
 
-* The previously deprecated :func:`string.maketrans` function has been removed
-  in favor of the static methods, :meth:`bytes.maketrans` and
-  :meth:`bytearray.maketrans`.  This change solves the confusion around which
-  types were supported by the :mod:`string` module.  Now, :class:`str`,
-  :class:`bytes`, and :class:`bytearray` each have their own **maketrans** and
-  **translate** methods with intermediate translation tables of the appropriate
-  type.
+(Contributed by Antoine Pitrou in :issue:`8850`, :issue:`1589`, :issue:`8322`,
+:issue:`5639`, :issue:`4870`, :issue:`8484`, and :issue:`8321`.)
 
-  (Contributed by Georg Brandl; :issue:`5675`.)
+nntp
+----
 
-* :class:`~poplib.POP3_SSL` class now accepts a *context* parameter, which is a
-  :class:`ssl.SSLContext` object allowing bundling SSL configuration options,
-  certificates and private keys into a single (potentially long-lived)
-  structure.
+The :mod:`nntplib` module has a revamped implementation with better bytes and
+text semantics as well as more practical APIs.  These improvements break
+compatibility with the nntplib version in Python 3.1, which was partly
+dysfunctional in itself.
 
-  (Contributed by Giampaolo Rodolà; :issue:`8807`.)
+Support for secure connections through both implicit (using
+:class:`nntplib.NNTP_SSL`) and explicit (using :meth:`nntplib.NNTP.starttls`)
+TLS has also been added.
 
-* :func:`socket.create_connection` now supports the context manager protocol
-  to unconditionally consume :exc:`socket.error` exceptions and to close the
-  socket when done.
+(Contributed by Antoine Pitrou in :issue:`9360` and Andrew Vant in :issue:`1926`.)
 
-  (Contributed by Giampaolo Rodolà; :issue:`9794`.)
+certificates
+------------
 
-* :class:`asyncore.dispatcher` now provides a
-  :meth:`~asyncore.dispatcher.handle_accepted()` method
-  returning a `(sock, addr)` pair which is called when a connection has actually
-  been established with a new remote endpoint. This is supposed to be used as a
-  replacement for old :meth:`~asyncore.dispatcher.handle_accept()` and avoids
-  the user  to call :meth:`~asyncore.dispatcher.accept()` directly.
-
-  (Contributed by Giampaolo Rodolà; :issue:`6706`.)
-
-* The :mod:`tempfile` module has a new context manager,
-  :class:`~tempfile.TemporaryDirectory` which provides easy deterministic
-  cleanup of temporary directories.
+:class:`http.client.HTTPSConnection`, :class:`urllib.request.HTTPSHandler`
+and :func:`urllib.request.urlopen` now take optional arguments to allow for
+server certificate checking against a set of Certificate Authorities,
+as recommended in public uses of HTTPS.
 
-  (Contributed by Neil Schemenauer and Nick Coghlan; :issue:`5178`.)
+(Added by Antoine Pitrou, :issue:`9003`.)
 
-* The :mod:`smtplib` :class:`~smtplib.SMTP` class now accepts a byte string
-  for the *msg* argument to the :meth:`~smtplib.SMTP.sendmail` method,
-  and a new method, :meth:`~smtplib.SMTP.send_message` accepts a
-  :class:`~email.message.Message` object and can optionally obtain the
-  *from_addr* and *to_addrs* addresses directly from the object.
+imaplib
+-------
+
+Support for explicit TLS on standard IMAP4 connections has been added through
+the new :mod:`imaplib.IMAP4.starttls` method.
+
+(Contributed by Lorenzo M. Catucci and Antoine Pitrou, :issue:`4471`.)
+
+http.client
+-----------
 
-  (Contributed by R. David Murray, :issue:`10321`.)
+There were a number of small API improvements in the :mod:`http.client` module.
+The old-style HTTP 0.9 simple responses are no longer supported and the *strict*
+parameter is deprecated in all classes.
 
+The :class:`~http.client.HTTPConnection` and
+:class:`~http.client.HTTPSConnection` classes now have a *source_address*
+parameter for a (host, port) tuple indicating where the HTTP connection is made
+from.
+
+Support for certificate checking and HTTPS virtual hosts were added to
+:class:`~http.client.HTTPSConnection`.
+
+The :meth:`~http.client.HTTPConnection.request` method on connection objects
+allowed an optional *body* argument so that a :term:`file object` could be used
+to supply the content of the request.  Conveniently, the *body* argument now
+also accepts an :term:`iterable` object so long as it includes an explicit
+``Content-Length`` header.  This extended interface is much more flexible than
+before.
+
+To establish an HTTPS connection through a proxy server, there is a new
+:meth:`~http.client.HTTPConnection.set_tunnel` method that sets the host and
+port for HTTP Connect tunneling.
+
+To match the behavior of :mod:`http.server`, the HTTP client library now also
+encodes headers with ISO-8859-1 (Latin-1) encoding.  It was already doing that
+for incoming headers, so now the behavior is consistent for both incoming and
+outgoing traffic. (See work by Armin Ronacher in :issue:`10980`.)
+
+unittest
+--------
+
+The unittest module has a number of improvements supporting test discovery for
+packages, easier experimentation at the interactive prompt, new testcase
+methods, improved diagnostic messages for test failures, and better method
+names.
+
+* The command-line call ``python -m unittest`` can now accept file paths
+  instead of module names for running specific tests (:issue:`10620`).  The new
+  test discovery can find tests within packages, locating any test importable
+  from the top-level directory.  The top-level directory can be specified with
+  the `-t` option, a pattern for matching files with ``-p``, and a directory to
+  start discovery with ``-s``::
+
+    $ python -m unittest discover -s my_proj_dir -p _test.py
+
+  (Contributed by Michael Foord.)
+
+* Experimentation at the interactive prompt is now easier because the
+  :class:`unittest.case.TestCase` class can now be instantiated without
+  arguments:
+
+  >>> TestCase().assertEqual(pow(2, 3), 8)
+
+  (Contributed by Michael Foord.)
+
+* The :mod:`unittest` module has two new methods,
+  :meth:`~unittest.TestCase.assertWarns` and
+  :meth:`~unittest.TestCase.assertWarnsRegex` to verify that a given warning type
+  is triggered by the code under test::
+
+      with self.assertWarns(DeprecationWarning):
+          legacy_function('XYZ')
+
+  (Contributed by Antoine Pitrou, :issue:`9754`.)
+
+  Another new method, :meth:`~unittest.TestCase.assertCountEqual` is used to
+  compare two iterables to determine if their element counts are equal (whether
+  the same elements are present with the same number of occurrences regardless
+  of order)::
+
+     def test_anagram(self):
+         self.assertCountEqual('algorithm', 'logarithm')
+
+  (Contributed by Raymond Hettinger.)
+
+* A principal feature of the unittest module is an effort to produce meaningful
+  diagnostics when a test fails.  When possible, the failure is recorded along
+  with a diff of the output.  This is especially helpful for analyzing log files
+  of failed test runs. However, since diffs can sometime be voluminous, there is
+  a new :attr:`~unittest.TestCase.maxDiff` attribute that sets maximum length of
+  diffs displayed.
+
+* In addition, the method names in the module have undergone a number of clean-ups.
+
+  For example, :meth:`~unittest.TestCase.assertRegex` is the new name for
+  :meth:`~unittest.TestCase.assertRegexpMatches` which was misnamed because the
+  test uses :func:`re.search`, not :func:`re.match`.  Other methods using
+  regular expressions are now named using short form "Regex" in preference to
+  "Regexp" -- this matches the names used in other unittest implementations,
+  matches Python's old name for the :mod:`re` module, and it has unambiguous
+  camel-casing.
+
+  (Contributed by Raymond Hettinger and implemented by Ezio Melotti.)
+
+* To improve consistency, some long-standing method aliases are being
+  deprecated in favor of the preferred names:
+
+   ===============================   ==============================
+   Old Name                          Preferred Name
+   ===============================   ==============================
+   :meth:`assert_`                   :meth:`.assertTrue`
+   :meth:`assertEquals`              :meth:`.assertEqual`
+   :meth:`assertNotEquals`           :meth:`.assertNotEqual`
+   :meth:`assertAlmostEquals`        :meth:`.assertAlmostEqual`
+   :meth:`assertNotAlmostEquals`     :meth:`.assertNotAlmostEqual`
+   ===============================   ==============================
+
+  Likewise, the ``TestCase.fail*`` methods deprecated in Python 3.1 are expected
+  to be removed in Python 3.3.  Also see the :ref:`deprecated-aliases` section in
+  the :mod:`unittest` documentation.
+
+  (Contributed by Ezio Melotti; :issue:`9424`.)
+
+* The :meth:`~unittest.TestCase.assertDictContainsSubset` method was deprecated
+  because it was misimplemented with the arguments in the wrong order.  This
+  created hard-to-debug optical illusions where tests like
+  ``TestCase().assertDictContainsSubset({'a':1, 'b':2}, {'a':1})`` would fail.
+
+  (Contributed by Raymond Hettinger.)
+
+random
+------
+
+The integer methods in the :mod:`random` module now do a better job of producing
+uniform distributions.  Previously, they computed selections with
+``int(n*random())`` which had a slight bias whenever *n* was not a power of two.
+Now, multiple selections are made from a range up to the next power of two and a
+selection is kept only when it falls within the range ``0 <= x < n``.  The
+functions and methods affected are :func:`~random.randrange`,
+:func:`~random.randint`, :func:`~random.choice`, :func:`~random.shuffle` and
+:func:`~random.sample`.
+
+(Contributed by Raymond Hettinger; :issue:`9025`.)
+
+poplib
+------
+
+:class:`~poplib.POP3_SSL` class now accepts a *context* parameter, which is a
+:class:`ssl.SSLContext` object allowing bundling SSL configuration options,
+certificates and private keys into a single (potentially long-lived)
+structure.
+
+(Contributed by Giampaolo Rodolà; :issue:`8807`.)
+
+asyncore
+--------
+
+:class:`asyncore.dispatcher` now provides a
+:meth:`~asyncore.dispatcher.handle_accepted()` method
+returning a `(sock, addr)` pair which is called when a connection has actually
+been established with a new remote endpoint. This is supposed to be used as a
+replacement for old :meth:`~asyncore.dispatcher.handle_accept()` and avoids
+the user  to call :meth:`~asyncore.dispatcher.accept()` directly.
+
+(Contributed by Giampaolo Rodolà; :issue:`6706`.)
+
+tempfile
+--------
+
+The :mod:`tempfile` module has a new context manager,
+:class:`~tempfile.TemporaryDirectory` which provides easy deterministic
+cleanup of temporary directories::
+
+    with tempfile.TemporaryDirectory() as tmpdirname:
+        print('created temporary dir:', tmpdirname)
+
+(Contributed by Neil Schemenauer and Nick Coghlan; :issue:`5178`.)
+
+inspect
+-------
+
+* The :mod:`inspect` module has a new function
+  :func:`~inspect.getgeneratorstate` to easily identify the current state of a
+  generator-iterator::
+
+    >>> from inspect import getgeneratorstate
+    >>> def gen():
+            yield 'demo'
+    >>> g = gen()
+    >>> getgeneratorstate(g)
+    'GEN_CREATED'
+    >>> next(g)
+    'demo'
+    >>> getgeneratorstate(g)
+    'GEN_SUSPENDED'
+    >>> next(g, None)
+    >>> getgeneratorstate(g)
+    'GEN_CLOSED'
+
+  (Contributed by Rodolpho Eckhardt and Nick Coghlan, :issue:`10220`.)
+
+* To support lookups without the possibility of activating a dynamic attribute,
+  the :mod:`inspect` module has a new function, :func:`~inspect.getattr_static`.
+  Unlike :func:`hasattr`, this is a true read-only search, guaranteed not to
+  change state while it is searching::
+
+    >>> class A:
+            @property
+            def f(self):
+                print('Running')
+                return 10
+
+    >>> a = A()
+    >>> getattr(a, 'f')
+    Running
+    10
+    >>> inspect.getattr_static(a, 'f')
+    <property object at 0x1022bd788>
+
+ (Contributed by Michael Foord.)
+
+pydoc
+-----
+
+The :mod:`pydoc` module now provides a much-improved Web server interface, as
+well as a new command-line option ``-b`` to automatically open a browser window
+to display that server::
+
+    $ pydoc3.2 -b
+
+(Contributed by Ron Adam; :issue:`2001`.)
+
+dis
+---
+
+The :mod:`dis` module gained two new functions for inspecting code,
+:func:`~dis.code_info` and :func:`~dis.show_code`.  Both provide detailed code
+object information for the supplied function, method, source code string or code
+object.  The former returns a string and the latter prints it::
+
+    >>> import dis, random
+    >>> dis.show_code(random.choice)
+    Name:              choice
+    Filename:          /Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/random.py
+    Argument count:    2
+    Kw-only arguments: 0
+    Number of locals:  3
+    Stack size:        11
+    Flags:             OPTIMIZED, NEWLOCALS, NOFREE
+    Constants:
+       0: 'Choose a random element from a non-empty sequence.'
+       1: 'Cannot choose from an empty sequence'
+    Names:
+       0: _randbelow
+       1: len
+       2: ValueError
+       3: IndexError
+    Variable names:
+       0: self
+       1: seq
+       2: i
+
+In addition, the :func:`~dis.dis` function now accepts string arguments
+so that the common idiom ``dis(compile(s, '', 'eval'))`` can be shortened
+to ``dis(s)``::
+
+    >>> dis('3*x+1 if x%2==1 else x//2')
+      1           0 LOAD_NAME                0 (x)
+                  3 LOAD_CONST               0 (2)
+                  6 BINARY_MODULO
+                  7 LOAD_CONST               1 (1)
+                 10 COMPARE_OP               2 (==)
+                 13 POP_JUMP_IF_FALSE       28
+                 16 LOAD_CONST               2 (3)
+                 19 LOAD_NAME                0 (x)
+                 22 BINARY_MULTIPLY
+                 23 LOAD_CONST               1 (1)
+                 26 BINARY_ADD
+                 27 RETURN_VALUE
+            >>   28 LOAD_NAME                0 (x)
+                 31 LOAD_CONST               0 (2)
+                 34 BINARY_FLOOR_DIVIDE
+                 35 RETURN_VALUE
+
+Taken together, these improvements make it easier to explore how CPython is
+implemented and to see for yourself what the language syntax does
+under-the-hood.
+
+(Contributed by Nick Coghlan in :issue:`9147`.)
+
+dbm
+---
+
+All database modules now support the :meth:`get` and :meth:`setdefault` methods.
+
+(Suggested by Ray Allen in :issue:`9523`.)
+
+ctypes
+------
+
+A new type, :class:`ctypes.c_ssize_t` represents the C :c:type:`ssize_t` datatype.
+
+site
+----
+
+The :mod:`site` module has three new functions useful for reporting on the
+details of a given Python installation.
+
+* :func:`~site.getsitepackages` lists all global site-packages directories.
+
+* :func:`~site.getuserbase` reports on the user's base directory where data can
+  be stored.
+
+* :func:`~site.getusersitepackages` reveals the user-specific site-packages
+  directory path.
+
+::
+
+    >>> import site
+    >>> site.getsitepackages()
+    ['/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/site-packages',
+     '/Library/Frameworks/Python.framework/Versions/3.2/lib/site-python',
+     '/Library/Python/3.2/site-packages']
+    >>> site.getuserbase()
+    '/Users/raymondhettinger/Library/Python/3.2'
+    >>> site.getusersitepackages()
+    '/Users/raymondhettinger/Library/Python/3.2/lib/python/site-packages'
+
+Conveniently, some of site's functionality is accessible directly from the
+command-line::
+
+    $ python -m site --user-base
+    /Users/raymondhettinger/.local
+    $ python -m site --user-site
+    /Users/raymondhettinger/.local/lib/python3.2/site-packages
+
+(Contributed by Tarek Ziadé in :issue:`6693`.)
+
+sysconfig
+---------
+
+The new :mod:`sysconfig` module makes it straightforward to discover
+installation paths and configuration variables that vary across platforms and
+installations.
+
+The module offers access simple access functions for platform and version
+information:
+
+* :func:`~sysconfig.get_platform` returning values like *linux-i586* or
+  *macosx-10.6-ppc*.
+* :func:`~sysconfig.get_python_version` returns a Python version string
+  such as "3.2".
+
+It also provides access to the paths and variables corresponding to one of
+seven named schemes used by :mod:`distutils`.  Those include *posix_prefix*,
+*posix_home*, *posix_user*, *nt*, *nt_user*, *os2*, *os2_home*:
+
+* :func:`~sysconfig.get_paths` makes a dictionary containing installation paths
+  for the current installation scheme.
+* :func:`~sysconfig.get_config_vars` returns a dictionary of platform specific
+  variables.
+
+There is also a convenient command-line interface::
+
+  C:\Python32>python -m sysconfig
+  Platform: "win32"
+  Python version: "3.2"
+  Current installation scheme: "nt"
+
+  Paths:
+          data = "C:\Python32"
+          include = "C:\Python32\Include"
+          platinclude = "C:\Python32\Include"
+          platlib = "C:\Python32\Lib\site-packages"
+          platstdlib = "C:\Python32\Lib"
+          purelib = "C:\Python32\Lib\site-packages"
+          scripts = "C:\Python32\Scripts"
+          stdlib = "C:\Python32\Lib"
+
+  Variables:
+          BINDIR = "C:\Python32"
+          BINLIBDEST = "C:\Python32\Lib"
+          EXE = ".exe"
+          INCLUDEPY = "C:\Python32\Include"
+          LIBDEST = "C:\Python32\Lib"
+          SO = ".pyd"
+          VERSION = "32"
+          abiflags = ""
+          base = "C:\Python32"
+          exec_prefix = "C:\Python32"
+          platbase = "C:\Python32"
+          prefix = "C:\Python32"
+          projectbase = "C:\Python32"
+          py_version = "3.2"
+          py_version_nodot = "32"
+          py_version_short = "3.2"
+          srcdir = "C:\Python32"
+          userbase = "C:\Documents and Settings\Raymond\Application Data\Python"
+
+(Moved out of Distutils by Tarek Ziadé.)
+
+pdb
+---
+
+The :mod:`pdb` debugger module gained a number of usability improvements:
+
+* :file:`pdb.py` now has a ``-c`` option that executes commands as given in a
+  :file:`.pdbrc` script file.
+* A :file:`.pdbrc` script file can contain ``continue`` and ``next`` commands
+  that continue debugging.
+* The :class:`Pdb` class constructor now accepts a *nosigint* argument.
+* New commands: ``l(list)``, ``ll(long list)`` and ``source`` for
+  listing source code.
+* New commands: ``display`` and ``undisplay`` for showing or hiding
+  the value of an expression if it has changed.
+* New command: ``interact`` for starting an interactive interpreter containing
+  the global and local  names found in the current scope.
+* Breakpoints can be cleared by breakpoint number.
+
+(Contributed by Georg Brandl, Antonio Cuni and Ilya Sandler.)
+
+configparser
+------------
+
+The :mod:`configparser` module was modified to improve usability and
+predictability of the default parser and its supported INI syntax.  The old
+:class:`ConfigParser` class was removed in favor of :class:`SafeConfigParser`
+which has in turn been renamed to :class:`~configparser.ConfigParser`. Support
+for inline comments is now turned off by default and section or option
+duplicates are not allowed in a single configuration source.
+
+Config parsers gained a new API based on the mapping protocol::
+
+    >>> parser = ConfigParser()
+    >>> parser.read_string("""
+    [DEFAULT]
+    location = upper left
+    visible = yes
+    editable = no
+    color = blue
+
+    [main]
+    title = Main Menu
+    color = green
+
+    [options]
+    title = Options
+    """)
+    >>> parser['main']['color']
+    'green'
+    >>> parser['main']['editable']
+    'no'
+    >>> section = parser['options']
+    >>> section['title']
+    'Options'
+    >>> section['title'] = 'Options (editable: %(editable)s)'
+    >>> section['title']
+    'Options (editable: no)'
+
+The new API is implemented on top of the classical API, so custom parser
+subclasses should be able to use it without modifications.
+
+The INI file structure accepted by config parsers can now be customized. Users
+can specify alternative option/value delimiters and comment prefixes, change the
+name of the *DEFAULT* section or switch the interpolation syntax.
+
+There is support for pluggable interpolation including an additional interpolation
+handler :class:`~configparser.ExtendedInterpolation`::
+
+  >>> parser = ConfigParser(interpolation=ExtendedInterpolation())
+  >>> parser.read_dict({'buildout': {'directory': '/home/ambv/zope9'},
+                        'custom': {'prefix': '/usr/local'}})
+  >>> parser.read_string("""
+      [buildout]
+      parts =
+        zope9
+        instance
+      find-links =
+        ${buildout:directory}/downloads/dist
+
+      [zope9]
+      recipe = plone.recipe.zope9install
+      location = /opt/zope
+
+      [instance]
+      recipe = plone.recipe.zope9instance
+      zope9-location = ${zope9:location}
+      zope-conf = ${custom:prefix}/etc/zope.conf
+      """)
+  >>> parser['buildout']['find-links']
+  '\n/home/ambv/zope9/downloads/dist'
+  >>> parser['instance']['zope-conf']
+  '/usr/local/etc/zope.conf'
+  >>> instance = parser['instance']
+  >>> instance['zope-conf']
+  '/usr/local/etc/zope.conf'
+  >>> instance['zope9-location']
+  '/opt/zope'
+
+A number of smaller features were also introduced, like support for specifying
+encoding in read operations, specifying fallback values for get-functions, or
+reading directly from dictionaries and strings.
+
+(All changes contributed by Łukasz Langa.)
+
+.. XXX consider showing a difflib example
+
+urllib.parse
+------------
+
+A number of usability improvements were made for the :mod:`urllib.parse` module.
+
+The :func:`~urllib.parse.urlparse` function now supports `IPv6
+<http://en.wikipedia.org/wiki/IPv6>`_ addresses as described in :rfc:`2732`:
+
+    >>> import urllib.parse
+    >>> urllib.parse.urlparse('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/')
+    ParseResult(scheme='http',
+                netloc='[dead:beef:cafe:5417:affe:8FA3:deaf:feed]',
+                path='/foo/',
+                params='',
+                query='',
+                fragment='')
+
+The :func:`~urllib.parse.urldefrag` function now returns a :term:`named tuple`::
+
+    >>> r = urllib.parse.urldefrag('http://python.org/about/#target')
+    >>> r
+    DefragResult(url='http://python.org/about/', fragment='target')
+    >>> r[0]
+    'http://python.org/about/'
+    >>> r.fragment
+    'target'
+
+And, the :func:`~urllib.parse.urlencode` function is now much more flexible,
+accepting either a string or bytes type for the *query* argument.  If it is a
+string, then the *safe*, *encoding*, and *error* parameters are sent to
+:func:`~urllib.parse.quote_plus` for encoding::
+
+    >>> urllib.parse.urlencode([
+             ('type', 'telenovela'),
+             ('name', '¿Dónde Está Elisa?')],
+             encoding='latin-1')
+    'type=telenovela&name=%BFD%F3nde+Est%E1+Elisa%3F'
+
+As detailed in :ref:`parsing-ascii-encoded-bytes`, all the :mod:`urllib.parse`
+functions now accept ASCII-encoded byte strings as input, so long as they are
+not mixed with regular strings.  If ASCII-encoded byte strings are given as
+parameters, the return types will also be an ASCII-encoded byte strings:
+
+    >>> urllib.parse.urlparse(b'http://www.python.org:80/about/')
+    ParseResultBytes(scheme=b'http', netloc=b'www.python.org:80',
+                     path=b'/about/', params=b'', query=b'', fragment=b'')
+
+(Work by Nick Coghlan, Dan Mahn, and Senthil Kumaran in :issue:`2987`,
+:issue:`5468`, and :issue:`9873`.)
+
+mailbox
+-------
+
+Thanks to a concerted effort by R. David Murray, the :mod:`mailbox` module has
+been fixed for Python 3.2.  The challenge was that mailbox had been originally
+designed with a text interface, but email messages are best represented with
+:class:`bytes` because various parts of a message may have different encodings.
+
+The solution harnessed the :mod:`email` package's binary support for parsing
+arbitrary email messages.  In addition, the solution required a number of API
+changes.
+
+As expected, the :meth:`~mailbox.Mailbox.add` method for
+:class:`mailbox.Mailbox` objects now accepts binary input.
+
+:class:`~io.StringIO` and text file input are deprecated.  Also, string input
+will fail early if non-ASCII characters are used.  Previously it would fail when
+the email was processed in a later step.
+
+There is also support for binary output.  The :meth:`~mailbox.Mailbox.get_file`
+method now returns a file in the binary mode (where it used to incorrectly set
+the file to text-mode).  There is also a new :meth:`~mailbox.Mailbox.get_bytes`
+method that returns a :class:`bytes` representation of a message corresponding
+to a given *key*.
+
+It is still possible to get non-binary output using the old API's
+:meth:`~mailbox.Mailbox.get_string` method, but that approach
+is not very useful.  Instead, it is best to extract messages from
+a :class:`~mailbox.Message` object or to load them from binary input.
+
+(Contributed by R. David Murray, with efforts from Steffen Daode Nurpmeso and an
+initial patch by Victor Stinner in :issue:`9124`.)
+
+turtledemo
+----------
+
+The demonstration code for the :mod:`turtle` module was moved from the *Demo*
+directory to main library.  It includes over a dozen sample scripts with
+lively displays.  Being on :attr:`sys.path`, it can now be run directly
+from the command-line::
+
+    $ python -m turtledemo
+
+(Moved from the Demo directory by Alexander Belopolsky in :issue:`10199`.)
 
 Multi-threading
 ===============
 
 * The mechanism for serializing execution of concurrently running Python threads
-  (generally known as the GIL or Global Interpreter Lock) has been rewritten.
-  Among the objectives were more predictable switching intervals and reduced
-  overhead due to lock contention and the number of ensuing system calls.  The
-  notion of a "check interval" to allow thread switches has been abandoned and
-  replaced by an absolute duration expressed in seconds.  This parameter is
-  tunable through :func:`sys.setswitchinterval()`.  It currently defaults to 5
-  milliseconds.
+  (generally known as the :term:`GIL` or :term:`Global Interpreter Lock`) has
+  been rewritten.  Among the objectives were more predictable switching
+  intervals and reduced overhead due to lock contention and the number of
+  ensuing system calls.  The notion of a "check interval" to allow thread
+  switches has been abandoned and replaced by an absolute duration expressed in
+  seconds.  This parameter is tunable through :func:`sys.setswitchinterval()`.
+  It currently defaults to 5 milliseconds.
 
   Additional details about the implementation can be read from a `python-dev
   mailing-list message
@@ -569,34 +2291,25 @@
 
   (Contributed by Antoine Pitrou.)
 
-* Recursive locks (created with the :func:`threading.RLock` API) now benefit
-  from a C implementation which makes them as fast as regular locks, and between
-  10x and 15x faster than their previous pure Python implementation.
-
-  (Contributed by Antoine Pitrou; :issue:`3001`.)
-
 * Regular and recursive locks now accept an optional *timeout* argument to their
-  :meth:`acquire` method.  (Contributed by Antoine Pitrou; :issue:`7316`.)
+  :meth:`~threading.Lock.acquire` method.  (Contributed by Antoine Pitrou;
+  :issue:`7316`.)
 
-  Similarly, :meth:`threading.Semaphore.acquire` also gains a *timeout*
+* Similarly, :meth:`threading.Semaphore.acquire` also gained a *timeout*
   argument.  (Contributed by Torsten Landschoff; :issue:`850728`.)
 
+* Regular and recursive lock acquisitions can now be interrupted by signals on
+  platforms using Pthreads.  This means that Python programs that deadlock while
+  acquiring locks can be successfully killed by repeatedly sending SIGINT to the
+  process (by pressing :kbd:`Ctrl+C` in most shells).
+  (Contributed by Reid Kleckner; :issue:`8844`.)
+
 
 Optimizations
 =============
 
 A number of small performance enhancements have been added:
 
-* JSON decoding performance is improved and memory consumption is reduced
-  whenever the same string is repeated for multiple keys.
-
-  (Contributed by Antoine Pitrou; :issue:`7451`.)
-
-* JSON encoding now uses the C speedups also when the ``sort_keys`` argument
-  is true.
-
-  (Contributed by Raymond Hettinger and Antoine Pitrou, :issue:`10314`.)
-
 * Python's peephole optimizer now recognizes patterns such ``x in {1, 2, 3}`` as
   being a test for membership in a set of constants.  The optimizer recasts the
   :class:`set` as a :class:`frozenset` and stores the pre-built constant.
@@ -609,7 +2322,36 @@
       if extension in {'xml', 'html', 'xhtml', 'css'}:
           handle(name)
 
-  (Patch and additional tests by Dave Malcolm; :issue:`6690`).
+  (Patch and additional tests contributed by Dave Malcolm; :issue:`6690`).
+
+* Serializing and unserializing data using the :mod:`pickle` module is now
+  several times faster.
+
+  (Contributed by Alexandre Vassalotti, Antoine Pitrou
+  and the Unladen Swallow team in :issue:`9410` and :issue:`3873`.)
+
+* The `Timsort algorithm <http://en.wikipedia.org/wiki/Timsort>`_ used in
+  :meth:`list.sort` and :func:`sorted` now runs faster and uses less memory
+  when called with a :term:`key function`.  Previously, every element of
+  a list was wrapped with a temporary object that remembered the key value
+  associated with each element.  Now, two arrays of keys and values are
+  sorted in parallel.  This saves the memory consumed by the sort wrappers,
+  and it saves time lost to delegating comparisons.
+
+  (Patch by Daniel Stutzbach in :issue:`9915`.)
+
+* JSON decoding performance is improved and memory consumption is reduced
+  whenever the same string is repeated for multiple keys.  Also, JSON encoding
+  now uses the C speedups when the ``sort_keys`` argument is true.
+
+  (Contributed by Antoine Pitrou in :issue:`7451` and by Raymond Hettinger and
+  Antoine Pitrou in :issue:`10314`.)
+
+* Recursive locks (created with the :func:`threading.RLock` API) now benefit
+  from a C implementation which makes them as fast as regular locks, and between
+  10x and 15x faster than their previous pure Python implementation.
+
+  (Contributed by Antoine Pitrou; :issue:`3001`.)
 
 * The fast-search algorithm in stringlib is now used by the :meth:`split`,
   :meth:`rsplit`, :meth:`splitlines` and :meth:`replace` methods on
@@ -619,40 +2361,126 @@
 
   (Patch by Florent Xicluna in :issue:`7622` and :issue:`7462`.)
 
-* Serializing and unserializing data using the :mod:`pickle` module is now
-  several times faster. (Contributed by Alexandre Vassalotti, Antoine Pitrou
-  and the Unladen Swallow team in :issue:`9410` and :issue:`3873`.)
+
+* String to integer conversions now work two "digits" at a time, reducing the
+  number of division and modulo operations.
+
+  (:issue:`6713` by Gawain Bolton, Mark Dickinson, and Victor Stinner.)
+
+There were several other minor optimizations. Set differencing now runs faster
+when one operand is much larger than the other (patch by Andress Bennetts in
+:issue:`8685`).  The :meth:`array.repeat` method has a faster implementation
+(:issue:`1569291` by Alexander Belopolsky). The :class:`BaseHTTPRequestHandler`
+has more efficient buffering (:issue:`3709` by Andrew Schaaf).  The
+:func:`operator.attrgetter` function has been sped-up (:issue:`10160` by
+Christos Georgiou).  And :class:`ConfigParser` loads multi-line arguments a bit
+faster (:issue:`7113` by Łukasz Langa).
 
 
 Unicode
 =======
 
-The :mod:`os` module has two new functions: :func:`~os.fsencode` and
-:func:`~os.fsdecode`. Add :data:`os.environb`: bytes version of
-:data:`os.environ`, :func:`os.getenvb` function and
-:data:`os.supports_bytes_environ` constant.
-
-``'mbcs'`` encoding doesn't ignore the error handler argument anymore. By
-default (strict mode), it raises an UnicodeDecodeError on undecodable byte
-sequence and UnicodeEncodeError on unencodable character. To get the ``'mbcs'``
-encoding of Python 3.1, use ``'ignore'`` error handler to decode and
-``'replace'`` error handler to encode. ``'mbcs'`` supports ``'strict'`` and
-``'ignore'`` error handlers for decoding, and ``'strict'`` and ``'replace'``
-for encoding.
-
-On Mac OS X, Python uses ``'utf-8'`` to decode the command line arguments,
-instead of the locale encoding (which is ISO-8859-1 if the ``LANG`` environment
-variable is not set).
+Python has been updated to `Unicode 6.0.0
+<http://unicode.org/versions/Unicode6.0.0/>`_.  The update to the standard adds
+over 2,000 new characters including `emoji <http://en.wikipedia.org/wiki/Emoji>`_
+symbols which are important for mobile phones.
+
+In addition, the updated standard has altered the character properties for two
+Kannada characters (U+0CF1, U+0CF2) and one New Tai Lue numeric character
+(U+19DA), making the former eligible for use in identifiers while disqualifying
+the latter.  For more information, see `Unicode Character Database Changes
+<http://www.unicode.org/versions/Unicode6.0.0/#Database_Changes>`_.
+
+
+Codecs
+======
 
-By default, tarfile uses ``'utf-8'`` encoding on Windows (instead of
-``'mbcs'``), and the ``'surrogateescape'`` error handler on all operating
+Support was added for *cp720* Arabic DOS encoding (:issue:`1616979`).
+
+MBCS encoding no longer ignores the error handler argument. In the default
+strict mode, it raises an :exc:`UnicodeDecodeError` when it encounters an
+undecodable byte sequence and an :exc:`UnicodeEncodeError` for an unencodable
+character.
+
+The MBCS codec supports ``'strict'`` and ``'ignore'`` error handlers for
+decoding, and ``'strict'`` and ``'replace'`` for encoding.
+
+To emulate Python3.1 MBCS encoding, select the ``'ignore'`` handler for decoding
+and the ``'replace'`` handler for encoding.
+
+On Mac OS X, Python decodes command line arguments with ``'utf-8'`` rather than
+the locale encoding.
+
+By default, :mod:`tarfile` uses ``'utf-8'`` encoding on Windows (instead of
+``'mbcs'``) and the ``'surrogateescape'`` error handler on all operating
 systems.
 
 
-.. IDLE
-   ====
+Documentation
+=============
+
+The documentation continues to be improved.
+
+* A table of quick links has been added to the top of lengthy sections such as
+  :ref:`built-in-funcs`.  In the case of :mod:`itertools`, the links are
+  accompanied by tables of cheatsheet-style summaries to provide an overview and
+  memory jog without having to read all of the docs.
+
+* In some cases, the pure Python source code can be a helpful adjunct to the
+  documentation, so now many modules now feature quick links to the latest
+  version of the source code.  For example, the :mod:`functools` module
+  documentation has a quick link at the top labeled:
+
+    **Source code** :source:`Lib/functools.py`.
+
+  (Contributed by Raymond Hettinger; see
+  `rationale <http://rhettinger.wordpress.com/2011/01/28/open-your-source-more/>`_.)
+
+* The docs now contain more examples and recipes.  In particular, :mod:`re`
+  module has an extensive section, :ref:`re-examples`.  Likewise, the
+  :mod:`itertools` module continues to be updated with new
+  :ref:`itertools-recipes`.
+
+* The :mod:`datetime` module now has an auxiliary implementation in pure Python.
+  No functionality was changed.  This just provides an easier-to-read alternate
+  implementation.
+
+  (Contributed by Alexander Belopolsky in :issue:`9528`.)
+
+* The unmaintained :file:`Demo` directory has been removed.  Some demos were
+  integrated into the documentation, some were moved to the :file:`Tools/demo`
+  directory, and others were removed altogether.
+
+  (Contributed by Georg Brandl in :issue:`7962`.)
 
-   * Stub
+
+IDLE
+====
+
+* The format menu now has an option to clean source files by stripping
+  trailing whitespace.
+
+  (Contributed by Raymond Hettinger; :issue:`5150`.)
+
+* IDLE on Mac OS X now works with both Carbon AquaTk and Cocoa AquaTk.
+
+  (Contributed by Kevin Walzer, Ned Deily, and Ronald Oussoren; :issue:`6075`.)
+
+Code Repository
+===============
+
+In addition to the existing Subversion code repository at http://svn.python.org
+there is now a `Mercurial <http://mercurial.selenic.com/>`_ repository at
+http://hg.python.org/ .
+
+After the 3.2 release, there are plans to switch to Mercurial as the primary
+repository.  This distributed version control system should make it easier for
+members of the community to create and share external changesets.  See
+:pep:`385` for details.
+
+To learn to use the new version control system, see the `tutorial by Joel
+Spolsky <http://hginit.com>`_ or the `Guide to Mercurial Workflows
+<http://mercurial.selenic.com/guide/>`_.
 
 
 Build and C API Changes
@@ -660,6 +2488,9 @@
 
 Changes to Python's build process and to the C API include:
 
+* The *idle*, *pydoc* and *2to3* scripts are now installed with a
+  version-specific suffix on ``make altinstall`` (:issue:`10679`).
+
 * The C functions that access the Unicode Database now accept and return
   characters from the full Unicode range, even on narrow unicode builds
   (Py_UNICODE_TOLOWER, Py_UNICODE_ISDECIMAL, and others).  A visible difference
@@ -680,12 +2511,58 @@
 
   (Contributed by Amaury Forgeot D'Arc; :issue:`9210`.)
 
-* Hash values are now values of a new type, Py_hash_t, which is defined to
-  be the same size as a pointer.  Previously they were of type long, which
-  on some 64-bit operating systems is still only 32 bits long.
-
-  (Contributed by Benjamin Peterson; :issue:`9778`.)
-
+* Hash values are now values of a new type, :c:type:`Py_hash_t`, which is
+  defined to be the same size as a pointer.  Previously they were of type long,
+  which on some 64-bit operating systems is still only 32 bits long.  As a
+  result of this fix, :class:`set` and :class:`dict` can now hold more than
+  ``2**32`` entries on builds with 64-bit pointers (previously, they could grow
+  to that size but their performance degraded catastrophically).
+
+  (Suggested by Raymond Hettinger and implemented by Benjamin Peterson;
+  :issue:`9778`.)
+
+* A new macro :c:macro:`Py_VA_COPY` copies the state of the variable argument
+  list.  It is equivalent to C99 *va_copy* but available on all Python platforms
+  (:issue:`2443`).
+
+* A new C API function :c:func:`PySys_SetArgvEx` allows an embedded interpreter
+  to set :attr:`sys.argv` without also modifying :attr:`sys.path`
+  (:issue:`5753`).
+
+* :c:macro:`PyEval_CallObject` is now only available in macro form.  The
+  function declaration, which was kept for backwards compatibility reasons, is
+  now removed -- the macro was introduced in 1997 (:issue:`8276`).
+
+* There is a new function :c:func:`PyLong_AsLongLongAndOverflow` which
+  is analogous to :c:func:`PyLong_AsLongAndOverflow`.  They both serve to
+  convert Python :class:`int` into a native fixed-width type while providing
+  detection of cases where the conversion won't fit (:issue:`7767`).
+
+* The :c:func:`PyUnicode_CompareWithASCIIString` function now returns *not
+  equal* if the Python string is *NUL* terminated.
+
+* There is a new function :c:func:`PyErr_NewExceptionWithDoc` that is
+  like :c:func:`PyErr_NewException` but allows a docstring to be specified.
+  This lets C exceptions have the same self-documenting capabilities as
+  their pure Python counterparts (:issue:`7033`).
+
+* When compiled with the ``--with-valgrind`` option, the pymalloc
+  allocator will be automatically disabled when running under Valgrind.  This
+  gives improved memory leak detection when running under Valgrind, while taking
+  advantage of pymalloc at other times (:issue:`2422`).
+
+* Removed the ``O?`` format from the *PyArg_Parse* functions.  The format is no
+  longer used and it had never been documented (:issue:`8837`).
+
+There were a number of other small changes to the C-API.  See the
+:source:`Misc/NEWS` file for a complete list.
+
+Also, there were a number of updates to the Mac OS X build, see
+:source:`Mac/BuildScript/README.txt` for details.  For users running a 32/64-bit
+build, there is a known problem with the default Tcl/Tk on Mac OS X 10.6.
+Accordingly, we recommend installing an updated alternative such as
+`ActiveState Tcl/Tk 8.5.9 <http://www.activestate.com/activetcl/downloads>`_\.
+See http://www.python.org/download/mac/tcltk/ for additional details.
 
 Porting to Python 3.2
 =====================
@@ -693,13 +2570,48 @@
 This section lists previously described changes and other bugfixes that may
 require changes to your code:
 
+* The :mod:`configparser` module has a number of clean-ups.  The major change is
+  to replace the old :class:`ConfigParser` class with long-standing preferred
+  alternative :class:`SafeConfigParser`.  In addition there are a number of
+  smaller incompatibilities:
+
+  * The interpolation syntax is now validated on
+    :meth:`~configparser.ConfigParser.get` and
+    :meth:`~configparser.ConfigParser.set` operations. In the default
+    interpolation scheme, only two tokens with percent signs are valid: ``%(name)s``
+    and ``%%``, the latter being an escaped percent sign.
+
+  * The :meth:`~configparser.ConfigParser.set` and
+    :meth:`~configparser.ConfigParser.add_section` methods now verify that
+    values are actual strings.  Formerly, unsupported types could be introduced
+    unintentionally.
+
+  * Duplicate sections or options from a single source now raise either
+    :exc:`~configparser.DuplicateSectionError` or
+    :exc:`~configparser.DuplicateOptionError`.  Formerly, duplicates would
+    silently overwrite a previous entry.
+
+  * Inline comments are now disabled by default so now the **;** character
+    can be safely used in values.
+
+  * Comments now can be indented.  Consequently, for **;** or **#** to appear at
+    the start of a line in multiline values, it has to be interpolated.  This
+    keeps comment prefix characters in values from being mistaken as comments.
+
+  * ``""`` is now a valid value and is no longer automatically converted to an
+    empty string. For empty strings, use ``"option ="`` in a line.
+
 * The :mod:`nntplib` module was reworked extensively, meaning that its APIs
   are often incompatible with the 3.1 APIs.
 
-* :class:`bytearray` objects cannot be used anymore as filenames: convert them
-  to :class:`bytes`.
+* :class:`bytearray` objects can no longer be used as filenames; instead,
+  they should be converted to :class:`bytes`.
+
+* The :meth:`array.tostring` and :meth:`array.fromstring` have been renamed to
+  :meth:`array.tobytes` and :meth:`array.frombytes` for clarity.  The old names
+  have been deprecated. (See :issue:`8990`.)
 
-* PyArg_Parse*() functions:
+* ``PyArg_Parse*()`` functions:
 
   * "t#" format has been removed: use "s#" or "s*" instead
   * "w" and "w#" formats has been removed: use "w*" instead
@@ -709,4 +2621,80 @@
   instead; the new type has a well-defined interface for passing typing safety
   information and a less complicated signature for calling a destructor.
 
- * Remove sys.setfilesystemencoding() function: it was broken by design.
+* The :func:`sys.setfilesystemencoding` function was removed because
+  it had a flawed design.
+
+* The :func:`random.seed` function and method now salt string seeds with an
+  sha512 hash function.  To access the previous version of *seed* in order to
+  reproduce Python 3.1 sequences, set the *version* argument to *1*,
+  ``random.seed(s, version=1)``.
+
+* The previously deprecated :func:`string.maketrans` function has been removed
+  in favor of the static methods :meth:`bytes.maketrans` and
+  :meth:`bytearray.maketrans`.  This change solves the confusion around which
+  types were supported by the :mod:`string` module.  Now, :class:`str`,
+  :class:`bytes`, and :class:`bytearray` each have their own **maketrans** and
+  **translate** methods with intermediate translation tables of the appropriate
+  type.
+
+  (Contributed by Georg Brandl; :issue:`5675`.)
+
+* The previously deprecated :func:`contextlib.nested` function has been removed
+  in favor of a plain :keyword:`with` statement which can accept multiple
+  context managers.  The latter technique is faster (because it is built-in),
+  and it does a better job finalizing multiple context managers when one of them
+  raises an exception::
+
+    with open('mylog.txt') as infile, open('a.out', 'w') as outfile:
+        for line in infile:
+            if '<critical>' in line:
+                outfile.write(line)
+
+  (Contributed by Georg Brandl and Mattias Brändström;
+  `appspot issue 53094 <http://codereview.appspot.com/53094>`_.)
+
+* :func:`struct.pack` now only allows bytes for the ``s`` string pack code.
+  Formerly, it would accept text arguments and implicitly encode them to bytes
+  using UTF-8.  This was problematic because it made assumptions about the
+  correct encoding and because a variable-length encoding can fail when writing
+  to fixed length segment of a structure.
+
+  Code such as ``struct.pack('<6sHHBBB', 'GIF87a', x, y)`` should be rewritten
+  with to use bytes instead of text, ``struct.pack('<6sHHBBB', b'GIF87a', x, y)``.
+
+  (Discovered by David Beazley and fixed by Victor Stinner; :issue:`10783`.)
+
+* The :class:`xml.etree.ElementTree` class now raises an
+  :exc:`xml.etree.ElementTree.ParseError` when a parse fails. Previously it
+  raised a :exc:`xml.parsers.expat.ExpatError`.
+
+* The new, longer :func:`str` value on floats may break doctests which rely on
+  the old output format.
+
+* In :class:`subprocess.Popen`, the default value for *close_fds* is now
+  ``True`` under Unix; under Windows, it is ``True`` if the three standard
+  streams are set to ``None``, ``False`` otherwise.  Previously, *close_fds*
+  was always ``False`` by default, which produced difficult to solve bugs
+  or race conditions when open file descriptors would leak into the child
+  process.
+
+* Support for legacy HTTP 0.9 has been removed from :mod:`urllib.request`
+  and :mod:`http.client`.  Such support is still present on the server side
+  (in :mod:`http.server`).
+
+  (Contributed by Antoine Pitrou, :issue:`10711`.)
+
+* SSL sockets in timeout mode now raise :exc:`socket.timeout` when a timeout
+  occurs, rather than a generic :exc:`~ssl.SSLError`.
+
+  (Contributed by Antoine Pitrou, :issue:`10272`.)
+
+* The misleading functions :c:func:`PyEval_AcquireLock()` and
+  :c:func:`PyEval_ReleaseLock()` have been officially deprecated.  The
+  thread-state aware APIs (such as :c:func:`PyEval_SaveThread()`
+  and :c:func:`PyEval_RestoreThread()`) should be used instead.
+
+* Due to security risks, :func:`asyncore.handle_accept` has been deprecated, and
+  a new function, :func:`asyncore.handle_accepted`, was added to replace it.
+
+  (Contributed by Giampaolo Rodola in :issue:`6706`.)

Modified: python/branches/pep-3151/Doc/whatsnew/index.rst
==============================================================================
--- python/branches/pep-3151/Doc/whatsnew/index.rst	(original)
+++ python/branches/pep-3151/Doc/whatsnew/index.rst	Sat Feb 26 08:16:32 2011
@@ -11,6 +11,7 @@
 .. toctree::
    :maxdepth: 2
 
+   3.3.rst
    3.2.rst
    3.1.rst
    3.0.rst

Modified: python/branches/pep-3151/Include/Python.h
==============================================================================
--- python/branches/pep-3151/Include/Python.h	(original)
+++ python/branches/pep-3151/Include/Python.h	Sat Feb 26 08:16:32 2011
@@ -66,6 +66,7 @@
 
 #include "object.h"
 #include "objimpl.h"
+#include "typeslots.h"
 
 #include "pydebug.h"
 
@@ -98,6 +99,8 @@
 #include "descrobject.h"
 #include "warnings.h"
 #include "weakrefobject.h"
+#include "structseq.h"
+
 
 #include "codecs.h"
 #include "pyerrors.h"
@@ -129,7 +132,9 @@
 #endif
 
 /* _Py_Mangle is defined in compile.c */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) _Py_Mangle(PyObject *p, PyObject *name);
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/abstract.h
==============================================================================
--- python/branches/pep-3151/Include/abstract.h	(original)
+++ python/branches/pep-3151/Include/abstract.h	Sat Feb 26 08:16:32 2011
@@ -387,7 +387,9 @@
      PyAPI_FUNC(Py_ssize_t) PyObject_Length(PyObject *o);
 #define PyObject_Length PyObject_Size
 
+#ifndef Py_LIMITED_API
      PyAPI_FUNC(Py_ssize_t) _PyObject_LengthHint(PyObject *o, Py_ssize_t);
+#endif
 
        /*
      Guess the size of object o using len(o) or o.__length_hint__().
@@ -486,6 +488,7 @@
 
     /* new buffer API */
 
+#ifndef Py_LIMITED_API
 #define PyObject_CheckBuffer(obj) \
     (((obj)->ob_type->tp_as_buffer != NULL) &&  \
      ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL))
@@ -573,6 +576,7 @@
 
        /* Releases a Py_buffer obtained from getbuffer ParseTuple's s*.
     */
+#endif /* Py_LIMITED_API */
 
      PyAPI_FUNC(PyObject *) PyObject_Format(PyObject* obj,
                                             PyObject *format_spec);
@@ -765,9 +769,11 @@
      that can accept a char* naming integral's type.
        */
 
+#ifndef Py_LIMITED_API
      PyAPI_FUNC(PyObject *) _PyNumber_ConvertIntegralToInt(
          PyObject *integral,
          const char* error_format);
+#endif
 
        /*
     Returns the object converted to Py_ssize_t by going through
@@ -1057,11 +1063,13 @@
      Use __contains__ if possible, else _PySequence_IterSearch().
        */
 
+#ifndef Py_LIMITED_API
 #define PY_ITERSEARCH_COUNT    1
 #define PY_ITERSEARCH_INDEX    2
 #define PY_ITERSEARCH_CONTAINS 3
      PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq,
                                         PyObject *obj, int operation);
+#endif
     /*
       Iterate over seq.  Result depends on the operation:
       PY_ITERSEARCH_COUNT:  return # of times obj appears in seq; -1 if
@@ -1228,6 +1236,7 @@
       /* issubclass(object, typeorclass) */
 
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PyObject_RealIsInstance(PyObject *inst, PyObject *cls);
 
 PyAPI_FUNC(int) _PyObject_RealIsSubclass(PyObject *derived, PyObject *cls);
@@ -1235,6 +1244,7 @@
 PyAPI_FUNC(char *const *) _PySequence_BytesToCharpArray(PyObject* self);
 
 PyAPI_FUNC(void) _Py_FreeCharPArray(char *const array[]);
+#endif
 
 /* For internal use by buffer API functions */
 PyAPI_FUNC(void) _Py_add_one_to_index_F(int nd, Py_ssize_t *index,

Modified: python/branches/pep-3151/Include/ast.h
==============================================================================
--- python/branches/pep-3151/Include/ast.h	(original)
+++ python/branches/pep-3151/Include/ast.h	Sat Feb 26 08:16:32 2011
@@ -4,8 +4,11 @@
 extern "C" {
 #endif
 
-PyAPI_FUNC(mod_ty) PyAST_FromNode(const node *, PyCompilerFlags *flags,
-				  const char *, PyArena *);
+PyAPI_FUNC(mod_ty) PyAST_FromNode(
+    const node *n,
+    PyCompilerFlags *flags,
+    const char *filename,       /* decoded from the filesystem encoding */
+    PyArena *arena);
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/bytearrayobject.h
==============================================================================
--- python/branches/pep-3151/Include/bytearrayobject.h	(original)
+++ python/branches/pep-3151/Include/bytearrayobject.h	Sat Feb 26 08:16:32 2011
@@ -19,6 +19,7 @@
  */
 
 /* Object layout */
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_VAR_HEAD
     /* XXX(nnorwitz): should ob_exports be Py_ssize_t? */
@@ -26,6 +27,7 @@
     Py_ssize_t ob_alloc; /* How many bytes allocated */
     char *ob_bytes;
 } PyByteArrayObject;
+#endif
 
 /* Type object */
 PyAPI_DATA(PyTypeObject) PyByteArray_Type;
@@ -44,12 +46,14 @@
 PyAPI_FUNC(int) PyByteArray_Resize(PyObject *, Py_ssize_t);
 
 /* Macros, trading safety for speed */
+#ifndef Py_LIMITED_API
 #define PyByteArray_AS_STRING(self) \
     (assert(PyByteArray_Check(self)), \
      Py_SIZE(self) ? ((PyByteArrayObject *)(self))->ob_bytes : _PyByteArray_empty_string)
 #define PyByteArray_GET_SIZE(self)  (assert(PyByteArray_Check(self)),Py_SIZE(self))
 
 PyAPI_DATA(char) _PyByteArray_empty_string[];
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/bytes_methods.h
==============================================================================
--- python/branches/pep-3151/Include/bytes_methods.h	(original)
+++ python/branches/pep-3151/Include/bytes_methods.h	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,4 @@
+#ifndef Py_LIMITED_API
 #ifndef Py_BYTES_CTYPE_H
 #define Py_BYTES_CTYPE_H
 
@@ -42,3 +43,4 @@
 #define PyDoc_STRVAR_shared(name,str) const char name[] = PyDoc_STR(str)
 
 #endif /* !Py_BYTES_CTYPE_H */
+#endif /* !Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/bytesobject.h
==============================================================================
--- python/branches/pep-3151/Include/bytesobject.h	(original)
+++ python/branches/pep-3151/Include/bytesobject.h	Sat Feb 26 08:16:32 2011
@@ -27,6 +27,7 @@
 /* Caching the hash (ob_shash) saves recalculation of a string's hash value.
    This significantly speeds up dict lookups. */
 
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_VAR_HEAD
     Py_hash_t ob_shash;
@@ -38,6 +39,7 @@
      *     ob_shash is the hash of the string or -1 if not computed yet.
      */
 } PyBytesObject;
+#endif
 
 PyAPI_DATA(PyTypeObject) PyBytes_Type;
 PyAPI_DATA(PyTypeObject) PyBytesIter_Type;
@@ -58,21 +60,27 @@
 PyAPI_FUNC(PyObject *) PyBytes_Repr(PyObject *, int);
 PyAPI_FUNC(void) PyBytes_Concat(PyObject **, PyObject *);
 PyAPI_FUNC(void) PyBytes_ConcatAndDel(PyObject **, PyObject *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PyBytes_Resize(PyObject **, Py_ssize_t);
 PyAPI_FUNC(PyObject *) _PyBytes_FormatLong(PyObject*, int, int,
 						  int, char**, int*);
+#endif
 PyAPI_FUNC(PyObject *) PyBytes_DecodeEscape(const char *, Py_ssize_t,
 						   const char *, Py_ssize_t,
 						   const char *);
 
 /* Macro, trading safety for speed */
+#ifndef Py_LIMITED_API
 #define PyBytes_AS_STRING(op) (assert(PyBytes_Check(op)), \
                                 (((PyBytesObject *)(op))->ob_sval))
 #define PyBytes_GET_SIZE(op)  (assert(PyBytes_Check(op)),Py_SIZE(op))
+#endif
 
 /* _PyBytes_Join(sep, x) is like sep.join(x).  sep must be PyBytesObject*,
    x must be an iterable object. */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyBytes_Join(PyObject *sep, PyObject *x);
+#endif
 
 /* Provides access to the internal data buffer and size of a string
    object or the default encoded version of an Unicode object. Passing
@@ -90,7 +98,7 @@
 /* Using the current locale, insert the thousands grouping
    into the string pointed to by buffer.  For the argument descriptions,
    see Objects/stringlib/localeutil.h */
-
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(Py_ssize_t) _PyBytes_InsertThousandsGroupingLocale(char *buffer,
                                                    Py_ssize_t n_buffer,
                                                    char *digits,
@@ -107,6 +115,7 @@
                                                    Py_ssize_t min_width,
                                                    const char *grouping,
                                                    const char *thousands_sep);
+#endif
 
 /* Flags used by string formatting */
 #define F_LJUST (1<<0)

Modified: python/branches/pep-3151/Include/cellobject.h
==============================================================================
--- python/branches/pep-3151/Include/cellobject.h	(original)
+++ python/branches/pep-3151/Include/cellobject.h	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,5 @@
 /* Cell object interface */
-
+#ifndef Py_LIMITED_API
 #ifndef Py_CELLOBJECT_H
 #define Py_CELLOBJECT_H
 #ifdef __cplusplus
@@ -26,3 +26,4 @@
 }
 #endif
 #endif /* !Py_TUPLEOBJECT_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/ceval.h
==============================================================================
--- python/branches/pep-3151/Include/ceval.h	(original)
+++ python/branches/pep-3151/Include/ceval.h	Sat Feb 26 08:16:32 2011
@@ -20,8 +20,10 @@
                                          const char *methodname,
                                          const char *format, ...);
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void) PyEval_SetProfile(Py_tracefunc, PyObject *);
 PyAPI_FUNC(void) PyEval_SetTrace(Py_tracefunc, PyObject *);
+#endif
 
 struct _frame; /* Avoid including frameobject.h */
 
@@ -33,7 +35,9 @@
 /* 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
    flag was set, else return 0. */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) PyEval_MergeCompilerFlags(PyCompilerFlags *cf);
+#endif
 
 PyAPI_FUNC(int) Py_AddPendingCall(int (*func)(void *), void *arg);
 PyAPI_FUNC(int) Py_MakePendingCalls(void);
@@ -167,8 +171,10 @@
 PyAPI_FUNC(void) PyEval_ReleaseThread(PyThreadState *tstate);
 PyAPI_FUNC(void) PyEval_ReInitThreads(void);
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void) _PyEval_SetSwitchInterval(unsigned long microseconds);
 PyAPI_FUNC(unsigned long) _PyEval_GetSwitchInterval(void);
+#endif
 
 #define Py_BEGIN_ALLOW_THREADS { \
                         PyThreadState *_save; \
@@ -187,8 +193,10 @@
 
 #endif /* !WITH_THREAD */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PyEval_SliceIndex(PyObject *, Py_ssize_t *);
 PyAPI_FUNC(void) _PyEval_SignalAsyncExc(void);
+#endif
 
 
 #ifdef __cplusplus

Modified: python/branches/pep-3151/Include/classobject.h
==============================================================================
--- python/branches/pep-3151/Include/classobject.h	(original)
+++ python/branches/pep-3151/Include/classobject.h	Sat Feb 26 08:16:32 2011
@@ -2,6 +2,7 @@
 
 /* Revealing some structures (not for general use) */
 
+#ifndef Py_LIMITED_API
 #ifndef Py_CLASSOBJECT_H
 #define Py_CLASSOBJECT_H
 #ifdef __cplusplus
@@ -54,3 +55,4 @@
 }
 #endif
 #endif /* !Py_CLASSOBJECT_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/code.h
==============================================================================
--- python/branches/pep-3151/Include/code.h	(original)
+++ python/branches/pep-3151/Include/code.h	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,6 @@
 /* Definitions for bytecode */
 
+#ifndef Py_LIMITED_API
 #ifndef Py_CODE_H
 #define Py_CODE_H
 #ifdef __cplusplus
@@ -93,8 +94,10 @@
 /* Update *bounds to describe the first and one-past-the-last instructions in the
    same line as lasti.  Return the number of that line.
 */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PyCode_CheckLineNumber(PyCodeObject* co,
                                         int lasti, PyAddrPair *bounds);
+#endif
 
 PyAPI_FUNC(PyObject*) PyCode_Optimize(PyObject *code, PyObject* consts,
                                       PyObject *names, PyObject *lineno_obj);
@@ -103,3 +106,4 @@
 }
 #endif
 #endif /* !Py_CODE_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/codecs.h
==============================================================================
--- python/branches/pep-3151/Include/codecs.h	(original)
+++ python/branches/pep-3151/Include/codecs.h	Sat Feb 26 08:16:32 2011
@@ -45,9 +45,11 @@
 
  */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyCodec_Lookup(
        const char *encoding
        );
+#endif
 
 /* Codec registry encoding check API.
 
@@ -144,7 +146,7 @@
 
 /* Unicode encoding error handling callback registry API */
 
-/* Register the error handling callback function error under the name
+/* Register the error handling callback function error under the given
    name. This function will be called by the codec when it encounters
    unencodable characters/undecodable bytes and doesn't know the
    callback name, when name is specified as the error parameter
@@ -152,8 +154,8 @@
    Return 0 on success, -1 on error */
 PyAPI_FUNC(int) PyCodec_RegisterError(const char *name, PyObject *error);
 
-/* Lookup the error handling callback function registered under the
-   name error. As a special case NULL can be passed, in which case
+/* Lookup the error handling callback function registered under the given
+   name. As a special case NULL can be passed, in which case
    the error handling callback for "strict" will be returned. */
 PyAPI_FUNC(PyObject *) PyCodec_LookupError(const char *name);
 
@@ -163,7 +165,7 @@
 /* ignore the unicode error, skipping the faulty input */
 PyAPI_FUNC(PyObject *) PyCodec_IgnoreErrors(PyObject *exc);
 
-/* replace the unicode error with ? or U+FFFD */
+/* replace the unicode encode error with ? or U+FFFD */
 PyAPI_FUNC(PyObject *) PyCodec_ReplaceErrors(PyObject *exc);
 
 /* replace the unicode encode error with XML character references */

Modified: python/branches/pep-3151/Include/compile.h
==============================================================================
--- python/branches/pep-3151/Include/compile.h	(original)
+++ python/branches/pep-3151/Include/compile.h	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,4 @@
-
+#ifndef Py_LIMITED_API
 #ifndef Py_COMPILE_H
 #define Py_COMPILE_H
 
@@ -29,8 +29,13 @@
 #define FUTURE_BARRY_AS_BDFL "barry_as_FLUFL"
 
 struct _mod; /* Declare the existence of this type */
-PyAPI_FUNC(PyCodeObject *) PyAST_Compile(struct _mod *, const char *,
-					PyCompilerFlags *, PyArena *);
+#define PyAST_Compile(mod, s, f, ar) PyAST_CompileEx(mod, s, f, -1, ar)
+PyAPI_FUNC(PyCodeObject *) PyAST_CompileEx(
+    struct _mod *mod,
+    const char *filename,       /* decoded from the filesystem encoding */
+    PyCompilerFlags *flags,
+    int optimize,
+    PyArena *arena);
 PyAPI_FUNC(PyFutureFeatures *) PyFuture_FromAST(struct _mod *, const char *);
 
 
@@ -38,3 +43,4 @@
 }
 #endif
 #endif /* !Py_COMPILE_H */
+#endif /* !Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/complexobject.h
==============================================================================
--- python/branches/pep-3151/Include/complexobject.h	(original)
+++ python/branches/pep-3151/Include/complexobject.h	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,7 @@
 extern "C" {
 #endif
 
+#ifndef Py_LIMITED_API
 typedef struct {
     double real;
     double imag;
@@ -28,7 +29,7 @@
 PyAPI_FUNC(Py_complex) c_quot(Py_complex, Py_complex);
 PyAPI_FUNC(Py_complex) c_pow(Py_complex, Py_complex);
 PyAPI_FUNC(double) c_abs(Py_complex);
-
+#endif
 
 /* Complex object interface */
 
@@ -36,29 +37,36 @@
 PyComplexObject represents a complex number with double-precision
 real and imaginary parts.
 */
-
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_HEAD
     Py_complex cval;
-} PyComplexObject;     
+} PyComplexObject;
+#endif
 
 PyAPI_DATA(PyTypeObject) PyComplex_Type;
 
 #define PyComplex_Check(op) PyObject_TypeCheck(op, &PyComplex_Type)
 #define PyComplex_CheckExact(op) (Py_TYPE(op) == &PyComplex_Type)
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyComplex_FromCComplex(Py_complex);
+#endif
 PyAPI_FUNC(PyObject *) PyComplex_FromDoubles(double real, double imag);
 
 PyAPI_FUNC(double) PyComplex_RealAsDouble(PyObject *op);
 PyAPI_FUNC(double) PyComplex_ImagAsDouble(PyObject *op);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(Py_complex) PyComplex_AsCComplex(PyObject *op);
+#endif
 
 /* Format the object based on the format_spec, as defined in PEP 3101
    (Advanced String Formatting). */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyComplex_FormatAdvanced(PyObject *obj,
                                                  Py_UNICODE *format_spec,
                                                  Py_ssize_t format_spec_len);
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/datetime.h
==============================================================================
--- python/branches/pep-3151/Include/datetime.h	(original)
+++ python/branches/pep-3151/Include/datetime.h	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
 /*  datetime.h
  */
-
+#ifndef Py_LIMITED_API
 #ifndef DATETIME_H
 #define DATETIME_H
 #ifdef __cplusplus
@@ -234,3 +234,4 @@
 }
 #endif
 #endif
+#endif /* !Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/descrobject.h
==============================================================================
--- python/branches/pep-3151/Include/descrobject.h	(original)
+++ python/branches/pep-3151/Include/descrobject.h	Sat Feb 26 08:16:32 2011
@@ -16,6 +16,7 @@
     void *closure;
 } PyGetSetDef;
 
+#ifndef Py_LIMITED_API
 typedef PyObject *(*wrapperfunc)(PyObject *self, PyObject *args,
                                  void *wrapped);
 
@@ -68,6 +69,7 @@
     struct wrapperbase *d_base;
     void *d_wrapped; /* This can be any function pointer */
 } PyWrapperDescrObject;
+#endif /* Py_LIMITED_API */
 
 PyAPI_DATA(PyTypeObject) PyClassMethodDescr_Type;
 PyAPI_DATA(PyTypeObject) PyGetSetDescr_Type;
@@ -78,13 +80,16 @@
 
 PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *);
 PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *);
+struct PyMemberDef; /* forward declaration for following prototype */
 PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *,
                                                struct PyMemberDef *);
 PyAPI_FUNC(PyObject *) PyDescr_NewGetSet(PyTypeObject *,
                                                struct PyGetSetDef *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyDescr_NewWrapper(PyTypeObject *,
                                                 struct wrapperbase *, void *);
 #define PyDescr_IsData(d) (Py_TYPE(d)->tp_descr_set != NULL)
+#endif
 
 PyAPI_FUNC(PyObject *) PyDictProxy_New(PyObject *);
 PyAPI_FUNC(PyObject *) PyWrapper_New(PyObject *, PyObject *);

Modified: python/branches/pep-3151/Include/dictobject.h
==============================================================================
--- python/branches/pep-3151/Include/dictobject.h	(original)
+++ python/branches/pep-3151/Include/dictobject.h	Sat Feb 26 08:16:32 2011
@@ -45,6 +45,7 @@
  * majority of dicts (consisting mostly of usually-small instance dicts and
  * usually-small dicts created to pass keyword arguments).
  */
+#ifndef Py_LIMITED_API
 #define PyDict_MINSIZE 8
 
 typedef struct {
@@ -84,6 +85,7 @@
     PyDictEntry *(*ma_lookup)(PyDictObject *mp, PyObject *key, Py_hash_t hash);
     PyDictEntry ma_smalltable[PyDict_MINSIZE];
 };
+#endif /* Py_LIMITED_API */
 
 PyAPI_DATA(PyTypeObject) PyDict_Type;
 PyAPI_DATA(PyTypeObject) PyDictIterKey_Type;
@@ -112,18 +114,22 @@
 PyAPI_FUNC(void) PyDict_Clear(PyObject *mp);
 PyAPI_FUNC(int) PyDict_Next(
     PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PyDict_Next(
     PyObject *mp, Py_ssize_t *pos, PyObject **key, PyObject **value, Py_hash_t *hash);
+#endif
 PyAPI_FUNC(PyObject *) PyDict_Keys(PyObject *mp);
 PyAPI_FUNC(PyObject *) PyDict_Values(PyObject *mp);
 PyAPI_FUNC(PyObject *) PyDict_Items(PyObject *mp);
 PyAPI_FUNC(Py_ssize_t) PyDict_Size(PyObject *mp);
 PyAPI_FUNC(PyObject *) PyDict_Copy(PyObject *mp);
 PyAPI_FUNC(int) PyDict_Contains(PyObject *mp, PyObject *key);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PyDict_Contains(PyObject *mp, PyObject *key, Py_hash_t hash);
 PyAPI_FUNC(PyObject *) _PyDict_NewPresized(Py_ssize_t minused);
 PyAPI_FUNC(void) _PyDict_MaybeUntrack(PyObject *mp);
 PyAPI_FUNC(int) _PyDict_HasOnlyStringKeys(PyObject *mp);
+#endif
 
 /* PyDict_Update(mp, other) is equivalent to PyDict_Merge(mp, other, 1). */
 PyAPI_FUNC(int) PyDict_Update(PyObject *mp, PyObject *other);

Modified: python/branches/pep-3151/Include/dtoa.h
==============================================================================
--- python/branches/pep-3151/Include/dtoa.h	(original)
+++ python/branches/pep-3151/Include/dtoa.h	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,4 @@
+#ifndef Py_LIMITED_API
 #ifndef PY_NO_SHORT_FLOAT_REPR
 #ifdef __cplusplus
 extern "C" {
@@ -13,3 +14,4 @@
 }
 #endif
 #endif
+#endif

Modified: python/branches/pep-3151/Include/eval.h
==============================================================================
--- python/branches/pep-3151/Include/eval.h	(original)
+++ python/branches/pep-3151/Include/eval.h	Sat Feb 26 08:16:32 2011
@@ -7,9 +7,9 @@
 extern "C" {
 #endif
 
-PyAPI_FUNC(PyObject *) PyEval_EvalCode(PyCodeObject *, PyObject *, PyObject *);
+PyAPI_FUNC(PyObject *) PyEval_EvalCode(PyObject *, PyObject *, PyObject *);
 
-PyAPI_FUNC(PyObject *) PyEval_EvalCodeEx(PyCodeObject *co,
+PyAPI_FUNC(PyObject *) PyEval_EvalCodeEx(PyObject *co,
 					PyObject *globals,
 					PyObject *locals,
 					PyObject **args, int argc,
@@ -17,7 +17,9 @@
 					PyObject **defs, int defc,
 					PyObject *kwdefs, PyObject *closure);
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyEval_CallTracing(PyObject *func, PyObject *args);
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/fileobject.h
==============================================================================
--- python/branches/pep-3151/Include/fileobject.h	(original)
+++ python/branches/pep-3151/Include/fileobject.h	Sat Feb 26 08:16:32 2011
@@ -14,7 +14,9 @@
 PyAPI_FUNC(int) PyFile_WriteObject(PyObject *, PyObject *, int);
 PyAPI_FUNC(int) PyFile_WriteString(const char *, PyObject *);
 PyAPI_FUNC(int) PyObject_AsFileDescriptor(PyObject *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(char *) Py_UniversalNewlineFgets(char *, int, FILE*, PyObject *);
+#endif
 
 /* The default encoding used by the platform file system APIs
    If non-NULL, this is different than the default encoding for strings
@@ -26,6 +28,7 @@
 
    The std printer acts as a preliminary sys.stderr until the new io
    infrastructure is in place. */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyFile_NewStdPrinter(int);
 PyAPI_DATA(PyTypeObject) PyStdPrinter_Type;
 
@@ -39,6 +42,7 @@
 #else
 #define _PyVerify_fd(A) (1) /* dummy */
 #endif
+#endif /* Py_LIMITED_API */
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/floatobject.h
==============================================================================
--- python/branches/pep-3151/Include/floatobject.h	(original)
+++ python/branches/pep-3151/Include/floatobject.h	Sat Feb 26 08:16:32 2011
@@ -11,10 +11,12 @@
 extern "C" {
 #endif
 
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_HEAD
     double ob_fval;
 } PyFloatObject;
+#endif
 
 PyAPI_DATA(PyTypeObject) PyFloat_Type;
 
@@ -45,8 +47,11 @@
 /* Extract C double from Python float.  The macro version trades safety for
    speed. */
 PyAPI_FUNC(double) PyFloat_AsDouble(PyObject *);
+#ifndef Py_LIMITED_API
 #define PyFloat_AS_DOUBLE(op) (((PyFloatObject *)(op))->ob_fval)
+#endif
 
+#ifndef Py_LIMITED_API
 /* _PyFloat_{Pack,Unpack}{4,8}
  *
  * The struct and pickle (at least) modules need an efficient platform-
@@ -110,6 +115,7 @@
 PyAPI_FUNC(PyObject *) _PyFloat_FormatAdvanced(PyObject *obj,
 					       Py_UNICODE *format_spec,
 					       Py_ssize_t format_spec_len);
+#endif /* Py_LIMITED_API */
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/frameobject.h
==============================================================================
--- python/branches/pep-3151/Include/frameobject.h	(original)
+++ python/branches/pep-3151/Include/frameobject.h	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,7 @@
 
 /* Frame object interface */
 
+#ifndef Py_LIMITED_API
 #ifndef Py_FRAMEOBJECT_H
 #define Py_FRAMEOBJECT_H
 #ifdef __cplusplus
@@ -85,3 +86,4 @@
 }
 #endif
 #endif /* !Py_FRAMEOBJECT_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/funcobject.h
==============================================================================
--- python/branches/pep-3151/Include/funcobject.h	(original)
+++ python/branches/pep-3151/Include/funcobject.h	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
 
 /* Function object interface */
-
+#ifndef Py_LIMITED_API
 #ifndef Py_FUNCOBJECT_H
 #define Py_FUNCOBJECT_H
 #ifdef __cplusplus
@@ -84,3 +84,4 @@
 }
 #endif
 #endif /* !Py_FUNCOBJECT_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/genobject.h
==============================================================================
--- python/branches/pep-3151/Include/genobject.h	(original)
+++ python/branches/pep-3151/Include/genobject.h	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,7 @@
 
 /* Generator object interface */
 
+#ifndef Py_LIMITED_API
 #ifndef Py_GENOBJECT_H
 #define Py_GENOBJECT_H
 #ifdef __cplusplus
@@ -38,3 +39,4 @@
 }
 #endif
 #endif /* !Py_GENOBJECT_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/import.h
==============================================================================
--- python/branches/pep-3151/Include/import.h	(original)
+++ python/branches/pep-3151/Include/import.h	Sat Feb 26 08:16:32 2011
@@ -9,27 +9,51 @@
 
 PyAPI_FUNC(long) PyImport_GetMagicNumber(void);
 PyAPI_FUNC(const char *) PyImport_GetMagicTag(void);
-PyAPI_FUNC(PyObject *) PyImport_ExecCodeModule(char *name, PyObject *co);
+PyAPI_FUNC(PyObject *) PyImport_ExecCodeModule(
+    char *name,                 /* UTF-8 encoded string */
+    PyObject *co
+    );
 PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleEx(
-	char *name, PyObject *co, char *pathname);
+    char *name,                 /* UTF-8 encoded string */
+    PyObject *co,
+    char *pathname              /* decoded from the filesystem encoding */
+    );
 PyAPI_FUNC(PyObject *) PyImport_ExecCodeModuleWithPathnames(
-	char *name, PyObject *co, char *pathname, char *cpathname);
+    char *name,                 /* UTF-8 encoded string */
+    PyObject *co,
+    char *pathname,             /* decoded from the filesystem encoding */
+    char *cpathname             /* decoded from the filesystem encoding */
+    );
 PyAPI_FUNC(PyObject *) PyImport_GetModuleDict(void);
-PyAPI_FUNC(PyObject *) PyImport_AddModule(const char *name);
-PyAPI_FUNC(PyObject *) PyImport_ImportModule(const char *name);
-PyAPI_FUNC(PyObject *) PyImport_ImportModuleNoBlock(const char *);
-PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevel(char *name,
-	PyObject *globals, PyObject *locals, PyObject *fromlist, int level);
+PyAPI_FUNC(PyObject *) PyImport_AddModule(
+    const char *name            /* UTF-8 encoded string */
+    );
+PyAPI_FUNC(PyObject *) PyImport_ImportModule(
+    const char *name            /* UTF-8 encoded string */
+    );
+PyAPI_FUNC(PyObject *) PyImport_ImportModuleNoBlock(
+    const char *name            /* UTF-8 encoded string */
+    );
+PyAPI_FUNC(PyObject *) PyImport_ImportModuleLevel(
+    char *name,                 /* UTF-8 encoded string */
+    PyObject *globals,
+    PyObject *locals,
+    PyObject *fromlist,
+    int level
+    );
 
 #define PyImport_ImportModuleEx(n, g, l, f) \
-	PyImport_ImportModuleLevel(n, g, l, f, -1)
+    PyImport_ImportModuleLevel(n, g, l, f, -1)
 
 PyAPI_FUNC(PyObject *) PyImport_GetImporter(PyObject *path);
 PyAPI_FUNC(PyObject *) PyImport_Import(PyObject *name);
 PyAPI_FUNC(PyObject *) PyImport_ReloadModule(PyObject *m);
 PyAPI_FUNC(void) PyImport_Cleanup(void);
-PyAPI_FUNC(int) PyImport_ImportFrozenModule(char *);
+PyAPI_FUNC(int) PyImport_ImportFrozenModule(
+    char *name                  /* UTF-8 encoded string */
+    );
 
+#ifndef Py_LIMITED_API
 #ifdef WITH_THREAD
 PyAPI_FUNC(void) _PyImport_AcquireLock(void);
 PyAPI_FUNC(int) _PyImport_ReleaseLock(void);
@@ -40,24 +64,34 @@
 
 PyAPI_FUNC(void) _PyImport_ReInitLock(void);
 
-PyAPI_FUNC(PyObject *)_PyImport_FindBuiltin(char *);
-PyAPI_FUNC(PyObject *)_PyImport_FindExtensionUnicode(char *, PyObject *);
-PyAPI_FUNC(int)_PyImport_FixupBuiltin(PyObject*, char *);
+PyAPI_FUNC(PyObject *)_PyImport_FindBuiltin(
+    const char *name            /* UTF-8 encoded string */
+    );
+PyAPI_FUNC(PyObject *)_PyImport_FindExtensionUnicode(const char *, PyObject *);
+PyAPI_FUNC(int)_PyImport_FixupBuiltin(
+    PyObject *mod,
+    char *name                  /* UTF-8 encoded string */
+    );
 PyAPI_FUNC(int)_PyImport_FixupExtensionUnicode(PyObject*, char *, PyObject *);
 
 struct _inittab {
     char *name;
     PyObject* (*initfunc)(void);
 };
+PyAPI_DATA(struct _inittab *) PyImport_Inittab;
+PyAPI_FUNC(int) PyImport_ExtendInittab(struct _inittab *newtab);
+#endif /* Py_LIMITED_API */
 
 PyAPI_DATA(PyTypeObject) PyNullImporter_Type;
-PyAPI_DATA(struct _inittab *) PyImport_Inittab;
 
-PyAPI_FUNC(int) PyImport_AppendInittab(const char *name, PyObject* (*initfunc)(void));
-PyAPI_FUNC(int) PyImport_ExtendInittab(struct _inittab *newtab);
+PyAPI_FUNC(int) PyImport_AppendInittab(
+    const char *name,           /* ASCII encoded string */
+    PyObject* (*initfunc)(void)
+    );
 
+#ifndef Py_LIMITED_API
 struct _frozen {
-    char *name;
+    char *name;                 /* ASCII encoded string */
     unsigned char *code;
     int size;
 };
@@ -66,6 +100,7 @@
    collection of frozen modules: */
 
 PyAPI_DATA(struct _frozen *) PyImport_FrozenModules;
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/listobject.h
==============================================================================
--- python/branches/pep-3151/Include/listobject.h	(original)
+++ python/branches/pep-3151/Include/listobject.h	Sat Feb 26 08:16:32 2011
@@ -19,6 +19,7 @@
 extern "C" {
 #endif
 
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_VAR_HEAD
     /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
@@ -37,6 +38,7 @@
      */
     Py_ssize_t allocated;
 } PyListObject;
+#endif
 
 PyAPI_DATA(PyTypeObject) PyList_Type;
 PyAPI_DATA(PyTypeObject) PyListIter_Type;
@@ -58,12 +60,16 @@
 PyAPI_FUNC(int) PyList_Sort(PyObject *);
 PyAPI_FUNC(int) PyList_Reverse(PyObject *);
 PyAPI_FUNC(PyObject *) PyList_AsTuple(PyObject *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyList_Extend(PyListObject *, PyObject *);
+#endif
 
 /* Macro, trading safety for speed */
+#ifndef Py_LIMITED_API
 #define PyList_GET_ITEM(op, i) (((PyListObject *)(op))->ob_item[i])
 #define PyList_SET_ITEM(op, i, v) (((PyListObject *)(op))->ob_item[i] = (v))
 #define PyList_GET_SIZE(op)    Py_SIZE(op)
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/longintrepr.h
==============================================================================
--- python/branches/pep-3151/Include/longintrepr.h	(original)
+++ python/branches/pep-3151/Include/longintrepr.h	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,4 @@
+#ifndef Py_LIMITED_API
 #ifndef Py_LONGINTREPR_H
 #define Py_LONGINTREPR_H
 #ifdef __cplusplus
@@ -99,3 +100,4 @@
 }
 #endif
 #endif /* !Py_LONGINTREPR_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/longobject.h
==============================================================================
--- python/branches/pep-3151/Include/longobject.h	(original)
+++ python/branches/pep-3151/Include/longobject.h	Sat Feb 26 08:16:32 2011
@@ -50,7 +50,9 @@
 #endif /* SIZEOF_PID_T */
 
 /* Used by Python/mystrtoul.c. */
+#ifndef Py_LIMITED_API
 PyAPI_DATA(unsigned char) _PyLong_DigitValue[256];
+#endif
 
 /* _PyLong_Frexp returns a double x and an exponent e such that the
    true value is approximately equal to x * 2**e.  e is >= 0.  x is
@@ -58,7 +60,9 @@
    zeroes); otherwise, 0.5 <= abs(x) < 1.0.  On overflow, which is
    possible if the number of bits doesn't fit into a Py_ssize_t, sets
    OverflowError and returns -1.0 for x, 0 for e. */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(double) _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e);
+#endif
 
 PyAPI_FUNC(double) PyLong_AsDouble(PyObject *);
 PyAPI_FUNC(PyObject *) PyLong_FromVoidPtr(void *);
@@ -74,8 +78,11 @@
 #endif /* HAVE_LONG_LONG */
 
 PyAPI_FUNC(PyObject *) PyLong_FromString(char *, char **, int);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyLong_FromUnicode(Py_UNICODE*, Py_ssize_t, int);
+#endif
 
+#ifndef Py_LIMITED_API
 /* _PyLong_Sign.  Return 0 if v is 0, -1 if v < 0, +1 if v > 0.
    v must not be NULL, and must be a normalized long.
    There are no error cases.
@@ -150,6 +157,7 @@
 PyAPI_FUNC(PyObject *) _PyLong_FormatAdvanced(PyObject *obj,
 					      Py_UNICODE *format_spec,
 					      Py_ssize_t format_spec_len);
+#endif /* Py_LIMITED_API */
 
 /* These aren't really part of the long object, but they're handy. The
    functions are in Python/mystrtoul.c.

Modified: python/branches/pep-3151/Include/marshal.h
==============================================================================
--- python/branches/pep-3151/Include/marshal.h	(original)
+++ python/branches/pep-3151/Include/marshal.h	Sat Feb 26 08:16:32 2011
@@ -13,10 +13,12 @@
 PyAPI_FUNC(void) PyMarshal_WriteObjectToFile(PyObject *, FILE *, int);
 PyAPI_FUNC(PyObject *) PyMarshal_WriteObjectToString(PyObject *, int);
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(long) PyMarshal_ReadLongFromFile(FILE *);
 PyAPI_FUNC(int) PyMarshal_ReadShortFromFile(FILE *);
 PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromFile(FILE *);
 PyAPI_FUNC(PyObject *) PyMarshal_ReadLastObjectFromFile(FILE *);
+#endif
 PyAPI_FUNC(PyObject *) PyMarshal_ReadObjectFromString(char *, Py_ssize_t);
 
 #ifdef __cplusplus

Modified: python/branches/pep-3151/Include/memoryobject.h
==============================================================================
--- python/branches/pep-3151/Include/memoryobject.h	(original)
+++ python/branches/pep-3151/Include/memoryobject.h	Sat Feb 26 08:16:32 2011
@@ -10,10 +10,12 @@
 
 #define PyMemoryView_Check(op) (Py_TYPE(op) == &PyMemoryView_Type)
 
+#ifndef Py_LIMITED_API
 /* Get a pointer to the underlying Py_buffer of a memoryview object. */
 #define PyMemoryView_GET_BUFFER(op) (&((PyMemoryViewObject *)(op))->view)
 /* Get a pointer to the PyObject from which originates a memoryview object. */
 #define PyMemoryView_GET_BASE(op) (((PyMemoryViewObject *)(op))->view.obj)
+#endif
 
 
 PyAPI_FUNC(PyObject *) PyMemoryView_GetContiguous(PyObject *base, 
@@ -53,19 +55,22 @@
 
 PyAPI_FUNC(PyObject *) PyMemoryView_FromObject(PyObject *base);
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyMemoryView_FromBuffer(Py_buffer *info);
     /* create new if bufptr is NULL 
         will be a new bytesobject in base */
+#endif
 
 
 /* The struct is declared here so that macros can work, but it shouldn't
    be considered public. Don't access those fields directly, use the macros
    and functions instead! */
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_HEAD
     Py_buffer view;
 } PyMemoryViewObject;
-
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/methodobject.h
==============================================================================
--- python/branches/pep-3151/Include/methodobject.h	(original)
+++ python/branches/pep-3151/Include/methodobject.h	Sat Feb 26 08:16:32 2011
@@ -26,12 +26,14 @@
 
 /* Macros for direct access to these values. Type checks are *not*
    done, so use with care. */
+#ifndef Py_LIMITED_API
 #define PyCFunction_GET_FUNCTION(func) \
         (((PyCFunctionObject *)func) -> m_ml -> ml_meth)
 #define PyCFunction_GET_SELF(func) \
 	(((PyCFunctionObject *)func) -> m_self)
 #define PyCFunction_GET_FLAGS(func) \
 	(((PyCFunctionObject *)func) -> m_ml -> ml_flags)
+#endif
 PyAPI_FUNC(PyObject *) PyCFunction_Call(PyObject *, PyObject *, PyObject *);
 
 struct PyMethodDef {
@@ -68,12 +70,14 @@
 
 #define METH_COEXIST   0x0040
 
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_HEAD
     PyMethodDef *m_ml; /* Description of the C function to call */
     PyObject    *m_self; /* Passed as 'self' arg to the C func, can be NULL */
     PyObject    *m_module; /* The __module__ attribute, can be anything */
 } PyCFunctionObject;
+#endif
 
 PyAPI_FUNC(int) PyCFunction_ClearFreeList(void);
 

Modified: python/branches/pep-3151/Include/modsupport.h
==============================================================================
--- python/branches/pep-3151/Include/modsupport.h	(original)
+++ python/branches/pep-3151/Include/modsupport.h	Sat Feb 26 08:16:32 2011
@@ -31,7 +31,9 @@
 PyAPI_FUNC(int) PyArg_UnpackTuple(PyObject *, const char *, Py_ssize_t, Py_ssize_t, ...);
 PyAPI_FUNC(PyObject *) Py_BuildValue(const char *, ...);
 PyAPI_FUNC(PyObject *) _Py_BuildValue_SizeT(const char *, ...);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PyArg_NoKeywords(const char *funcname, PyObject *kw);
+#endif
 
 PyAPI_FUNC(int) PyArg_VaParse(PyObject *, const char *, va_list);
 PyAPI_FUNC(int) PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *,
@@ -92,6 +94,12 @@
    9-Jan-1995	GvR	Initial version (incompatible with older API)
 */
 
+/* The PYTHON_ABI_VERSION is introduced in PEP 384. For the lifetime of
+   Python 3, it will stay at the value of 3; changes to the limited API
+   must be performed in a strictly backwards-compatible manner. */
+#define PYTHON_ABI_VERSION 3
+#define PYTHON_ABI_STRING "3"
+
 #ifdef Py_TRACE_REFS
  /* When we are tracing reference counts, rename PyModule_Create2 so
     modules compiled with incompatible settings will generate a
@@ -102,10 +110,17 @@
 PyAPI_FUNC(PyObject *) PyModule_Create2(struct PyModuleDef*,
                                      int apiver);
 
+#ifdef Py_LIMITED_API
+#define PyModule_Create(module) \
+	PyModule_Create2(module, PYTHON_ABI_VERSION)
+#else
 #define PyModule_Create(module) \
 	PyModule_Create2(module, PYTHON_API_VERSION)
+#endif
 
+#ifndef Py_LIMITED_API
 PyAPI_DATA(char *) _Py_PackageContext;
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/moduleobject.h
==============================================================================
--- python/branches/pep-3151/Include/moduleobject.h	(original)
+++ python/branches/pep-3151/Include/moduleobject.h	Sat Feb 26 08:16:32 2011
@@ -12,12 +12,17 @@
 #define PyModule_Check(op) PyObject_TypeCheck(op, &PyModule_Type)
 #define PyModule_CheckExact(op) (Py_TYPE(op) == &PyModule_Type)
 
-PyAPI_FUNC(PyObject *) PyModule_New(const char *);
+PyAPI_FUNC(PyObject *) PyModule_New(
+    const char *name            /* UTF-8 encoded string */
+    );
 PyAPI_FUNC(PyObject *) PyModule_GetDict(PyObject *);
+PyAPI_FUNC(PyObject *) PyModule_GetNameObject(PyObject *);
 PyAPI_FUNC(const char *) PyModule_GetName(PyObject *);
 PyAPI_FUNC(const char *) PyModule_GetFilename(PyObject *);
 PyAPI_FUNC(PyObject *) PyModule_GetFilenameObject(PyObject *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void) _PyModule_Clear(PyObject *);
+#endif
 PyAPI_FUNC(struct PyModuleDef*) PyModule_GetDef(PyObject*);
 PyAPI_FUNC(void*) PyModule_GetState(PyObject*);
 
@@ -28,7 +33,12 @@
   PyObject* m_copy;
 } PyModuleDef_Base;
 
-#define PyModuleDef_HEAD_INIT {PyObject_HEAD_INIT(NULL)}
+#define PyModuleDef_HEAD_INIT { \
+    PyObject_HEAD_INIT(NULL)    \
+    NULL, /* m_init */          \
+    0,    /* m_index */         \
+    NULL, /* m_copy */          \
+  }
 
 typedef struct PyModuleDef{
   PyModuleDef_Base m_base;

Modified: python/branches/pep-3151/Include/object.h
==============================================================================
--- python/branches/pep-3151/Include/object.h	(original)
+++ python/branches/pep-3151/Include/object.h	Sat Feb 26 08:16:32 2011
@@ -61,6 +61,10 @@
 #define Py_REF_DEBUG
 #endif
 
+#if defined(Py_LIMITED_API) && defined(Py_REF_DEBUG)
+#error Py_LIMITED_API is incompatible with Py_DEBUG, Py_TRACE_REFS, and Py_REF_DEBUG
+#endif
+
 #ifdef Py_TRACE_REFS
 /* Define pointers to support a doubly-linked list of all live heap objects. */
 #define _PyObject_HEAD_EXTRA            \
@@ -139,7 +143,7 @@
 typedef int(*ssizessizeobjargproc)(PyObject *, Py_ssize_t, Py_ssize_t, PyObject *);
 typedef int(*objobjargproc)(PyObject *, PyObject *, PyObject *);
 
-
+#ifndef Py_LIMITED_API
 /* buffer interface */
 typedef struct bufferinfo {
     void *buf;
@@ -191,11 +195,13 @@
 #define PyBUF_WRITE 0x200
 
 /* End buffer interface */
+#endif /* Py_LIMITED_API */
 
 typedef int (*objobjproc)(PyObject *, PyObject *);
 typedef int (*visitproc)(PyObject *, void *);
 typedef int (*traverseproc)(PyObject *, visitproc, void *);
 
+#ifndef Py_LIMITED_API
 typedef struct {
     /* Number implementations must check *both*
        arguments for proper type and implement the necessary conversions
@@ -265,10 +271,17 @@
      getbufferproc bf_getbuffer;
      releasebufferproc bf_releasebuffer;
 } PyBufferProcs;
+#endif /* Py_LIMITED_API */
 
 typedef void (*freefunc)(void *);
 typedef void (*destructor)(PyObject *);
+#ifndef Py_LIMITED_API
+/* We can't provide a full compile-time check that limited-API
+   users won't implement tp_print. However, not defining printfunc
+   and making tp_print of a different function pointer type
+   should at least cause a warning in most cases. */
 typedef int (*printfunc)(PyObject *, FILE *, int);
+#endif
 typedef PyObject *(*getattrfunc)(PyObject *, char *);
 typedef PyObject *(*getattrofunc)(PyObject *, PyObject *);
 typedef int (*setattrfunc)(PyObject *, char *, PyObject *);
@@ -284,6 +297,9 @@
 typedef PyObject *(*newfunc)(struct _typeobject *, PyObject *, PyObject *);
 typedef PyObject *(*allocfunc)(struct _typeobject *, Py_ssize_t);
 
+#ifdef Py_LIMITED_API
+typedef struct _typeobject PyTypeObject; /* opaque */
+#else
 typedef struct _typeobject {
     PyObject_VAR_HEAD
     const char *tp_name; /* For printing, in format "<module>.<name>" */
@@ -371,8 +387,24 @@
     struct _typeobject *tp_next;
 #endif
 } PyTypeObject;
+#endif
+
+typedef struct{
+    int slot;    /* slot id, see below */
+    void *pfunc; /* function pointer */
+} PyType_Slot;
+
+typedef struct{
+    const char* name;
+    int basicsize;
+    int itemsize;
+    int flags;
+    PyType_Slot *slots; /* terminated by slot==0. */
+} PyType_Spec;
 
+PyAPI_FUNC(PyObject*) PyType_FromSpec(PyType_Spec*);
 
+#ifndef Py_LIMITED_API
 /* The *real* layout of a type object when allocated on the heap */
 typedef struct _heaptypeobject {
     /* Note: there's a dependency on the order of these members
@@ -393,7 +425,7 @@
 /* access macro to the members which are floating "behind" the object */
 #define PyHeapType_GET_MEMBERS(etype) \
     ((PyMemberDef *)(((char *)etype) + Py_TYPE(etype)->tp_basicsize))
-
+#endif
 
 /* Generic type check */
 PyAPI_FUNC(int) PyType_IsSubtype(PyTypeObject *, PyTypeObject *);
@@ -404,6 +436,8 @@
 PyAPI_DATA(PyTypeObject) PyBaseObject_Type; /* built-in 'object' */
 PyAPI_DATA(PyTypeObject) PySuper_Type; /* built-in 'super' */
 
+PyAPI_FUNC(long) PyType_GetFlags(PyTypeObject*);
+
 #define PyType_Check(op) \
     PyType_FastSubclass(Py_TYPE(op), Py_TPFLAGS_TYPE_SUBCLASS)
 #define PyType_CheckExact(op) (Py_TYPE(op) == &PyType_Type)
@@ -412,15 +446,19 @@
 PyAPI_FUNC(PyObject *) PyType_GenericAlloc(PyTypeObject *, Py_ssize_t);
 PyAPI_FUNC(PyObject *) PyType_GenericNew(PyTypeObject *,
                                                PyObject *, PyObject *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
 PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, char *, PyObject **);
+#endif
 PyAPI_FUNC(unsigned int) PyType_ClearCache(void);
 PyAPI_FUNC(void) PyType_Modified(PyTypeObject *);
 
 /* Generic operations on objects */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
 PyAPI_FUNC(void) _Py_BreakPoint(void);
 PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
+#endif
 PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *);
 PyAPI_FUNC(PyObject *) PyObject_Str(PyObject *);
 PyAPI_FUNC(PyObject *) PyObject_ASCII(PyObject *);
@@ -433,9 +471,13 @@
 PyAPI_FUNC(PyObject *) PyObject_GetAttr(PyObject *, PyObject *);
 PyAPI_FUNC(int) PyObject_SetAttr(PyObject *, PyObject *, PyObject *);
 PyAPI_FUNC(int) PyObject_HasAttr(PyObject *, PyObject *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *);
+#endif
 PyAPI_FUNC(PyObject *) PyObject_SelfIter(PyObject *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
+#endif
 PyAPI_FUNC(PyObject *) PyObject_GenericGetAttr(PyObject *, PyObject *);
 PyAPI_FUNC(int) PyObject_GenericSetAttr(PyObject *,
                                               PyObject *, PyObject *);
@@ -469,8 +511,10 @@
 PyAPI_FUNC(void) Py_ReprLeave(PyObject *);
 
 /* Helpers for hash functions */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(Py_hash_t) _Py_HashDouble(double);
 PyAPI_FUNC(Py_hash_t) _Py_HashPointer(void*);
+#endif
 
 /* Helper for passing objects to printf and the like */
 #define PyObject_REPR(obj) _PyUnicode_AsString(PyObject_Repr(obj))
@@ -546,7 +590,11 @@
                  Py_TPFLAGS_HAVE_VERSION_TAG | \
                 0)
 
+#ifdef Py_LIMITED_API
+#define PyType_HasFeature(t,f)  ((PyType_GetFlags(t) & (f)) != 0)
+#else
 #define PyType_HasFeature(t,f)  (((t)->tp_flags & (f)) != 0)
+#endif
 #define PyType_FastSubclass(t,f)  PyType_HasFeature(t,f)
 
 
@@ -649,9 +697,13 @@
 
 #define _Py_ForgetReference(op) _Py_INC_TPFREES(op)
 
+#ifdef Py_LIMITED_API
+PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
+#else
 #define _Py_Dealloc(op) (                               \
     _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA          \
     (*Py_TYPE(op)->tp_dealloc)((PyObject *)(op)))
+#endif
 #endif /* !Py_TRACE_REFS */
 
 #define Py_INCREF(op) (                         \

Modified: python/branches/pep-3151/Include/objimpl.h
==============================================================================
--- python/branches/pep-3151/Include/objimpl.h	(original)
+++ python/branches/pep-3151/Include/objimpl.h	Sat Feb 26 08:16:32 2011
@@ -242,10 +242,8 @@
 #define PyObject_GC_Resize(type, op, n) \
                 ( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) )
 
-/* for source compatibility with 2.2 */
-#define _PyObject_GC_Del PyObject_GC_Del
-
 /* GC information is stored BEFORE the object structure. */
+#ifndef Py_LIMITED_API
 typedef union _gc_head {
     struct {
         union _gc_head *gc_next;
@@ -298,7 +296,7 @@
 #define _PyObject_GC_MAY_BE_TRACKED(obj) \
     (PyObject_IS_GC(obj) && \
         (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj)))
-
+#endif /* Py_LIMITED_API */
 
 PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t);
 PyAPI_FUNC(PyObject *) _PyObject_GC_New(PyTypeObject *);
@@ -327,15 +325,6 @@
         }                                                               \
     } while (0)
 
-/* This is here for the sake of backwards compatibility.  Extensions that
- * use the old GC API will still compile but the objects will not be
- * tracked by the GC. */
-#define PyGC_HEAD_SIZE 0
-#define PyObject_GC_Init(op)
-#define PyObject_GC_Fini(op)
-#define PyObject_AS_GC(op) (op)
-#define PyObject_FROM_GC(op) (op)
-
 
 /* Test if a type supports weak references */
 #define PyType_SUPPORTS_WEAKREFS(t) ((t)->tp_weaklistoffset > 0)

Modified: python/branches/pep-3151/Include/parsetok.h
==============================================================================
--- python/branches/pep-3151/Include/parsetok.h	(original)
+++ python/branches/pep-3151/Include/parsetok.h	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
 
 /* Parser-tokenizer link interface */
-
+#ifndef Py_LIMITED_API
 #ifndef Py_PARSETOK_H
 #define Py_PARSETOK_H
 #ifdef __cplusplus
@@ -9,10 +9,10 @@
 
 typedef struct {
     int error;
-    const char *filename;
+    const char *filename;       /* decoded from the filesystem encoding */
     int lineno;
     int offset;
-    char *text;
+    char *text;                 /* UTF-8-encoded string */
     int token;
     int expected;
 } perrdetail;
@@ -39,23 +39,32 @@
 
 PyAPI_FUNC(node *) PyParser_ParseStringFlags(const char *, grammar *, int,
                                               perrdetail *, int);
-PyAPI_FUNC(node *) PyParser_ParseFileFlags(FILE *, const char *, 
+PyAPI_FUNC(node *) PyParser_ParseFileFlags(FILE *, const char *,
 					   const char*, grammar *,
 						 int, char *, char *,
 						 perrdetail *, int);
-PyAPI_FUNC(node *) PyParser_ParseFileFlagsEx(FILE *, const char *,
-					   const char*, grammar *,
-						 int, char *, char *,
-						 perrdetail *, int *);
+PyAPI_FUNC(node *) PyParser_ParseFileFlagsEx(
+    FILE *fp,
+    const char *filename,       /* decoded from the filesystem encoding */
+    const char *enc,
+    grammar *g,
+    int start,
+    char *ps1,
+    char *ps2,
+    perrdetail *err_ret,
+    int *flags);
 
 PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilename(const char *,
 					      const char *,
 					      grammar *, int,
                                               perrdetail *, int);
-PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilenameEx(const char *,
-					      const char *,
-					      grammar *, int,
-                                              perrdetail *, int *);
+PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilenameEx(
+    const char *s,
+    const char *filename,       /* decoded from the filesystem encoding */
+    grammar *g,
+    int start,
+    perrdetail *err_ret,
+    int *flags);
 
 /* Note that he following function is defined in pythonrun.c not parsetok.c. */
 PyAPI_FUNC(void) PyParser_SetError(perrdetail *);
@@ -64,3 +73,4 @@
 }
 #endif
 #endif /* !Py_PARSETOK_H */
+#endif /* !Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/patchlevel.h
==============================================================================
--- python/branches/pep-3151/Include/patchlevel.h	(original)
+++ python/branches/pep-3151/Include/patchlevel.h	Sat Feb 26 08:16:32 2011
@@ -17,13 +17,13 @@
 /* Version parsed out into numeric values */
 /*--start constants--*/
 #define PY_MAJOR_VERSION	3
-#define PY_MINOR_VERSION	2
+#define PY_MINOR_VERSION	3
 #define PY_MICRO_VERSION	0
 #define PY_RELEASE_LEVEL	PY_RELEASE_LEVEL_ALPHA
-#define PY_RELEASE_SERIAL	3
+#define PY_RELEASE_SERIAL	0
 
 /* Version as a string */
-#define PY_VERSION      	"3.2a3+"
+#define PY_VERSION      	"3.3a0"
 /*--end constants--*/
 
 /* Subversion Revision number of this file (not of the repository) */

Modified: python/branches/pep-3151/Include/pyarena.h
==============================================================================
--- python/branches/pep-3151/Include/pyarena.h	(original)
+++ python/branches/pep-3151/Include/pyarena.h	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,7 @@
 /* An arena-like memory interface for the compiler.
  */
 
+#ifndef Py_LIMITED_API
 #ifndef Py_PYARENA_H
 #define Py_PYARENA_H
 
@@ -60,3 +61,4 @@
 #endif
 
 #endif /* !Py_PYARENA_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/pyatomic.h
==============================================================================
--- python/branches/pep-3151/Include/pyatomic.h	(original)
+++ python/branches/pep-3151/Include/pyatomic.h	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,4 @@
+#ifndef Py_LIMITED_API
 #ifndef Py_ATOMIC_H
 #define Py_ATOMIC_H
 /* XXX: When compilers start offering a stdatomic.h with lock-free
@@ -177,3 +178,4 @@
 #endif
 
 #endif  /* Py_ATOMIC_H */
+#endif  /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/pycapsule.h
==============================================================================
--- python/branches/pep-3151/Include/pycapsule.h	(original)
+++ python/branches/pep-3151/Include/pycapsule.h	Sat Feb 26 08:16:32 2011
@@ -48,7 +48,9 @@
 
 PyAPI_FUNC(int) PyCapsule_SetContext(PyObject *capsule, void *context);
 
-PyAPI_FUNC(void *) PyCapsule_Import(const char *name, int no_block);
+PyAPI_FUNC(void *) PyCapsule_Import(
+    const char *name,           /* UTF-8 encoded string */
+    int no_block);
 
 
 #ifdef __cplusplus

Modified: python/branches/pep-3151/Include/pyctype.h
==============================================================================
--- python/branches/pep-3151/Include/pyctype.h	(original)
+++ python/branches/pep-3151/Include/pyctype.h	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,4 @@
+#ifndef Py_LIMITED_API
 #ifndef PYCTYPE_H
 #define PYCTYPE_H
 
@@ -29,3 +30,4 @@
 #define Py_TOUPPER(c) (_Py_ctype_toupper[Py_CHARMASK(c)])
 
 #endif /* !PYCTYPE_H */
+#endif /* !Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/pydebug.h
==============================================================================
--- python/branches/pep-3151/Include/pydebug.h	(original)
+++ python/branches/pep-3151/Include/pydebug.h	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,4 @@
-
+#ifndef Py_LIMITED_API
 #ifndef Py_PYDEBUG_H
 #define Py_PYDEBUG_H
 #ifdef __cplusplus
@@ -7,6 +7,7 @@
 
 PyAPI_DATA(int) Py_DebugFlag;
 PyAPI_DATA(int) Py_VerboseFlag;
+PyAPI_DATA(int) Py_QuietFlag;
 PyAPI_DATA(int) Py_InteractiveFlag;
 PyAPI_DATA(int) Py_InspectFlag;
 PyAPI_DATA(int) Py_OptimizeFlag;
@@ -25,9 +26,8 @@
    PYTHONPATH and PYTHONHOME from the environment */
 #define Py_GETENV(s) (Py_IgnoreEnvironmentFlag ? NULL : getenv(s))
 
-PyAPI_FUNC(void) Py_FatalError(const char *message);
-
 #ifdef __cplusplus
 }
 #endif
 #endif /* !Py_PYDEBUG_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/pyerrors.h
==============================================================================
--- python/branches/pep-3151/Include/pyerrors.h	(original)
+++ python/branches/pep-3151/Include/pyerrors.h	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,7 @@
 
 /* Error objects */
 
+#ifndef Py_LIMITED_API
 /* PyException_HEAD defines the initial segment of every exception class. */
 #define PyException_HEAD PyObject_HEAD PyObject *dict;\
              PyObject *args; PyObject *traceback;\
@@ -54,6 +55,7 @@
 #ifdef MS_WINDOWS
 typedef PyIOErrorObject PyWindowsErrorObject;
 #endif
+#endif /* !Py_LIMITED_API */
 
 /* Error handling definitions */
 
@@ -68,7 +70,18 @@
 PyAPI_FUNC(void) PyErr_Fetch(PyObject **, PyObject **, PyObject **);
 PyAPI_FUNC(void) PyErr_Restore(PyObject *, PyObject *, PyObject *);
 
-#ifdef Py_DEBUG
+#if defined(__clang__) || \
+    (defined(__GNUC__) && \
+     ((__GNUC_MAJOR__ >= 3) || \
+      (__GNUC_MAJOR__ == 2) && (__GNUC_MINOR__ >= 5)))
+#define _Py_NO_RETURN __attribute__((__noreturn__))
+#else
+#define _Py_NO_RETURN
+#endif
+
+PyAPI_FUNC(void) Py_FatalError(const char *message) _Py_NO_RETURN;
+
+#if defined(Py_DEBUG) || defined(Py_LIMITED_API)
 #define _PyErr_OCCURRED() PyErr_Occurred()
 #else
 #define _PyErr_OCCURRED() (_PyThreadState_Current->curexc_type)
@@ -183,7 +196,7 @@
     PyObject *exc,
     const char *filename   /* decoded from the filesystem encoding */
     );
-#ifdef MS_WINDOWS
+#if defined(MS_WINDOWS) && !defined(Py_LIMITED_API)
 PyAPI_FUNC(PyObject *) PyErr_SetFromErrnoWithUnicodeFilename(
     PyObject *, const Py_UNICODE *);
 #endif /* MS_WINDOWS */
@@ -198,16 +211,26 @@
 PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilenameObject(
     int, const char *);
 PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithFilename(
-    int, const char *);
+    int ierr,
+    const char *filename        /* decoded from the filesystem encoding */
+    );
+#ifndef Py_LIMITED_API
+/* XXX redeclare to use WSTRING */
 PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErrWithUnicodeFilename(
     int, const Py_UNICODE *);
+#endif
 PyAPI_FUNC(PyObject *) PyErr_SetFromWindowsErr(int);
 PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilenameObject(
     PyObject *,int, PyObject *);
 PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithFilename(
-    PyObject *,int, const char *);
+    PyObject *exc,
+    int ierr,
+    const char *filename        /* decoded from the filesystem encoding */
+    );
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErrWithUnicodeFilename(
     PyObject *,int, const Py_UNICODE *);
+#endif
 PyAPI_FUNC(PyObject *) PyErr_SetExcFromWindowsErr(PyObject *, int);
 #endif /* MS_WINDOWS */
 
@@ -230,27 +253,57 @@
 PyAPI_FUNC(void) PyErr_SetInterrupt(void);
 
 /* In signalmodule.c */
+#ifndef Py_LIMITED_API
 int PySignal_SetWakeupFd(int fd);
+#endif
 
 /* Support for adding program text to SyntaxErrors */
-PyAPI_FUNC(void) PyErr_SyntaxLocation(const char *, int);
-PyAPI_FUNC(void) PyErr_SyntaxLocationEx(const char *, int, int);
-PyAPI_FUNC(PyObject *) PyErr_ProgramText(const char *, int);
+PyAPI_FUNC(void) PyErr_SyntaxLocation(
+    const char *filename,       /* decoded from the filesystem encoding */
+    int lineno);
+PyAPI_FUNC(void) PyErr_SyntaxLocationEx(
+    const char *filename,       /* decoded from the filesystem encoding */
+    int lineno,
+    int col_offset);
+PyAPI_FUNC(PyObject *) PyErr_ProgramText(
+    const char *filename,       /* decoded from the filesystem encoding */
+    int lineno);
 
 /* The following functions are used to create and modify unicode
    exceptions from C */
 
 /* create a UnicodeDecodeError object */
 PyAPI_FUNC(PyObject *) PyUnicodeDecodeError_Create(
-    const char *, const char *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
+    const char *encoding,       /* UTF-8 encoded string */
+    const char *object,
+    Py_ssize_t length,
+    Py_ssize_t start,
+    Py_ssize_t end,
+    const char *reason          /* UTF-8 encoded string */
+    );
 
 /* create a UnicodeEncodeError object */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_Create(
-    const char *, const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
+    const char *encoding,       /* UTF-8 encoded string */
+    const Py_UNICODE *object,
+    Py_ssize_t length,
+    Py_ssize_t start,
+    Py_ssize_t end,
+    const char *reason          /* UTF-8 encoded string */
+    );
+#endif
 
 /* create a UnicodeTranslateError object */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyUnicodeTranslateError_Create(
-    const Py_UNICODE *, Py_ssize_t, Py_ssize_t, Py_ssize_t, const char *);
+    const Py_UNICODE *object,
+    Py_ssize_t length,
+    Py_ssize_t start,
+    Py_ssize_t end,
+    const char *reason          /* UTF-8 encoded string */
+    );
+#endif
 
 /* get the encoding attribute */
 PyAPI_FUNC(PyObject *) PyUnicodeEncodeError_GetEncoding(PyObject *);
@@ -293,11 +346,17 @@
 /* assign a new value to the reason attribute
    return 0 on success, -1 on failure */
 PyAPI_FUNC(int) PyUnicodeEncodeError_SetReason(
-    PyObject *, const char *);
+    PyObject *exc,
+    const char *reason          /* UTF-8 encoded string */
+    );
 PyAPI_FUNC(int) PyUnicodeDecodeError_SetReason(
-    PyObject *, const char *);
+    PyObject *exc,
+    const char *reason          /* UTF-8 encoded string */
+    );
 PyAPI_FUNC(int) PyUnicodeTranslateError_SetReason(
-    PyObject *, const char *);
+    PyObject *exc,
+    const char *reason          /* UTF-8 encoded string */
+    );
 
 
 /* These APIs aren't really part of the error implementation, but

Modified: python/branches/pep-3151/Include/pygetopt.h
==============================================================================
--- python/branches/pep-3151/Include/pygetopt.h	(original)
+++ python/branches/pep-3151/Include/pygetopt.h	Sat Feb 26 08:16:32 2011
@@ -5,9 +5,11 @@
 extern "C" {
 #endif
 
+#ifndef Py_LIMITED_API
 PyAPI_DATA(int) _PyOS_opterr;
 PyAPI_DATA(int) _PyOS_optind;
 PyAPI_DATA(wchar_t *) _PyOS_optarg;
+#endif
 
 PyAPI_FUNC(int) _PyOS_GetOpt(int argc, wchar_t **argv, wchar_t *optstring);
 

Modified: python/branches/pep-3151/Include/pymath.h
==============================================================================
--- python/branches/pep-3151/Include/pymath.h	(original)
+++ python/branches/pep-3151/Include/pymath.h	Sat Feb 26 08:16:32 2011
@@ -67,6 +67,7 @@
    nothing. */
 
 /* we take double rounding as evidence of x87 usage */
+#ifndef Py_LIMITED_API
 #ifndef Py_FORCE_DOUBLE
 #  ifdef X87_DOUBLE_ROUNDING
 PyAPI_FUNC(double) _Py_force_double(double);
@@ -75,11 +76,14 @@
 #    define Py_FORCE_DOUBLE(X) (X)
 #  endif
 #endif
+#endif
 
+#ifndef Py_LIMITED_API
 #ifdef HAVE_GCC_ASM_FOR_X87
 PyAPI_FUNC(unsigned short) _Py_get_387controlword(void);
 PyAPI_FUNC(void) _Py_set_387controlword(unsigned short);
 #endif
+#endif
 
 /* Py_IS_NAN(X)
  * Return 1 if float or double arg is a NaN, else 0.

Modified: python/branches/pep-3151/Include/pyport.h
==============================================================================
--- python/branches/pep-3151/Include/pyport.h	(original)
+++ python/branches/pep-3151/Include/pyport.h	Sat Feb 26 08:16:32 2011
@@ -62,15 +62,20 @@
 #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. */
+/* Otherwise, if GCC has a builtin define, use that.  (Definition of
+ * PY_LLONG_MIN assumes two's complement with no trap representation.) */
 #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)
+#define PY_LLONG_MIN (-PY_LLONG_MAX - 1)
+#define PY_ULLONG_MAX (PY_LLONG_MAX * Py_ULL(2) + 1)
+#elif defined(SIZEOF_LONG_LONG)
+/* Otherwise compute from SIZEOF_LONG_LONG, assuming two's complement, no
+   padding bits, and no trap representation.  Note: PY_ULLONG_MAX was
+   previously #defined as (~0ULL) here; but that'll give the wrong value in a
+   preprocessor expression on systems where long long != intmax_t. */
+#define PY_LLONG_MAX                                                    \
+    (1 + 2 * ((Py_LL(1) << (CHAR_BIT * SIZEOF_LONG_LONG - 2)) - 1))
+#define PY_LLONG_MIN (-PY_LLONG_MAX - 1)
+#define PY_ULLONG_MAX (PY_LLONG_MAX * Py_ULL(2) + 1)
 #endif /* LLONG_MAX */
 #endif
 #endif /* HAVE_LONG_LONG */

Modified: python/branches/pep-3151/Include/pystate.h
==============================================================================
--- python/branches/pep-3151/Include/pystate.h	(original)
+++ python/branches/pep-3151/Include/pystate.h	Sat Feb 26 08:16:32 2011
@@ -13,6 +13,9 @@
 struct _ts; /* Forward */
 struct _is; /* Forward */
 
+#ifdef Py_LIMITED_API
+typedef struct _is PyInterpreterState;
+#else
 typedef struct _is {
 
     struct _is *next;
@@ -37,12 +40,14 @@
 #endif
 
 } PyInterpreterState;
+#endif
 
 
 /* State unique per thread */
 
 struct _frame; /* Avoid including frameobject.h */
 
+#ifndef Py_LIMITED_API
 /* Py_tracefunc return -1 when raising an exception, or 0 for success. */
 typedef int (*Py_tracefunc)(PyObject *, struct _frame *, int, PyObject *);
 
@@ -54,7 +59,11 @@
 #define PyTrace_C_CALL 4
 #define PyTrace_C_EXCEPTION 5
 #define PyTrace_C_RETURN 6
+#endif
 
+#ifdef Py_LIMITED_API
+typedef struct _ts PyThreadState;
+#else
 typedef struct _ts {
     /* See Python/ceval.c for comments explaining most fields */
 
@@ -106,6 +115,7 @@
     /* XXX signal handlers should also be here */
 
 } PyThreadState;
+#endif
 
 
 PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_New(void);
@@ -133,9 +143,11 @@
 
 /* Assuming the current thread holds the GIL, this is the
    PyThreadState for the current thread. */
+#ifndef Py_LIMITED_API
 PyAPI_DATA(_Py_atomic_address) _PyThreadState_Current;
+#endif
 
-#ifdef Py_DEBUG
+#if defined(Py_DEBUG) || defined(Py_LIMITED_API)
 #define PyThreadState_GET() PyThreadState_Get()
 #else
 #define PyThreadState_GET() \
@@ -190,19 +202,25 @@
 /* The implementation of sys._current_frames()  Returns a dict mapping
    thread id to that thread's current frame.
 */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyThread_CurrentFrames(void);
+#endif
 
 /* Routines for advanced debuggers, requested by David Beazley.
    Don't use unless you know what you are doing! */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Head(void);
 PyAPI_FUNC(PyInterpreterState *) PyInterpreterState_Next(PyInterpreterState *);
 PyAPI_FUNC(PyThreadState *) PyInterpreterState_ThreadHead(PyInterpreterState *);
 PyAPI_FUNC(PyThreadState *) PyThreadState_Next(PyThreadState *);
 
 typedef struct _frame *(*PyThreadFrameGetter)(PyThreadState *self_);
+#endif
 
 /* hook for PyEval_GetFrame(), requested for Psyco */
+#ifndef Py_LIMITED_API
 PyAPI_DATA(PyThreadFrameGetter) _PyThreadState_GetFrame;
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/pystrtod.h
==============================================================================
--- python/branches/pep-3151/Include/pystrtod.h	(original)
+++ python/branches/pep-3151/Include/pystrtod.h	Sat Feb 26 08:16:32 2011
@@ -18,7 +18,9 @@
                                          int flags,
                                          int *type);
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(double) _Py_parse_inf_or_nan(const char *p, char **endptr);
+#endif
 
 
 /* PyOS_double_to_string's "flags" parameter can be set to 0 or more of: */

Modified: python/branches/pep-3151/Include/pythonrun.h
==============================================================================
--- python/branches/pep-3151/Include/pythonrun.h	(original)
+++ python/branches/pep-3151/Include/pythonrun.h	Sat Feb 26 08:16:32 2011
@@ -16,9 +16,11 @@
 #define PyCF_ONLY_AST 0x0400
 #define PyCF_IGNORE_COOKIE 0x0800
 
+#ifndef Py_LIMITED_API
 typedef struct {
     int cf_flags;  /* bitmask of CO_xxx flags relevant to future */
 } PyCompilerFlags;
+#endif
 
 PyAPI_FUNC(void) Py_SetProgramName(wchar_t *);
 PyAPI_FUNC(wchar_t *) Py_GetProgramName(void);
@@ -33,41 +35,87 @@
 PyAPI_FUNC(PyThreadState *) Py_NewInterpreter(void);
 PyAPI_FUNC(void) Py_EndInterpreter(PyThreadState *);
 
-PyAPI_FUNC(int) PyRun_AnyFileFlags(FILE *, const char *, PyCompilerFlags *);
-PyAPI_FUNC(int) PyRun_AnyFileExFlags(FILE *, const char *, int, PyCompilerFlags *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) PyRun_SimpleStringFlags(const char *, PyCompilerFlags *);
-PyAPI_FUNC(int) PyRun_SimpleFileExFlags(FILE *, const char *, int, PyCompilerFlags *);
-PyAPI_FUNC(int) PyRun_InteractiveOneFlags(FILE *, const char *, PyCompilerFlags *);
-PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(FILE *, const char *, PyCompilerFlags *);
-
-PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(const char *, const char *,
-                                                 int, PyCompilerFlags *flags,
-                                                 PyArena *);
-PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(FILE *, const char *,
-                                               const char*, int,
-                                               char *, char *,
-                                               PyCompilerFlags *, int *,
-                                               PyArena *);
+PyAPI_FUNC(int) PyRun_AnyFileFlags(FILE *, const char *, PyCompilerFlags *);
+PyAPI_FUNC(int) PyRun_AnyFileExFlags(
+    FILE *fp,
+    const char *filename,       /* decoded from the filesystem encoding */
+    int closeit,
+    PyCompilerFlags *flags);
+PyAPI_FUNC(int) PyRun_SimpleFileExFlags(
+    FILE *fp,
+    const char *filename,       /* decoded from the filesystem encoding */
+    int closeit,
+    PyCompilerFlags *flags);
+PyAPI_FUNC(int) PyRun_InteractiveOneFlags(
+    FILE *fp,
+    const char *filename,       /* decoded from the filesystem encoding */
+    PyCompilerFlags *flags);
+PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(
+    FILE *fp,
+    const char *filename,       /* decoded from the filesystem encoding */
+    PyCompilerFlags *flags);
+
+PyAPI_FUNC(struct _mod *) PyParser_ASTFromString(
+    const char *s,
+    const char *filename,       /* decoded from the filesystem encoding */
+    int start,
+    PyCompilerFlags *flags,
+    PyArena *arena);
+PyAPI_FUNC(struct _mod *) PyParser_ASTFromFile(
+    FILE *fp,
+    const char *filename,       /* decoded from the filesystem encoding */
+    const char* enc,
+    int start,
+    char *ps1,
+    char *ps2,
+    PyCompilerFlags *flags,
+    int *errcode,
+    PyArena *arena);
+#endif
+
+#ifndef PyParser_SimpleParseString
 #define PyParser_SimpleParseString(S, B) \
     PyParser_SimpleParseStringFlags(S, B, 0)
 #define PyParser_SimpleParseFile(FP, S, B) \
     PyParser_SimpleParseFileFlags(FP, S, B, 0)
+#endif
 PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int,
                                                           int);
 PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *,
                                                         int, int);
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *,
                                          PyObject *, PyCompilerFlags *);
 
-PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int,
-                                         PyObject *, PyObject *, int,
-                                         PyCompilerFlags *);
-
-#define Py_CompileString(str, p, s) Py_CompileStringFlags(str, p, s, NULL)
-PyAPI_FUNC(PyObject *) Py_CompileStringFlags(const char *, const char *, int,
-                                             PyCompilerFlags *);
-PyAPI_FUNC(struct symtable *) Py_SymtableString(const char *, const char *, int);
+PyAPI_FUNC(PyObject *) PyRun_FileExFlags(
+    FILE *fp,
+    const char *filename,       /* decoded from the filesystem encoding */
+    int start,
+    PyObject *globals,
+    PyObject *locals,
+    int closeit,
+    PyCompilerFlags *flags);
+#endif
+
+#ifdef Py_LIMITED_API
+PyAPI_FUNC(PyObject *) Py_CompileString(const char *, const char *, int);
+#else
+#define Py_CompileString(str, p, s) Py_CompileStringExFlags(str, p, s, NULL, -1)
+#define Py_CompileStringFlags(str, p, s, f) Py_CompileStringExFlags(str, p, s, f, -1)
+PyAPI_FUNC(PyObject *) Py_CompileStringExFlags(
+    const char *str,
+    const char *filename,       /* decoded from the filesystem encoding */
+    int start,
+    PyCompilerFlags *flags,
+    int optimize);
+#endif
+PyAPI_FUNC(struct symtable *) Py_SymtableString(
+    const char *str,
+    const char *filename,       /* decoded from the filesystem encoding */
+    int start);
 
 PyAPI_FUNC(void) PyErr_Print(void);
 PyAPI_FUNC(void) PyErr_PrintEx(int);
@@ -76,19 +124,24 @@
 /* Py_PyAtExit is for the atexit module, Py_AtExit is for low-level
  * exit functions.
  */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void) _Py_PyAtExit(void (*func)(void));
+#endif
 PyAPI_FUNC(int) Py_AtExit(void (*func)(void));
 
 PyAPI_FUNC(void) Py_Exit(int);
 
 /* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL. */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void) _Py_RestoreSignals(void);
 
 PyAPI_FUNC(int) Py_FdIsInteractive(FILE *, const char *);
+#endif
 
 /* Bootstrap */
 PyAPI_FUNC(int) Py_Main(int argc, wchar_t **argv);
 
+#ifndef Py_LIMITED_API
 /* Use macros for a bunch of old variants */
 #define PyRun_String(str, s, g, l) PyRun_StringFlags(str, s, g, l, NULL)
 #define PyRun_AnyFile(fp, name) PyRun_AnyFileExFlags(fp, name, 0, NULL)
@@ -107,6 +160,7 @@
     PyRun_FileExFlags(fp, p, s, g, l, c, NULL)
 #define PyRun_FileFlags(fp, p, s, g, l, flags) \
     PyRun_FileExFlags(fp, p, s, g, l, 0, flags)
+#endif
 
 /* In getpath.c */
 PyAPI_FUNC(wchar_t *) Py_GetProgramFullPath(void);
@@ -114,6 +168,9 @@
 PyAPI_FUNC(wchar_t *) Py_GetExecPrefix(void);
 PyAPI_FUNC(wchar_t *) Py_GetPath(void);
 PyAPI_FUNC(void)      Py_SetPath(const wchar_t *);
+#ifdef MS_WINDOWS
+int _Py_CheckPython3();
+#endif
 
 /* In their own files */
 PyAPI_FUNC(const char *) Py_GetVersion(void);
@@ -121,11 +178,14 @@
 PyAPI_FUNC(const char *) Py_GetCopyright(void);
 PyAPI_FUNC(const char *) Py_GetCompiler(void);
 PyAPI_FUNC(const char *) Py_GetBuildInfo(void);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(const char *) _Py_svnversion(void);
 PyAPI_FUNC(const char *) Py_SubversionRevision(void);
 PyAPI_FUNC(const char *) Py_SubversionShortBranch(void);
+#endif
 
 /* Internal -- various one-time initializations */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyBuiltin_Init(void);
 PyAPI_FUNC(PyObject *) _PySys_Init(void);
 PyAPI_FUNC(void) _PyImport_Init(void);
@@ -134,8 +194,10 @@
 PyAPI_FUNC(int) _PyFrame_Init(void);
 PyAPI_FUNC(void) _PyFloat_Init(void);
 PyAPI_FUNC(int) PyByteArray_Init(void);
+#endif
 
 /* Various internal finalizers */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void) _PyExc_Fini(void);
 PyAPI_FUNC(void) _PyImport_Fini(void);
 PyAPI_FUNC(void) PyMethod_Fini(void);
@@ -150,12 +212,17 @@
 PyAPI_FUNC(void) PyFloat_Fini(void);
 PyAPI_FUNC(void) PyOS_FiniInterrupts(void);
 PyAPI_FUNC(void) _PyGC_Fini(void);
+#endif
 
 /* Stuff with no proper home (yet) */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(char *) PyOS_Readline(FILE *, FILE *, char *);
+#endif
 PyAPI_DATA(int) (*PyOS_InputHook)(void);
 PyAPI_DATA(char) *(*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, char *);
+#ifndef Py_LIMITED_API
 PyAPI_DATA(PyThreadState*) _PyOS_ReadlineTState;
+#endif
 
 /* Stack size, in "pointers" (so we get extra safety margins
    on 64-bit platforms).  On a 32-bit platform, this translates

Modified: python/branches/pep-3151/Include/pythread.h
==============================================================================
--- python/branches/pep-3151/Include/pythread.h	(original)
+++ python/branches/pep-3151/Include/pythread.h	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,14 @@
 extern "C" {
 #endif
 
+/* Return status codes for Python lock acquisition.  Chosen for maximum
+ * backwards compatibility, ie failure -> 0, success -> 1.  */
+typedef enum PyLockStatus {
+    PY_LOCK_FAILURE = 0,
+    PY_LOCK_ACQUIRED = 1,
+    PY_LOCK_INTR
+} PyLockStatus;
+
 PyAPI_FUNC(void) PyThread_init_thread(void);
 PyAPI_FUNC(long) PyThread_start_new_thread(void (*)(void *), void *);
 PyAPI_FUNC(void) PyThread_exit_thread(void);
@@ -49,11 +57,18 @@
    even when the lock can't be acquired.
    If microseconds > 0, the call waits up to the specified duration.
    If microseconds < 0, the call waits until success (or abnormal failure)
-   
+
    microseconds must be less than PY_TIMEOUT_MAX. Behaviour otherwise is
-   undefined. */
-PyAPI_FUNC(int) PyThread_acquire_lock_timed(PyThread_type_lock,
-					    PY_TIMEOUT_T microseconds);
+   undefined.
+
+   If intr_flag is true and the acquire is interrupted by a signal, then the
+   call will return PY_LOCK_INTR.  The caller may reattempt to acquire the
+   lock.
+*/
+PyAPI_FUNC(PyLockStatus) PyThread_acquire_lock_timed(PyThread_type_lock,
+                                                     PY_TIMEOUT_T microseconds,
+                                                     int intr_flag);
+
 PyAPI_FUNC(void) PyThread_release_lock(PyThread_type_lock);
 
 PyAPI_FUNC(size_t) PyThread_get_stacksize(void);

Modified: python/branches/pep-3151/Include/pytime.h
==============================================================================
--- python/branches/pep-3151/Include/pytime.h	(original)
+++ python/branches/pep-3151/Include/pytime.h	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,4 @@
+#ifndef Py_LIMITED_API
 #ifndef Py_PYTIME_H
 #define Py_PYTIME_H
 
@@ -44,3 +45,4 @@
 #endif
 
 #endif /* Py_PYTIME_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/setobject.h
==============================================================================
--- python/branches/pep-3151/Include/setobject.h	(original)
+++ python/branches/pep-3151/Include/setobject.h	Sat Feb 26 08:16:32 2011
@@ -18,7 +18,7 @@
 hold a search finger.  The hash field of Unused or Dummy slots has
 no meaning otherwise.
 */
-
+#ifndef Py_LIMITED_API
 #define PySet_MINSIZE 8
 
 typedef struct {
@@ -56,6 +56,7 @@
     Py_hash_t hash;                  /* only used by frozenset objects */
     PyObject *weakreflist;      /* List of weak references */
 };
+#endif /* Py_LIMITED_API */
 
 PyAPI_DATA(PyTypeObject) PySet_Type;
 PyAPI_DATA(PyTypeObject) PyFrozenSet_Type;
@@ -85,14 +86,20 @@
 PyAPI_FUNC(PyObject *) PySet_New(PyObject *);
 PyAPI_FUNC(PyObject *) PyFrozenSet_New(PyObject *);
 PyAPI_FUNC(Py_ssize_t) PySet_Size(PyObject *anyset);
+#ifndef Py_LIMITED_API
 #define PySet_GET_SIZE(so) (((PySetObject *)(so))->used)
+#endif
 PyAPI_FUNC(int) PySet_Clear(PyObject *set);
 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);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, Py_hash_t *hash);
+#endif
 PyAPI_FUNC(PyObject *) PySet_Pop(PyObject *set);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PySet_Update(PyObject *set, PyObject *iterable);
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/sliceobject.h
==============================================================================
--- python/branches/pep-3151/Include/sliceobject.h	(original)
+++ python/branches/pep-3151/Include/sliceobject.h	Sat Feb 26 08:16:32 2011
@@ -18,11 +18,12 @@
 names are from range).  After much talk with Guido, it was decided to
 let these be any arbitrary python type.  Py_None stands for omitted values.
 */
-
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_HEAD
     PyObject *start, *stop, *step;	/* not NULL */
 } PySliceObject;
+#endif
 
 PyAPI_DATA(PyTypeObject) PySlice_Type;
 PyAPI_DATA(PyTypeObject) PyEllipsis_Type;
@@ -31,10 +32,12 @@
 
 PyAPI_FUNC(PyObject *) PySlice_New(PyObject* start, PyObject* stop,
                                   PyObject* step);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PySlice_FromIndices(Py_ssize_t start, Py_ssize_t stop);
-PyAPI_FUNC(int) PySlice_GetIndices(PySliceObject *r, Py_ssize_t length,
+#endif
+PyAPI_FUNC(int) PySlice_GetIndices(PyObject *r, Py_ssize_t length,
                                   Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step);
-PyAPI_FUNC(int) PySlice_GetIndicesEx(PySliceObject *r, Py_ssize_t length,
+PyAPI_FUNC(int) PySlice_GetIndicesEx(PyObject *r, Py_ssize_t length,
 				    Py_ssize_t *start, Py_ssize_t *stop, 
 				    Py_ssize_t *step, Py_ssize_t *slicelength);
 

Modified: python/branches/pep-3151/Include/structseq.h
==============================================================================
--- python/branches/pep-3151/Include/structseq.h	(original)
+++ python/branches/pep-3151/Include/structseq.h	Sat Feb 26 08:16:32 2011
@@ -21,18 +21,25 @@
 
 extern char* PyStructSequence_UnnamedField;
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void) PyStructSequence_InitType(PyTypeObject *type,
                                            PyStructSequence_Desc *desc);
+#endif
+PyAPI_FUNC(PyTypeObject*) PyStructSequence_NewType(PyStructSequence_Desc *desc);
 
 PyAPI_FUNC(PyObject *) PyStructSequence_New(PyTypeObject* type);
 
+#ifndef Py_LIMITED_API
 typedef PyTupleObject PyStructSequence;
 
 /* Macro, *only* to be used to fill in brand new objects */
 #define PyStructSequence_SET_ITEM(op, i, v) PyTuple_SET_ITEM(op, i, v)
 
 #define PyStructSequence_GET_ITEM(op, i) PyTuple_GET_ITEM(op, i)
+#endif
 
+PyAPI_FUNC(void) PyStructSequence_SetItem(PyObject*, Py_ssize_t, PyObject*);
+PyAPI_FUNC(PyObject*) PyStructSequence_GetItem(PyObject*, Py_ssize_t);
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/symtable.h
==============================================================================
--- python/branches/pep-3151/Include/symtable.h	(original)
+++ python/branches/pep-3151/Include/symtable.h	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,4 @@
+#ifndef Py_LIMITED_API
 #ifndef Py_SYMTABLE_H
 #define Py_SYMTABLE_H
 
@@ -15,7 +16,8 @@
 struct _symtable_entry;
 
 struct symtable {
-    const char *st_filename;        /* name of file being compiled */
+    const char *st_filename;        /* name of file being compiled,
+                                       decoded from the filesystem encoding */
     struct _symtable_entry *st_cur; /* current symbol table entry */
     struct _symtable_entry *st_top; /* symbol table entry for module */
     PyObject *st_blocks;            /* dict: map AST node addresses
@@ -59,8 +61,10 @@
 
 PyAPI_FUNC(int) PyST_GetScope(PySTEntryObject *, PyObject *);
 
-PyAPI_FUNC(struct symtable *) PySymtable_Build(mod_ty, const char *,
-                                              PyFutureFeatures *);
+PyAPI_FUNC(struct symtable *) PySymtable_Build(
+    mod_ty mod,
+    const char *filename,       /* decoded from the filesystem encoding */
+    PyFutureFeatures *future);
 PyAPI_FUNC(PySTEntryObject *) PySymtable_Lookup(struct symtable *, void *);
 
 PyAPI_FUNC(void) PySymtable_Free(struct symtable *);
@@ -102,3 +106,4 @@
 }
 #endif
 #endif /* !Py_SYMTABLE_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/sysmodule.h
==============================================================================
--- python/branches/pep-3151/Include/sysmodule.h	(original)
+++ python/branches/pep-3151/Include/sysmodule.h	Sat Feb 26 08:16:32 2011
@@ -20,7 +20,9 @@
 PyAPI_FUNC(void) PySys_FormatStdout(const char *format, ...);
 PyAPI_FUNC(void) PySys_FormatStderr(const char *format, ...);
 
+#ifndef Py_LIMITED_API
 PyAPI_DATA(PyObject *) _PySys_TraceFunc, *_PySys_ProfileFunc;
+#endif
 
 PyAPI_FUNC(void) PySys_ResetWarnOptions(void);
 PyAPI_FUNC(void) PySys_AddWarnOption(const wchar_t *);

Modified: python/branches/pep-3151/Include/timefuncs.h
==============================================================================
--- python/branches/pep-3151/Include/timefuncs.h	(original)
+++ python/branches/pep-3151/Include/timefuncs.h	Sat Feb 26 08:16:32 2011
@@ -14,7 +14,9 @@
  * to fit in a time_t.  ValueError is set on return iff the return
  * value is (time_t)-1 and PyErr_Occurred().
  */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(time_t) _PyTime_DoubleToTimet(double x);
+#endif
 
 
 #ifdef __cplusplus

Modified: python/branches/pep-3151/Include/token.h
==============================================================================
--- python/branches/pep-3151/Include/token.h	(original)
+++ python/branches/pep-3151/Include/token.h	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
 
 /* Token types */
-
+#ifndef Py_LIMITED_API
 #ifndef Py_TOKEN_H
 #define Py_TOKEN_H
 #ifdef __cplusplus
@@ -85,3 +85,4 @@
 }
 #endif
 #endif /* !Py_TOKEN_H */
+#endif /* Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/traceback.h
==============================================================================
--- python/branches/pep-3151/Include/traceback.h	(original)
+++ python/branches/pep-3151/Include/traceback.h	Sat Feb 26 08:16:32 2011
@@ -8,7 +8,7 @@
 struct _frame;
 
 /* Traceback interface */
-
+#ifndef Py_LIMITED_API
 typedef struct _traceback {
     PyObject_HEAD
     struct _traceback *tb_next;
@@ -16,10 +16,13 @@
     int tb_lasti;
     int tb_lineno;
 } PyTracebackObject;
+#endif
 
 PyAPI_FUNC(int) PyTraceBack_Here(struct _frame *);
 PyAPI_FUNC(int) PyTraceBack_Print(PyObject *, PyObject *);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _Py_DisplaySourceLine(PyObject *, PyObject *, int, int);
+#endif
 
 /* Reveal traceback type so we can typecheck traceback objects */
 PyAPI_DATA(PyTypeObject) PyTraceBack_Type;

Modified: python/branches/pep-3151/Include/tupleobject.h
==============================================================================
--- python/branches/pep-3151/Include/tupleobject.h	(original)
+++ python/branches/pep-3151/Include/tupleobject.h	Sat Feb 26 08:16:32 2011
@@ -21,6 +21,7 @@
 returned item's reference count.
 */
 
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_VAR_HEAD
     PyObject *ob_item[1];
@@ -30,6 +31,7 @@
      * the tuple is not yet visible outside the function that builds it.
      */
 } PyTupleObject;
+#endif
 
 PyAPI_DATA(PyTypeObject) PyTuple_Type;
 PyAPI_DATA(PyTypeObject) PyTupleIter_Type;
@@ -43,16 +45,22 @@
 PyAPI_FUNC(PyObject *) PyTuple_GetItem(PyObject *, Py_ssize_t);
 PyAPI_FUNC(int) PyTuple_SetItem(PyObject *, Py_ssize_t, PyObject *);
 PyAPI_FUNC(PyObject *) PyTuple_GetSlice(PyObject *, Py_ssize_t, Py_ssize_t);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) _PyTuple_Resize(PyObject **, Py_ssize_t);
+#endif
 PyAPI_FUNC(PyObject *) PyTuple_Pack(Py_ssize_t, ...);
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void) _PyTuple_MaybeUntrack(PyObject *);
+#endif
 
 /* Macro, trading safety for speed */
+#ifndef Py_LIMITED_API
 #define PyTuple_GET_ITEM(op, i) (((PyTupleObject *)(op))->ob_item[i])
 #define PyTuple_GET_SIZE(op)    Py_SIZE(op)
 
 /* Macro, *only* to be used to fill in brand new tuples */
 #define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject *)(op))->ob_item[i] = v)
+#endif
 
 PyAPI_FUNC(int) PyTuple_ClearFreeList(void);
 

Modified: python/branches/pep-3151/Include/ucnhash.h
==============================================================================
--- python/branches/pep-3151/Include/ucnhash.h	(original)
+++ python/branches/pep-3151/Include/ucnhash.h	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,5 @@
 /* Unicode name database interface */
-
+#ifndef Py_LIMITED_API
 #ifndef Py_UCNHASH_H
 #define Py_UCNHASH_H
 #ifdef __cplusplus
@@ -31,3 +31,4 @@
 }
 #endif
 #endif /* !Py_UCNHASH_H */
+#endif /* !Py_LIMITED_API */

Modified: python/branches/pep-3151/Include/unicodeobject.h
==============================================================================
--- python/branches/pep-3151/Include/unicodeobject.h	(original)
+++ python/branches/pep-3151/Include/unicodeobject.h	Sat Feb 26 08:16:32 2011
@@ -7,7 +7,8 @@
 
 Unicode implementation based on original code by Fredrik Lundh,
 modified by Marc-Andre Lemburg (mal at lemburg.com) according to the
-Unicode Integration Proposal (see file Misc/unicode.txt).
+Unicode Integration Proposal. (See
+http://www.egenix.com/files/python/unicode-proposal.txt).
 
 Copyright (c) Corporation for National Research Initiatives.
 
@@ -130,7 +131,9 @@
    Python and represents a single Unicode element in the Unicode
    type. */
 
+#ifndef Py_LIMITED_API
 typedef PY_UNICODE_TYPE Py_UNICODE;
+#endif
 
 /* --- UCS-2/UCS-4 Name Mangling ------------------------------------------ */
 
@@ -317,6 +320,7 @@
    _Py_ascii_whitespace (see below) with an inlined check.
 
  */
+#ifndef Py_LIMITED_API
 #define Py_UNICODE_ISSPACE(ch) \
     ((ch) < 128U ? _Py_ascii_whitespace[(ch)] : _PyUnicode_IsWhitespace(ch))
 
@@ -354,13 +358,14 @@
     for (i_ = 0; i_ < (length); i_++) t_[i_] = v_;\
     } while (0)
 
-/* Check if substring matches at given offset.  the offset must be
-   valid, and the substring must not be empty */
+/* Check if substring matches at given offset.  The offset must be
+   valid, and the substring must not be empty. */
 
 #define Py_UNICODE_MATCH(string, offset, substring) \
     ((*((string)->str + (offset)) == *((substring)->str)) && \
     ((*((string)->str + (offset) + (substring)->length-1) == *((substring)->str + (substring)->length-1))) && \
      !memcmp((string)->str + (offset), (substring)->str, (substring)->length*sizeof(Py_UNICODE)))
+#endif /* Py_LIMITED_API */
 
 #ifdef __cplusplus
 extern "C" {
@@ -368,6 +373,7 @@
 
 /* --- Unicode Type ------------------------------------------------------- */
 
+#ifndef Py_LIMITED_API
 typedef struct {
     PyObject_HEAD
     Py_ssize_t length;          /* Length of raw Unicode data in buffer */
@@ -380,6 +386,7 @@
                                    string, or NULL; this is used for
                                    implementing the buffer protocol */
 } PyUnicodeObject;
+#endif
 
 PyAPI_DATA(PyTypeObject) PyUnicode_Type;
 PyAPI_DATA(PyTypeObject) PyUnicodeIter_Type;
@@ -393,6 +400,7 @@
 #define PyUnicode_CheckExact(op) (Py_TYPE(op) == &PyUnicode_Type)
 
 /* Fast access macros */
+#ifndef Py_LIMITED_API
 #define PyUnicode_GET_SIZE(op) \
     (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->length))
 #define PyUnicode_GET_DATA_SIZE(op) \
@@ -401,6 +409,7 @@
     (assert(PyUnicode_Check(op)),(((PyUnicodeObject *)(op))->str))
 #define PyUnicode_AS_DATA(op) \
     (assert(PyUnicode_Check(op)),((const char *)((PyUnicodeObject *)(op))->str))
+#endif
 
 /* --- Constants ---------------------------------------------------------- */
 
@@ -425,29 +434,33 @@
 
    The buffer is copied into the new object. */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_FromUnicode(
     const Py_UNICODE *u,        /* Unicode buffer */
     Py_ssize_t size             /* size of buffer */
     );
+#endif
 
 /* Similar to PyUnicode_FromUnicode(), but u points to UTF-8 encoded bytes */
 PyAPI_FUNC(PyObject*) PyUnicode_FromStringAndSize(
-    const char *u,        /* char buffer */
-    Py_ssize_t size       /* size of buffer */
+    const char *u,             /* UTF-8 encoded string */
+    Py_ssize_t size            /* size of buffer */
     );
 
 /* Similar to PyUnicode_FromUnicode(), but u points to null-terminated
    UTF-8 encoded bytes */
 PyAPI_FUNC(PyObject*) PyUnicode_FromString(
-    const char *u        /* string */
+    const char *u              /* UTF-8 encoded string */
     );
 
 /* Return a read-only pointer to the Unicode object's internal
    Py_UNICODE buffer. */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(Py_UNICODE *) PyUnicode_AsUnicode(
     PyObject *unicode           /* Unicode object */
     );
+#endif
 
 /* Get the length of the Unicode object. */
 
@@ -455,8 +468,10 @@
     PyObject *unicode           /* Unicode object */
     );
 
+#ifndef Py_LIMITED_API
 /* Get the maximum ordinal for a Unicode character. */
 PyAPI_FUNC(Py_UNICODE) PyUnicode_GetMax(void);
+#endif
 
 /* Resize an already allocated Unicode object to the new size length.
 
@@ -483,8 +498,8 @@
    Coercion is done in the following way:
 
    1. bytes, bytearray and other char buffer compatible objects are decoded
-      under the assumptions that they contain data using the current
-      default encoding. Decoding is done in "strict" mode.
+      under the assumptions that they contain data using the UTF-8
+      encoding. Decoding is done in "strict" mode.
 
    2. All other objects (including Unicode objects) raise an
       exception.
@@ -526,16 +541,22 @@
     ...
     );
 
+#ifndef Py_LIMITED_API
 /* Format the object based on the format_spec, as defined in PEP 3101
    (Advanced String Formatting). */
 PyAPI_FUNC(PyObject *) _PyUnicode_FormatAdvanced(PyObject *obj,
                                                  Py_UNICODE *format_spec,
                                                  Py_ssize_t format_spec_len);
+#endif
 
 PyAPI_FUNC(void) PyUnicode_InternInPlace(PyObject **);
 PyAPI_FUNC(void) PyUnicode_InternImmortal(PyObject **);
-PyAPI_FUNC(PyObject *) PyUnicode_InternFromString(const char *);
+PyAPI_FUNC(PyObject *) PyUnicode_InternFromString(
+    const char *u              /* UTF-8 encoded string */
+    );
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(void) _Py_ReleaseInternedUnicodeStrings(void);
+#endif
 
 /* Use only if you know it's a string */
 #define PyUnicode_CHECK_INTERNED(op) (((PyUnicodeObject *)(op))->state)
@@ -567,7 +588,7 @@
    error. */
 
 PyAPI_FUNC(Py_ssize_t) PyUnicode_AsWideChar(
-    PyUnicodeObject *unicode,   /* Unicode object */
+    PyObject *unicode,          /* Unicode object */
     register wchar_t *w,        /* wchar_t buffer */
     Py_ssize_t size             /* size of buffer */
     );
@@ -614,7 +635,7 @@
 
    Many of these APIs take two arguments encoding and errors. These
    parameters encoding and errors have the same semantics as the ones
-   of the builtin unicode() API.
+   of the builtin str() API.
 
    Setting encoding to NULL causes the default encoding (UTF-8) to be used.
 
@@ -633,7 +654,8 @@
 /* Return a Python string holding the default encoded value of the
    Unicode object.
 
-   The resulting string is cached in the Unicode object for subsequent
+   Same as PyUnicode_AsUTF8String() except
+   the resulting string is cached in the Unicode object for subsequent
    usage by this function. The cached version is needed to implement
    the character buffer interface and will live (at least) as long as
    the Unicode object itself.
@@ -644,29 +666,33 @@
 
 */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) _PyUnicode_AsDefaultEncodedString(
     PyObject *unicode,
     const char *errors);
+#endif
 
-/* Returns a pointer to the default encoding (normally, UTF-8) of the
+/* Returns a pointer to the default encoding (UTF-8) of the
    Unicode object unicode and the size of the encoded representation
    in bytes stored in *size.
 
    In case of an error, no *size is set.
 
    *** This API is for interpreter INTERNAL USE ONLY and will likely
-   *** be removed or changed for Python 3.1.
+   *** be removed or changed in the future.
 
    *** If you need to access the Unicode object as UTF-8 bytes string,
    *** please use PyUnicode_AsUTF8String() instead.
 
 */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(char *) _PyUnicode_AsStringAndSize(
     PyObject *unicode,
     Py_ssize_t *size);
+#endif
 
-/* Returns a pointer to the default encoding (normally, UTf-8) of the
+/* Returns a pointer to the default encoding (UTF-8) of the
    Unicode object unicode.
 
    Use of this API is DEPRECATED since no size information can be
@@ -680,16 +706,11 @@
 
 */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(char *) _PyUnicode_AsString(PyObject *unicode);
+#endif
 
-/* Returns the currently active default encoding.
-
-   The default encoding is currently implemented as run-time settable
-   process global.  This may change in future versions of the
-   interpreter to become a parameter which is managed on a per-thread
-   basis.
-
- */
+/* Returns "utf-8".  */
 
 PyAPI_FUNC(const char*) PyUnicode_GetDefaultEncoding(void);
 
@@ -726,12 +747,14 @@
 /* Encodes a Py_UNICODE buffer of the given size and returns a
    Python string object. */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_Encode(
     const Py_UNICODE *s,        /* Unicode char buffer */
     Py_ssize_t size,            /* number of Py_UNICODE chars to encode */
     const char *encoding,       /* encoding */
     const char *errors          /* error handling */
     );
+#endif
 
 /* Encodes a Unicode object and returns the result as Python
    object. */
@@ -781,6 +804,7 @@
     Py_ssize_t *consumed        /* bytes consumed */
     );
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF7(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length,          /* number of Py_UNICODE chars to encode */
@@ -788,6 +812,7 @@
     int base64WhiteSpace,       /* Encode whitespace (sp, ht, nl, cr) in base64 */
     const char *errors          /* error handling */
     );
+#endif
 
 /* --- UTF-8 Codecs ------------------------------------------------------- */
 
@@ -808,11 +833,13 @@
     PyObject *unicode           /* Unicode object */
     );
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF8(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length,          /* number of Py_UNICODE chars to encode */
     const char *errors          /* error handling */
     );
+#endif
 
 /* --- UTF-32 Codecs ------------------------------------------------------ */
 
@@ -881,12 +908,14 @@
 
 */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF32(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length,          /* number of Py_UNICODE chars to encode */
     const char *errors,         /* error handling */
     int byteorder               /* byteorder to use 0=BOM+native;-1=LE,1=BE */
     );
+#endif
 
 /* --- UTF-16 Codecs ------------------------------------------------------ */
 
@@ -959,12 +988,14 @@
 
 */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeUTF16(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length,          /* number of Py_UNICODE chars to encode */
     const char *errors,         /* error handling */
     int byteorder               /* byteorder to use 0=BOM+native;-1=LE,1=BE */
     );
+#endif
 
 /* --- Unicode-Escape Codecs ---------------------------------------------- */
 
@@ -978,10 +1009,12 @@
     PyObject *unicode           /* Unicode object */
     );
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeUnicodeEscape(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length           /* Number of Py_UNICODE chars to encode */
     );
+#endif
 
 /* --- Raw-Unicode-Escape Codecs ------------------------------------------ */
 
@@ -995,20 +1028,24 @@
     PyObject *unicode           /* Unicode object */
     );
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeRawUnicodeEscape(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length           /* Number of Py_UNICODE chars to encode */
     );
+#endif
 
 /* --- Unicode Internal Codec ---------------------------------------------
 
     Only for internal use in _codecsmodule.c */
 
+#ifndef Py_LIMITED_API
 PyObject *_PyUnicode_DecodeUnicodeInternal(
     const char *string,
     Py_ssize_t length,
     const char *errors
     );
+#endif
 
 /* --- Latin-1 Codecs -----------------------------------------------------
 
@@ -1026,11 +1063,13 @@
     PyObject *unicode           /* Unicode object */
     );
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeLatin1(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length,          /* Number of Py_UNICODE chars to encode */
     const char *errors          /* error handling */
     );
+#endif
 
 /* --- ASCII Codecs -------------------------------------------------------
 
@@ -1048,11 +1087,13 @@
     PyObject *unicode           /* Unicode object */
     );
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeASCII(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length,          /* Number of Py_UNICODE chars to encode */
     const char *errors          /* error handling */
     );
+#endif
 
 /* --- Character Map Codecs -----------------------------------------------
 
@@ -1090,6 +1131,7 @@
                                    (unicode ordinal -> char ordinal) */
     );
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeCharmap(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length,          /* Number of Py_UNICODE chars to encode */
@@ -1097,6 +1139,7 @@
                                    (unicode ordinal -> char ordinal) */
     const char *errors          /* error handling */
     );
+#endif
 
 /* Translate a Py_UNICODE buffer of the given length by applying a
    character mapping table to it and return the resulting Unicode
@@ -1111,12 +1154,14 @@
 
 */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject *) PyUnicode_TranslateCharmap(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length,          /* Number of Py_UNICODE chars to encode */
     PyObject *table,            /* Translate table */
     const char *errors          /* error handling */
     );
+#endif
 
 #ifdef MS_WIN32
 
@@ -1139,11 +1184,13 @@
     PyObject *unicode           /* Unicode object */
     );
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) PyUnicode_EncodeMBCS(
     const Py_UNICODE *data,     /* Unicode char buffer */
     Py_ssize_t length,          /* Number of Py_UNICODE chars to encode */
     const char *errors          /* error handling */
     );
+#endif
 
 #endif /* MS_WIN32 */
 
@@ -1171,12 +1218,27 @@
 
 */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(int) PyUnicode_EncodeDecimal(
     Py_UNICODE *s,              /* Unicode buffer */
     Py_ssize_t length,          /* Number of Py_UNICODE chars to encode */
     char *output,               /* Output buffer; must have size >= length */
     const char *errors          /* error handling */
     );
+#endif
+
+/* Transforms code points that have decimal digit property to the
+   corresponding ASCII digit code points.
+
+   Returns a new Unicode string on success, NULL on failure.
+*/
+
+#ifndef Py_LIMITED_API
+PyAPI_FUNC(PyObject*) PyUnicode_TransformDecimalToASCII(
+    Py_UNICODE *s,              /* Unicode buffer */
+    Py_ssize_t length           /* Number of Py_UNICODE chars to transform */
+    );
+#endif
 
 /* --- File system encoding ---------------------------------------------- */
 
@@ -1395,7 +1457,7 @@
 
 PyAPI_FUNC(int) PyUnicode_CompareWithASCIIString(
     PyObject *left,
-    const char *right
+    const char *right           /* ASCII-encoded string */
     );
 
 /* Rich compare two strings and return one of the following:
@@ -1443,26 +1505,31 @@
 
 PyAPI_FUNC(int) PyUnicode_IsIdentifier(PyObject *s);
 
+#ifndef Py_LIMITED_API
 /* Externally visible for str.strip(unicode) */
 PyAPI_FUNC(PyObject *) _PyUnicode_XStrip(
     PyUnicodeObject *self,
     int striptype,
     PyObject *sepobj
     );
+#endif
 
 /* Using the current locale, insert the thousands grouping
    into the string pointed to by buffer.  For the argument descriptions,
    see Objects/stringlib/localeutil.h */
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(Py_ssize_t) _PyUnicode_InsertThousandsGroupingLocale(Py_UNICODE *buffer,
                                                    Py_ssize_t n_buffer,
                                                    Py_UNICODE *digits,
                                                    Py_ssize_t n_digits,
                                                    Py_ssize_t min_width);
+#endif
 
 /* Using explicit passed-in values, insert the thousands grouping
    into the string pointed to by buffer.  For the argument descriptions,
    see Objects/stringlib/localeutil.h */
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(Py_ssize_t) _PyUnicode_InsertThousandsGrouping(Py_UNICODE *buffer,
                                                    Py_ssize_t n_buffer,
                                                    Py_UNICODE *digits,
@@ -1470,10 +1537,12 @@
                                                    Py_ssize_t min_width,
                                                    const char *grouping,
                                                    const char *thousands_sep);
+#endif
 /* === Characters Type APIs =============================================== */
 
 /* Helper array used by Py_UNICODE_ISSPACE(). */
 
+#ifndef Py_LIMITED_API
 PyAPI_DATA(const unsigned char) _Py_ascii_whitespace[];
 
 /* These should not be used directly. Use the Py_UNICODE_IS* and
@@ -1599,6 +1668,7 @@
 PyAPI_FUNC(Py_UNICODE*) PyUnicode_AsUnicodeCopy(
     PyObject *unicode
     );
+#endif /* Py_LIMITED_API */
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/warnings.h
==============================================================================
--- python/branches/pep-3151/Include/warnings.h	(original)
+++ python/branches/pep-3151/Include/warnings.h	Sat Feb 26 08:16:32 2011
@@ -4,15 +4,31 @@
 extern "C" {
 #endif
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(PyObject*) _PyWarnings_Init(void);
+#endif
 
-PyAPI_FUNC(int) PyErr_WarnEx(PyObject *, const char *, Py_ssize_t);
-PyAPI_FUNC(int) PyErr_WarnFormat(PyObject *, Py_ssize_t, const char *, ...);
-PyAPI_FUNC(int) PyErr_WarnExplicit(PyObject *, const char *, const char *, int,
-                                    const char *, PyObject *);
+PyAPI_FUNC(int) PyErr_WarnEx(
+    PyObject *category,
+    const char *message,        /* UTF-8 encoded string */
+    Py_ssize_t stack_level);
+PyAPI_FUNC(int) PyErr_WarnFormat(
+    PyObject *category,
+    Py_ssize_t stack_level,
+    const char *format,         /* ASCII-encoded string  */
+    ...);
+PyAPI_FUNC(int) PyErr_WarnExplicit(
+    PyObject *category,
+    const char *message,        /* UTF-8 encoded string */
+    const char *filename,       /* decoded from the filesystem encoding */
+    int lineno,
+    const char *module,         /* UTF-8 encoded string */
+    PyObject *registry);
 
 /* DEPRECATED: Use PyErr_WarnEx() instead. */
+#ifndef Py_LIMITED_API
 #define PyErr_Warn(category, msg) PyErr_WarnEx(category, msg, 1)
+#endif
 
 #ifdef __cplusplus
 }

Modified: python/branches/pep-3151/Include/weakrefobject.h
==============================================================================
--- python/branches/pep-3151/Include/weakrefobject.h	(original)
+++ python/branches/pep-3151/Include/weakrefobject.h	Sat Feb 26 08:16:32 2011
@@ -12,6 +12,7 @@
 /* PyWeakReference is the base struct for the Python ReferenceType, ProxyType,
  * and CallableProxyType.
  */
+#ifndef Py_LIMITED_API
 struct _PyWeakReference {
     PyObject_HEAD
 
@@ -37,6 +38,7 @@
     PyWeakReference *wr_prev;
     PyWeakReference *wr_next;
 };
+#endif
 
 PyAPI_DATA(PyTypeObject) _PyWeakref_RefType;
 PyAPI_DATA(PyTypeObject) _PyWeakref_ProxyType;
@@ -62,9 +64,11 @@
                                                 PyObject *callback);
 PyAPI_FUNC(PyObject *) PyWeakref_GetObject(PyObject *ref);
 
+#ifndef Py_LIMITED_API
 PyAPI_FUNC(Py_ssize_t) _PyWeakref_GetWeakrefCount(PyWeakReference *head);
 
 PyAPI_FUNC(void) _PyWeakref_ClearRef(PyWeakReference *self);
+#endif
 
 #define PyWeakref_GET_OBJECT(ref) (((PyWeakReference *)(ref))->wr_object)
 

Modified: python/branches/pep-3151/LICENSE
==============================================================================
--- python/branches/pep-3151/LICENSE	(original)
+++ python/branches/pep-3151/LICENSE	Sat Feb 26 08:16:32 2011
@@ -68,7 +68,8 @@
     3.1             3.0.1       2009        PSF         yes
     3.1.1           3.1         2009        PSF         yes
     3.1.2           3.1         2010        PSF         yes
-    3.2             3.1         2010        PSF         yes
+    3.2             3.1         2011        PSF         yes
+    3.3             3.2         2012        PSF         yes
 
 Footnotes:
 
@@ -103,9 +104,9 @@
 analyze, test, perform and/or display publicly, prepare derivative works,
 distribute, and otherwise use Python alone or in any derivative version,
 provided, however, that PSF's License Agreement and PSF's notice of copyright,
-i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
-Python Software Foundation; All Rights Reserved" are retained in Python alone or
-in any derivative version prepared by Licensee.
+i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
+2011 Python Software Foundation; All Rights Reserved" are retained in Python
+alone or in any derivative version prepared by Licensee.
 
 3. In the event Licensee prepares a derivative work that is based on
 or incorporates Python or any part thereof, and wants to make

Deleted: python/branches/pep-3151/Lib/_abcoll.py
==============================================================================
--- python/branches/pep-3151/Lib/_abcoll.py	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,622 +0,0 @@
-# Copyright 2007 Google, Inc. All Rights Reserved.
-# Licensed to PSF under a Contributor Agreement.
-
-"""Abstract Base Classes (ABCs) for collections, according to PEP 3119.
-
-DON'T USE THIS MODULE DIRECTLY!  The classes here should be imported
-via collections; they are defined here only to alleviate certain
-bootstrapping issues.  Unit tests are in test_collections.
-"""
-
-from abc import ABCMeta, abstractmethod
-import sys
-
-__all__ = ["Hashable", "Iterable", "Iterator",
-           "Sized", "Container", "Callable",
-           "Set", "MutableSet",
-           "Mapping", "MutableMapping",
-           "MappingView", "KeysView", "ItemsView", "ValuesView",
-           "Sequence", "MutableSequence",
-           "ByteString",
-           ]
-
-
-### collection related types which are not exposed through builtin ###
-## iterators ##
-bytes_iterator = type(iter(b''))
-bytearray_iterator = type(iter(bytearray()))
-#callable_iterator = ???
-dict_keyiterator = type(iter({}.keys()))
-dict_valueiterator = type(iter({}.values()))
-dict_itemiterator = type(iter({}.items()))
-list_iterator = type(iter([]))
-list_reverseiterator = type(iter(reversed([])))
-range_iterator = type(iter(range(0)))
-set_iterator = type(iter(set()))
-str_iterator = type(iter(""))
-tuple_iterator = type(iter(()))
-zip_iterator = type(iter(zip()))
-## views ##
-dict_keys = type({}.keys())
-dict_values = type({}.values())
-dict_items = type({}.items())
-## misc ##
-dict_proxy = type(type.__dict__)
-
-
-### ONE-TRICK PONIES ###
-
-class Hashable(metaclass=ABCMeta):
-
-    @abstractmethod
-    def __hash__(self):
-        return 0
-
-    @classmethod
-    def __subclasshook__(cls, C):
-        if cls is Hashable:
-            for B in C.__mro__:
-                if "__hash__" in B.__dict__:
-                    if B.__dict__["__hash__"]:
-                        return True
-                    break
-        return NotImplemented
-
-
-class Iterable(metaclass=ABCMeta):
-
-    @abstractmethod
-    def __iter__(self):
-        while False:
-            yield None
-
-    @classmethod
-    def __subclasshook__(cls, C):
-        if cls is Iterable:
-            if any("__iter__" in B.__dict__ for B in C.__mro__):
-                return True
-        return NotImplemented
-
-
-class Iterator(Iterable):
-
-    @abstractmethod
-    def __next__(self):
-        raise StopIteration
-
-    def __iter__(self):
-        return self
-
-    @classmethod
-    def __subclasshook__(cls, C):
-        if cls is Iterator:
-            if any("__next__" in B.__dict__ for B in C.__mro__):
-                return True
-        return NotImplemented
-
-Iterator.register(bytes_iterator)
-Iterator.register(bytearray_iterator)
-#Iterator.register(callable_iterator)
-Iterator.register(dict_keyiterator)
-Iterator.register(dict_valueiterator)
-Iterator.register(dict_itemiterator)
-Iterator.register(list_iterator)
-Iterator.register(list_reverseiterator)
-Iterator.register(range_iterator)
-Iterator.register(set_iterator)
-Iterator.register(str_iterator)
-Iterator.register(tuple_iterator)
-Iterator.register(zip_iterator)
-
-class Sized(metaclass=ABCMeta):
-
-    @abstractmethod
-    def __len__(self):
-        return 0
-
-    @classmethod
-    def __subclasshook__(cls, C):
-        if cls is Sized:
-            if any("__len__" in B.__dict__ for B in C.__mro__):
-                return True
-        return NotImplemented
-
-
-class Container(metaclass=ABCMeta):
-
-    @abstractmethod
-    def __contains__(self, x):
-        return False
-
-    @classmethod
-    def __subclasshook__(cls, C):
-        if cls is Container:
-            if any("__contains__" in B.__dict__ for B in C.__mro__):
-                return True
-        return NotImplemented
-
-
-class Callable(metaclass=ABCMeta):
-
-    @abstractmethod
-    def __call__(self, *args, **kwds):
-        return False
-
-    @classmethod
-    def __subclasshook__(cls, C):
-        if cls is Callable:
-            if any("__call__" in B.__dict__ for B in C.__mro__):
-                return True
-        return NotImplemented
-
-
-### SETS ###
-
-
-class Set(Sized, Iterable, Container):
-
-    """A set is a finite, iterable container.
-
-    This class provides concrete generic implementations of all
-    methods except for __contains__, __iter__ and __len__.
-
-    To override the comparisons (presumably for speed, as the
-    semantics are fixed), all you have to do is redefine __le__ and
-    then the other operations will automatically follow suit.
-    """
-
-    def __le__(self, other):
-        if not isinstance(other, Set):
-            return NotImplemented
-        if len(self) > len(other):
-            return False
-        for elem in self:
-            if elem not in other:
-                return False
-        return True
-
-    def __lt__(self, other):
-        if not isinstance(other, Set):
-            return NotImplemented
-        return len(self) < len(other) and self.__le__(other)
-
-    def __gt__(self, other):
-        if not isinstance(other, Set):
-            return NotImplemented
-        return other < self
-
-    def __ge__(self, other):
-        if not isinstance(other, Set):
-            return NotImplemented
-        return other <= self
-
-    def __eq__(self, other):
-        if not isinstance(other, Set):
-            return NotImplemented
-        return len(self) == len(other) and self.__le__(other)
-
-    def __ne__(self, other):
-        return not (self == other)
-
-    @classmethod
-    def _from_iterable(cls, it):
-        '''Construct an instance of the class from any iterable input.
-
-        Must override this method if the class constructor signature
-        does not accept an iterable for an input.
-        '''
-        return cls(it)
-
-    def __and__(self, other):
-        if not isinstance(other, Iterable):
-            return NotImplemented
-        return self._from_iterable(value for value in other if value in self)
-
-    def isdisjoint(self, other):
-        for value in other:
-            if value in self:
-                return False
-        return True
-
-    def __or__(self, other):
-        if not isinstance(other, Iterable):
-            return NotImplemented
-        chain = (e for s in (self, other) for e in s)
-        return self._from_iterable(chain)
-
-    def __sub__(self, other):
-        if not isinstance(other, Set):
-            if not isinstance(other, Iterable):
-                return NotImplemented
-            other = self._from_iterable(other)
-        return self._from_iterable(value for value in self
-                                   if value not in other)
-
-    def __xor__(self, other):
-        if not isinstance(other, Set):
-            if not isinstance(other, Iterable):
-                return NotImplemented
-            other = self._from_iterable(other)
-        return (self - other) | (other - self)
-
-    def _hash(self):
-        """Compute the hash value of a set.
-
-        Note that we don't define __hash__: not all sets are hashable.
-        But if you define a hashable set type, its __hash__ should
-        call this function.
-
-        This must be compatible __eq__.
-
-        All sets ought to compare equal if they contain the same
-        elements, regardless of how they are implemented, and
-        regardless of the order of the elements; so there's not much
-        freedom for __eq__ or __hash__.  We match the algorithm used
-        by the built-in frozenset type.
-        """
-        MAX = sys.maxsize
-        MASK = 2 * MAX + 1
-        n = len(self)
-        h = 1927868237 * (n + 1)
-        h &= MASK
-        for x in self:
-            hx = hash(x)
-            h ^= (hx ^ (hx << 16) ^ 89869747)  * 3644798167
-            h &= MASK
-        h = h * 69069 + 907133923
-        h &= MASK
-        if h > MAX:
-            h -= MASK + 1
-        if h == -1:
-            h = 590923713
-        return h
-
-Set.register(frozenset)
-
-
-class MutableSet(Set):
-
-    @abstractmethod
-    def add(self, value):
-        """Add an element."""
-        raise NotImplementedError
-
-    @abstractmethod
-    def discard(self, value):
-        """Remove an element.  Do not raise an exception if absent."""
-        raise NotImplementedError
-
-    def remove(self, value):
-        """Remove an element. If not a member, raise a KeyError."""
-        if value not in self:
-            raise KeyError(value)
-        self.discard(value)
-
-    def pop(self):
-        """Return the popped value.  Raise KeyError if empty."""
-        it = iter(self)
-        try:
-            value = next(it)
-        except StopIteration:
-            raise KeyError
-        self.discard(value)
-        return value
-
-    def clear(self):
-        """This is slow (creates N new iterators!) but effective."""
-        try:
-            while True:
-                self.pop()
-        except KeyError:
-            pass
-
-    def __ior__(self, it: Iterable):
-        for value in it:
-            self.add(value)
-        return self
-
-    def __iand__(self, it: Iterable):
-        for value in (self - it):
-            self.discard(value)
-        return self
-
-    def __ixor__(self, it: Iterable):
-        if it is self:
-            self.clear()
-        else:
-            if not isinstance(it, Set):
-                it = self._from_iterable(it)
-            for value in it:
-                if value in self:
-                    self.discard(value)
-                else:
-                    self.add(value)
-        return self
-
-    def __isub__(self, it: Iterable):
-        if it is self:
-            self.clear()
-        else:
-            for value in it:
-                self.discard(value)
-        return self
-
-MutableSet.register(set)
-
-
-### MAPPINGS ###
-
-
-class Mapping(Sized, Iterable, Container):
-
-    @abstractmethod
-    def __getitem__(self, key):
-        raise KeyError
-
-    def get(self, key, default=None):
-        try:
-            return self[key]
-        except KeyError:
-            return default
-
-    def __contains__(self, key):
-        try:
-            self[key]
-        except KeyError:
-            return False
-        else:
-            return True
-
-    def keys(self):
-        return KeysView(self)
-
-    def items(self):
-        return ItemsView(self)
-
-    def values(self):
-        return ValuesView(self)
-
-    def __eq__(self, other):
-        if not isinstance(other, Mapping):
-            return NotImplemented
-        return dict(self.items()) == dict(other.items())
-
-    def __ne__(self, other):
-        return not (self == other)
-
-
-class MappingView(Sized):
-
-    def __init__(self, mapping):
-        self._mapping = mapping
-
-    def __len__(self):
-        return len(self._mapping)
-
-    def __repr__(self):
-        return '{0.__class__.__name__}({0._mapping!r})'.format(self)
-
-
-class KeysView(MappingView, Set):
-
-    @classmethod
-    def _from_iterable(self, it):
-        return set(it)
-
-    def __contains__(self, key):
-        return key in self._mapping
-
-    def __iter__(self):
-        for key in self._mapping:
-            yield key
-
-KeysView.register(dict_keys)
-
-
-class ItemsView(MappingView, Set):
-
-    @classmethod
-    def _from_iterable(self, it):
-        return set(it)
-
-    def __contains__(self, item):
-        key, value = item
-        try:
-            v = self._mapping[key]
-        except KeyError:
-            return False
-        else:
-            return v == value
-
-    def __iter__(self):
-        for key in self._mapping:
-            yield (key, self._mapping[key])
-
-ItemsView.register(dict_items)
-
-
-class ValuesView(MappingView):
-
-    def __contains__(self, value):
-        for key in self._mapping:
-            if value == self._mapping[key]:
-                return True
-        return False
-
-    def __iter__(self):
-        for key in self._mapping:
-            yield self._mapping[key]
-
-ValuesView.register(dict_values)
-
-
-class MutableMapping(Mapping):
-
-    @abstractmethod
-    def __setitem__(self, key, value):
-        raise KeyError
-
-    @abstractmethod
-    def __delitem__(self, key):
-        raise KeyError
-
-    __marker = object()
-
-    def pop(self, key, default=__marker):
-        try:
-            value = self[key]
-        except KeyError:
-            if default is self.__marker:
-                raise
-            return default
-        else:
-            del self[key]
-            return value
-
-    def popitem(self):
-        try:
-            key = next(iter(self))
-        except StopIteration:
-            raise KeyError
-        value = self[key]
-        del self[key]
-        return key, value
-
-    def clear(self):
-        try:
-            while True:
-                self.popitem()
-        except KeyError:
-            pass
-
-    def update(*args, **kwds):
-        if len(args) > 2:
-            raise TypeError("update() takes at most 2 positional "
-                            "arguments ({} given)".format(len(args)))
-        elif not args:
-            raise TypeError("update() takes at least 1 argument (0 given)")
-        self = args[0]
-        other = args[1] if len(args) >= 2 else ()
-
-        if isinstance(other, Mapping):
-            for key in other:
-                self[key] = other[key]
-        elif hasattr(other, "keys"):
-            for key in other.keys():
-                self[key] = other[key]
-        else:
-            for key, value in other:
-                self[key] = value
-        for key, value in kwds.items():
-            self[key] = value
-
-    def setdefault(self, key, default=None):
-        try:
-            return self[key]
-        except KeyError:
-            self[key] = default
-        return default
-
-MutableMapping.register(dict)
-
-
-### SEQUENCES ###
-
-
-class Sequence(Sized, Iterable, Container):
-
-    """All the operations on a read-only sequence.
-
-    Concrete subclasses must override __new__ or __init__,
-    __getitem__, and __len__.
-    """
-
-    @abstractmethod
-    def __getitem__(self, index):
-        raise IndexError
-
-    def __iter__(self):
-        i = 0
-        try:
-            while True:
-                v = self[i]
-                yield v
-                i += 1
-        except IndexError:
-            return
-
-    def __contains__(self, value):
-        for v in self:
-            if v == value:
-                return True
-        return False
-
-    def __reversed__(self):
-        for i in reversed(range(len(self))):
-            yield self[i]
-
-    def index(self, value):
-        for i, v in enumerate(self):
-            if v == value:
-                return i
-        raise ValueError
-
-    def count(self, value):
-        return sum(1 for v in self if v == value)
-
-Sequence.register(tuple)
-Sequence.register(str)
-Sequence.register(range)
-
-
-class ByteString(Sequence):
-
-    """This unifies bytes and bytearray.
-
-    XXX Should add all their methods.
-    """
-
-ByteString.register(bytes)
-ByteString.register(bytearray)
-
-
-class MutableSequence(Sequence):
-
-    @abstractmethod
-    def __setitem__(self, index, value):
-        raise IndexError
-
-    @abstractmethod
-    def __delitem__(self, index):
-        raise IndexError
-
-    @abstractmethod
-    def insert(self, index, value):
-        raise IndexError
-
-    def append(self, value):
-        self.insert(len(self), value)
-
-    def reverse(self):
-        n = len(self)
-        for i in range(n//2):
-            self[i], self[n-i-1] = self[n-i-1], self[i]
-
-    def extend(self, values):
-        for v in values:
-            self.append(v)
-
-    def pop(self, index=-1):
-        v = self[index]
-        del self[index]
-        return v
-
-    def remove(self, value):
-        del self[self.index(value)]
-
-    def __iadd__(self, values):
-        self.extend(values)
-        return self
-
-MutableSequence.register(list)
-MutableSequence.register(bytearray)  # Multiply inheriting, see ByteString

Modified: python/branches/pep-3151/Lib/_pyio.py
==============================================================================
--- python/branches/pep-3151/Lib/_pyio.py	(original)
+++ python/branches/pep-3151/Lib/_pyio.py	Sat Feb 26 08:16:32 2011
@@ -14,6 +14,7 @@
 
 import io
 from io import (__all__, SEEK_SET, SEEK_CUR, SEEK_END)
+from errno import EINTR
 
 # open() uses st_blksize whenever we can
 DEFAULT_BUFFER_SIZE = 8 * 1024  # bytes
@@ -34,9 +35,8 @@
         self.characters_written = characters_written
 
 
-def open(file: (str, bytes), mode: str = "r", buffering: int = -1,
-         encoding: str = None, errors: str = None,
-         newline: str = None, closefd: bool = True) -> "IOBase":
+def open(file, mode="r", buffering=-1, encoding=None, errors=None,
+         newline=None, closefd=True):
 
     r"""Open file and return a stream.  Raise IOError upon failure.
 
@@ -96,7 +96,7 @@
       use line buffering.  Other text files use the policy described above
       for binary files.
 
-    encoding is the name of the encoding used to decode or encode the
+    encoding is the str name of the encoding used to decode or encode the
     file. This should only be used in text mode. The default encoding is
     platform dependent, but any encoding supported by Python can be
     passed.  See the codecs module for the list of supported encodings.
@@ -109,9 +109,9 @@
     See the documentation for codecs.register for a list of the permitted
     encoding error strings.
 
-    newline controls how universal newlines works (it only applies to text
-    mode). It can be None, '', '\n', '\r', and '\r\n'.  It works as
-    follows:
+    newline is a string controlling how universal newlines works (it only
+    applies to text mode). It can be None, '', '\n', '\r', and '\r\n'.  It works
+    as follows:
 
     * On input, if newline is None, universal newlines mode is
       enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
@@ -127,9 +127,9 @@
       other legal values, any '\n' characters written are translated to
       the given string.
 
-    If closefd is False, the underlying file descriptor will be kept open
-    when the file is closed. This does not work when a file name is given
-    and must be True in that case.
+    closedfd is a bool. If closefd is False, the underlying file descriptor will
+    be kept open when the file is closed. This does not work when a file name is
+    given and must be True in that case.
 
     open() returns a file object whose type depends on the mode, and
     through which the standard file operations such as reading and writing
@@ -287,33 +287,33 @@
 
     ### Internal ###
 
-    def _unsupported(self, name: str) -> IOError:
-        """Internal: raise an exception for unsupported operations."""
+    def _unsupported(self, name):
+        """Internal: raise an IOError exception for unsupported operations."""
         raise UnsupportedOperation("%s.%s() not supported" %
                                    (self.__class__.__name__, name))
 
     ### Positioning ###
 
-    def seek(self, pos: int, whence: int = 0) -> int:
+    def seek(self, pos, whence=0):
         """Change stream position.
 
         Change the stream position to byte offset offset. offset is
         interpreted relative to the position indicated by whence.  Values
-        for whence are:
+        for whence are ints:
 
         * 0 -- start of stream (the default); offset should be zero or positive
         * 1 -- current stream position; offset may be negative
         * 2 -- end of stream; offset is usually negative
 
-        Return the new absolute position.
+        Return an int indicating the new absolute position.
         """
         self._unsupported("seek")
 
-    def tell(self) -> int:
-        """Return current stream position."""
+    def tell(self):
+        """Return an int indicating the current stream position."""
         return self.seek(0, 1)
 
-    def truncate(self, pos: int = None) -> int:
+    def truncate(self, pos=None):
         """Truncate file to size bytes.
 
         Size defaults to the current IO position as reported by tell().  Return
@@ -323,7 +323,7 @@
 
     ### Flush and close ###
 
-    def flush(self) -> None:
+    def flush(self):
         """Flush write buffers, if applicable.
 
         This is not implemented for read-only and non-blocking streams.
@@ -333,7 +333,7 @@
 
     __closed = False
 
-    def close(self) -> None:
+    def close(self):
         """Flush and close the IO object.
 
         This method has no effect if the file is already closed.
@@ -342,7 +342,7 @@
             self.flush()
             self.__closed = True
 
-    def __del__(self) -> None:
+    def __del__(self):
         """Destructor.  Calls close()."""
         # The try/except block is in case this is called at program
         # exit time, when it's possible that globals have already been
@@ -356,8 +356,8 @@
 
     ### Inquiries ###
 
-    def seekable(self) -> bool:
-        """Return whether object supports random access.
+    def seekable(self):
+        """Return a bool indicating whether object supports random access.
 
         If False, seek(), tell() and truncate() will raise UnsupportedOperation.
         This method may need to do a test seek().
@@ -371,8 +371,8 @@
             raise UnsupportedOperation("File or stream is not seekable."
                                        if msg is None else msg)
 
-    def readable(self) -> bool:
-        """Return whether object was opened for reading.
+    def readable(self):
+        """Return a bool indicating whether object was opened for reading.
 
         If False, read() will raise UnsupportedOperation.
         """
@@ -385,8 +385,8 @@
             raise UnsupportedOperation("File or stream is not readable."
                                        if msg is None else msg)
 
-    def writable(self) -> bool:
-        """Return whether object was opened for writing.
+    def writable(self):
+        """Return a bool indicating whether object was opened for writing.
 
         If False, write() and truncate() will raise UnsupportedOperation.
         """
@@ -416,12 +416,12 @@
 
     ### Context manager ###
 
-    def __enter__(self) -> "IOBase":  # That's a forward reference
-        """Context management protocol.  Returns self."""
+    def __enter__(self):  # That's a forward reference
+        """Context management protocol.  Returns self (an instance of IOBase)."""
         self._checkClosed()
         return self
 
-    def __exit__(self, *args) -> None:
+    def __exit__(self, *args):
         """Context management protocol.  Calls close()"""
         self.close()
 
@@ -429,15 +429,15 @@
 
     # XXX Should these be present even if unimplemented?
 
-    def fileno(self) -> int:
-        """Returns underlying file descriptor if one exists.
+    def fileno(self):
+        """Returns underlying file descriptor (an int) if one exists.
 
         An IOError is raised if the IO object does not use a file descriptor.
         """
         self._unsupported("fileno")
 
-    def isatty(self) -> bool:
-        """Return whether this is an 'interactive' stream.
+    def isatty(self):
+        """Return a bool indicating whether this is an 'interactive' stream.
 
         Return False if it can't be determined.
         """
@@ -446,10 +446,11 @@
 
     ### Readline[s] and writelines ###
 
-    def readline(self, limit: int = -1) -> bytes:
-        r"""Read and return a line from the stream.
+    def readline(self, limit=-1):
+        r"""Read and return a line of bytes from the stream.
 
         If limit is specified, at most limit bytes will be read.
+        Limit should be an int.
 
         The line terminator is always b'\n' for binary files; for text
         files, the newlines argument to open can be used to select the line
@@ -532,8 +533,8 @@
     # primitive operation, but that would lead to nasty recursion in case
     # a subclass doesn't implement either.)
 
-    def read(self, n: int = -1) -> bytes:
-        """Read and return up to n bytes.
+    def read(self, n=-1):
+        """Read and return up to n bytes, where n is an int.
 
         Returns an empty bytes object on EOF, or None if the object is
         set not to block and has no data to read.
@@ -559,15 +560,15 @@
             res += data
         return bytes(res)
 
-    def readinto(self, b: bytearray) -> int:
-        """Read up to len(b) bytes into b.
+    def readinto(self, b):
+        """Read up to len(b) bytes into bytearray b.
 
-        Returns number of bytes read (0 for EOF), or None if the object
-        is set not to block and has no data to read.
+        Returns an int representing the number of bytes read (0 for EOF), or
+        None if the object is set not to block and has no data to read.
         """
         self._unsupported("readinto")
 
-    def write(self, b: bytes) -> int:
+    def write(self, b):
         """Write the given buffer to the IO stream.
 
         Returns the number of bytes written, which may be less than len(b).
@@ -596,8 +597,8 @@
     implementation, but wrap one.
     """
 
-    def read(self, n: int = None) -> bytes:
-        """Read and return up to n bytes.
+    def read(self, n=None):
+        """Read and return up to n bytes, where n is an int.
 
         If the argument is omitted, None, or negative, reads and
         returns all data until EOF.
@@ -616,17 +617,19 @@
         """
         self._unsupported("read")
 
-    def read1(self, n: int=None) -> bytes:
-        """Read up to n bytes with at most one read() system call."""
+    def read1(self, n=None):
+        """Read up to n bytes with at most one read() system call,
+        where n is an int.
+        """
         self._unsupported("read1")
 
-    def readinto(self, b: bytearray) -> int:
-        """Read up to len(b) bytes into b.
+    def readinto(self, b):
+        """Read up to len(b) bytes into bytearray b.
 
         Like read(), this may issue multiple reads to the underlying raw
         stream, unless the latter is 'interactive'.
 
-        Returns the number of bytes read (0 for EOF).
+        Returns an int representing the number of bytes read (0 for EOF).
 
         Raises BlockingIOError if the underlying raw stream has no
         data at the moment.
@@ -643,8 +646,8 @@
             b[:n] = array.array('b', data)
         return n
 
-    def write(self, b: bytes) -> int:
-        """Write the given buffer to the IO stream.
+    def write(self, b):
+        """Write the given bytes buffer to the IO stream.
 
         Return the number of bytes written, which is never less than
         len(b).
@@ -654,7 +657,7 @@
         """
         self._unsupported("write")
 
-    def detach(self) -> None:
+    def detach(self):
         """
         Separate the underlying raw stream from the buffer and return it.
 
@@ -676,7 +679,7 @@
     """
 
     def __init__(self, raw):
-        self.raw = raw
+        self._raw = raw
 
     ### Positioning ###
 
@@ -720,8 +723,8 @@
         if self.raw is None:
             raise ValueError("raw stream already detached")
         self.flush()
-        raw = self.raw
-        self.raw = None
+        raw = self._raw
+        self._raw = None
         return raw
 
     ### Inquiries ###
@@ -736,6 +739,10 @@
         return self.raw.writable()
 
     @property
+    def raw(self):
+        return self._raw
+
+    @property
     def closed(self):
         return self.raw.closed
 
@@ -937,7 +944,12 @@
             current_size = 0
             while True:
                 # Read until EOF or until read() would block.
-                chunk = self.raw.read()
+                try:
+                    chunk = self.raw.read()
+                except IOError as e:
+                    if e.errno != EINTR:
+                        raise
+                    continue
                 if chunk in empty_values:
                     nodata_val = chunk
                     break
@@ -956,7 +968,12 @@
         chunks = [buf[pos:]]
         wanted = max(self.buffer_size, n)
         while avail < n:
-            chunk = self.raw.read(wanted)
+            try:
+                chunk = self.raw.read(wanted)
+            except IOError as e:
+                if e.errno != EINTR:
+                    raise
+                continue
             if chunk in empty_values:
                 nodata_val = chunk
                 break
@@ -985,7 +1002,14 @@
         have = len(self._read_buf) - self._read_pos
         if have < want or have <= 0:
             to_read = self.buffer_size - have
-            current = self.raw.read(to_read)
+            while True:
+                try:
+                    current = self.raw.read(to_read)
+                except IOError as e:
+                    if e.errno != EINTR:
+                        raise
+                    continue
+                break
             if current:
                 self._read_buf = self._read_buf[self._read_pos:] + current
                 self._read_pos = 0
@@ -1092,7 +1116,12 @@
         written = 0
         try:
             while self._write_buf:
-                n = self.raw.write(self._write_buf)
+                try:
+                    n = self.raw.write(self._write_buf)
+                except IOError as e:
+                    if e.errno != EINTR:
+                        raise
+                    continue
                 if n > len(self._write_buf) or n < 0:
                     raise IOError("write() returned incorrect number of bytes")
                 del self._write_buf[:n]
@@ -1268,30 +1297,32 @@
     are immutable. There is no public constructor.
     """
 
-    def read(self, n: int = -1) -> str:
-        """Read at most n characters from stream.
+    def read(self, n=-1):
+        """Read at most n characters from stream, where n is an int.
 
         Read from underlying buffer until we have n characters or we hit EOF.
         If n is negative or omitted, read until EOF.
+
+        Returns a string.
         """
         self._unsupported("read")
 
-    def write(self, s: str) -> int:
-        """Write string s to stream."""
+    def write(self, s):
+        """Write string s to stream and returning an int."""
         self._unsupported("write")
 
-    def truncate(self, pos: int = None) -> int:
-        """Truncate size to pos."""
+    def truncate(self, pos=None):
+        """Truncate size to pos, where pos is an int."""
         self._unsupported("truncate")
 
-    def readline(self) -> str:
+    def readline(self):
         """Read until newline or EOF.
 
         Returns an empty string if EOF is hit immediately.
         """
         self._unsupported("readline")
 
-    def detach(self) -> None:
+    def detach(self):
         """
         Separate the underlying buffer from the TextIOBase and return it.
 
@@ -1465,7 +1496,7 @@
             if not isinstance(errors, str):
                 raise ValueError("invalid errors: %r" % errors)
 
-        self.buffer = buffer
+        self._buffer = buffer
         self._line_buffering = line_buffering
         self._encoding = encoding
         self._errors = errors
@@ -1480,6 +1511,7 @@
         self._decoded_chars_used = 0  # offset into _decoded_chars for read()
         self._snapshot = None  # info for reconstructing decoder state
         self._seekable = self._telling = self.buffer.seekable()
+        self._b2cratio = 0.0
 
         if self._seekable and self.writable():
             position = self.buffer.tell()
@@ -1500,13 +1532,20 @@
     #   - "chars_..." for integer variables that count decoded characters
 
     def __repr__(self):
+        result = "<_pyio.TextIOWrapper"
         try:
             name = self.name
         except AttributeError:
-            return "<_pyio.TextIOWrapper encoding={0!r}>".format(self.encoding)
+            pass
         else:
-            return "<_pyio.TextIOWrapper name={0!r} encoding={1!r}>".format(
-                name, self.encoding)
+            result += " name={0!r}".format(name)
+        try:
+            mode = self.mode
+        except AttributeError:
+            pass
+        else:
+            result += " mode={0!r}".format(mode)
+        return result + " encoding={0!r}>".format(self.encoding)
 
     @property
     def encoding(self):
@@ -1520,6 +1559,10 @@
     def line_buffering(self):
         return self._line_buffering
 
+    @property
+    def buffer(self):
+        return self._buffer
+
     def seekable(self):
         return self._seekable
 
@@ -1552,7 +1595,8 @@
     def isatty(self):
         return self.buffer.isatty()
 
-    def write(self, s: str):
+    def write(self, s):
+        'Write data, where s is a str'
         if self.closed:
             raise ValueError("write to closed file")
         if not isinstance(s, str):
@@ -1635,7 +1679,12 @@
         # Read a chunk, decode it, and put the result in self._decoded_chars.
         input_chunk = self.buffer.read1(self._CHUNK_SIZE)
         eof = not input_chunk
-        self._set_decoded_chars(self._decoder.decode(input_chunk, eof))
+        decoded_chars = self._decoder.decode(input_chunk, eof)
+        self._set_decoded_chars(decoded_chars)
+        if decoded_chars:
+            self._b2cratio = len(input_chunk) / len(self._decoded_chars)
+        else:
+            self._b2cratio = 0.0
 
         if self._telling:
             # At the snapshot point, len(dec_buffer) bytes before the read,
@@ -1689,20 +1738,56 @@
         # forward until it gives us enough decoded characters.
         saved_state = decoder.getstate()
         try:
+            # Fast search for an acceptable start point, close to our
+            # current pos.
+            # Rationale: calling decoder.decode() has a large overhead
+            # regardless of chunk size; we want the number of such calls to
+            # be O(1) in most situations (common decoders, non-crazy input).
+            # Actually, it will be exactly 1 for fixed-size codecs (all
+            # 8-bit codecs, also UTF-16 and UTF-32).
+            skip_bytes = int(self._b2cratio * chars_to_skip)
+            skip_back = 1
+            assert skip_bytes <= len(next_input)
+            while skip_bytes > 0:
+                decoder.setstate((b'', dec_flags))
+                # Decode up to temptative start point
+                n = len(decoder.decode(next_input[:skip_bytes]))
+                if n <= chars_to_skip:
+                    b, d = decoder.getstate()
+                    if not b:
+                        # Before pos and no bytes buffered in decoder => OK
+                        dec_flags = d
+                        chars_to_skip -= n
+                        break
+                    # Skip back by buffered amount and reset heuristic
+                    skip_bytes -= len(b)
+                    skip_back = 1
+                else:
+                    # We're too far ahead, skip back a bit
+                    skip_bytes -= skip_back
+                    skip_back = skip_back * 2
+            else:
+                skip_bytes = 0
+                decoder.setstate((b'', dec_flags))
+
             # Note our initial start point.
-            decoder.setstate((b'', dec_flags))
-            start_pos = position
-            start_flags, bytes_fed, chars_decoded = dec_flags, 0, 0
-            need_eof = 0
+            start_pos = position + skip_bytes
+            start_flags = dec_flags
+            if chars_to_skip == 0:
+                # We haven't moved from the start point.
+                return self._pack_cookie(start_pos, start_flags)
 
             # Feed the decoder one byte at a time.  As we go, note the
             # nearest "safe start point" before the current location
             # (a point where the decoder has nothing buffered, so seek()
             # can safely start from there and advance to this location).
-            next_byte = bytearray(1)
-            for next_byte[0] in next_input:
+            bytes_fed = 0
+            need_eof = 0
+            # Chars decoded since `start_pos`
+            chars_decoded = 0
+            for i in range(skip_bytes, len(next_input)):
                 bytes_fed += 1
-                chars_decoded += len(decoder.decode(next_byte))
+                chars_decoded += len(decoder.decode(next_input[i:i+1]))
                 dec_buffer, dec_flags = decoder.getstate()
                 if not dec_buffer and chars_decoded <= chars_to_skip:
                     # Decoder buffer is empty, so this is a safe start point.
@@ -1734,8 +1819,8 @@
         if self.buffer is None:
             raise ValueError("buffer is already detached")
         self.flush()
-        buffer = self.buffer
-        self.buffer = None
+        buffer = self._buffer
+        self._buffer = None
         return buffer
 
     def seek(self, cookie, whence=0):

Modified: python/branches/pep-3151/Lib/_weakrefset.py
==============================================================================
--- python/branches/pep-3151/Lib/_weakrefset.py	(original)
+++ python/branches/pep-3151/Lib/_weakrefset.py	Sat Feb 26 08:16:32 2011
@@ -66,7 +66,11 @@
         return sum(x() is not None for x in self.data)
 
     def __contains__(self, item):
-        return ref(item) in self.data
+        try:
+            wr = ref(item)
+        except TypeError:
+            return False
+        return wr in self.data
 
     def __reduce__(self):
         return (self.__class__, (list(self),),

Modified: python/branches/pep-3151/Lib/abc.py
==============================================================================
--- python/branches/pep-3151/Lib/abc.py	(original)
+++ python/branches/pep-3151/Lib/abc.py	Sat Feb 26 08:16:32 2011
@@ -133,11 +133,14 @@
         return cls
 
     def register(cls, subclass):
-        """Register a virtual subclass of an ABC."""
+        """Register a virtual subclass of an ABC.
+
+        Returns the subclass, to allow usage as a class decorator.
+        """
         if not isinstance(subclass, type):
             raise TypeError("Can only register classes")
         if issubclass(subclass, cls):
-            return  # Already a subclass
+            return subclass  # Already a subclass
         # Subtle: test for cycles *after* testing for "already a subclass";
         # this means we allow X.register(X) and interpret it as a no-op.
         if issubclass(cls, subclass):
@@ -145,6 +148,7 @@
             raise RuntimeError("Refusing to create an inheritance cycle")
         cls._abc_registry.add(subclass)
         ABCMeta._abc_invalidation_counter += 1  # Invalidate negative cache
+        return subclass
 
     def _dump_registry(cls, file=None):
         """Debug helper to print the ABC registry."""

Modified: python/branches/pep-3151/Lib/argparse.py
==============================================================================
--- python/branches/pep-3151/Lib/argparse.py	(original)
+++ python/branches/pep-3151/Lib/argparse.py	Sat Feb 26 08:16:32 2011
@@ -88,7 +88,7 @@
 import sys as _sys
 import textwrap as _textwrap
 
-from gettext import gettext as _
+from gettext import gettext as _, ngettext
 
 
 def _callable(obj):
@@ -1023,9 +1023,13 @@
 
     class _ChoicesPseudoAction(Action):
 
-        def __init__(self, name, help):
+        def __init__(self, name, aliases, help):
+            metavar = dest = name
+            if aliases:
+                metavar += ' (%s)' % ', '.join(aliases)
             sup = super(_SubParsersAction._ChoicesPseudoAction, self)
-            sup.__init__(option_strings=[], dest=name, help=help)
+            sup.__init__(option_strings=[], dest=dest, help=help,
+                         metavar=metavar)
 
     def __init__(self,
                  option_strings,
@@ -1053,15 +1057,22 @@
         if kwargs.get('prog') is None:
             kwargs['prog'] = '%s %s' % (self._prog_prefix, name)
 
+        aliases = kwargs.pop('aliases', ())
+
         # create a pseudo-action to hold the choice help
         if 'help' in kwargs:
             help = kwargs.pop('help')
-            choice_action = self._ChoicesPseudoAction(name, help)
+            choice_action = self._ChoicesPseudoAction(name, aliases, help)
             self._choices_actions.append(choice_action)
 
         # create the parser and add it to the map
         parser = self._parser_class(**kwargs)
         self._name_parser_map[name] = parser
+
+        # make parser available under aliases also
+        for alias in aliases:
+            self._name_parser_map[alias] = parser
+
         return parser
 
     def _get_subactions(self):
@@ -1079,8 +1090,9 @@
         try:
             parser = self._name_parser_map[parser_name]
         except KeyError:
-            tup = parser_name, ', '.join(self._name_parser_map)
-            msg = _('unknown parser %r (choices: %s)' % tup)
+            args = {'parser_name': parser_name,
+                    'choices': ', '.join(self._name_parser_map)}
+            msg = _('unknown parser %(parser_name)r (choices: %(choices)s)') % args
             raise ArgumentError(self, msg)
 
         # parse all the remaining options into the namespace
@@ -1109,7 +1121,7 @@
             the builtin open() function.
     """
 
-    def __init__(self, mode='r', bufsize=None):
+    def __init__(self, mode='r', bufsize=-1):
         self._mode = mode
         self._bufsize = bufsize
 
@@ -1121,18 +1133,19 @@
             elif 'w' in self._mode:
                 return _sys.stdout
             else:
-                msg = _('argument "-" with mode %r' % self._mode)
+                msg = _('argument "-" with mode %r') % self._mode
                 raise ValueError(msg)
 
         # all other arguments are used as file names
-        if self._bufsize:
+        try:
             return open(string, self._mode, self._bufsize)
-        else:
-            return open(string, self._mode)
+        except IOError as e:
+            message = _("can't open '%s': %s")
+            raise ArgumentTypeError(message % (string, e))
 
     def __repr__(self):
-        args = [self._mode, self._bufsize]
-        args_str = ', '.join([repr(arg) for arg in args if arg is not None])
+        args = self._mode, self._bufsize
+        args_str = ', '.join(repr(arg) for arg in args if arg != -1)
         return '%s(%s)' % (type(self).__name__, args_str)
 
 # ===========================
@@ -1380,10 +1393,11 @@
         for option_string in args:
             # error on strings that don't start with an appropriate prefix
             if not option_string[0] in self.prefix_chars:
-                msg = _('invalid option string %r: '
-                        'must start with a character %r')
-                tup = option_string, self.prefix_chars
-                raise ValueError(msg % tup)
+                args = {'option': option_string,
+                        'prefix_chars': self.prefix_chars}
+                msg = _('invalid option string %(option)r: '
+                        'must start with a character %(prefix_chars)r')
+                raise ValueError(msg % args)
 
             # strings starting with two prefix characters are long options
             option_strings.append(option_string)
@@ -1436,7 +1450,9 @@
             conflict_handler(action, confl_optionals)
 
     def _handle_conflict_error(self, action, conflicting_actions):
-        message = _('conflicting option string(s): %s')
+        message = ngettext('conflicting option string: %s',
+                           'conflicting option strings: %s',
+                           len(conflicting_actions))
         conflict_string = ', '.join([option_string
                                      for option_string, action
                                      in conflicting_actions])
@@ -1479,6 +1495,7 @@
         self._defaults = container._defaults
         self._has_negative_number_optionals = \
             container._has_negative_number_optionals
+        self._mutually_exclusive_groups = container._mutually_exclusive_groups
 
     def _add_action(self, action):
         action = super(_ArgumentGroup, self)._add_action(action)
@@ -1993,7 +2010,9 @@
                 OPTIONAL: _('expected at most one argument'),
                 ONE_OR_MORE: _('expected at least one argument'),
             }
-            default = _('expected %s argument(s)') % action.nargs
+            default = ngettext('expected %s argument',
+                               'expected %s arguments',
+                               action.nargs) % action.nargs
             msg = nargs_errors.get(action.nargs, default)
             raise ArgumentError(action, msg)
 
@@ -2049,8 +2068,9 @@
         if len(option_tuples) > 1:
             options = ', '.join([option_string
                 for action, option_string, explicit_arg in option_tuples])
-            tup = arg_string, options
-            self.error(_('ambiguous option: %s could match %s') % tup)
+            args = {'option': arg_string, 'matches': options}
+            msg = _('ambiguous option: %(option)s could match %(matches)s')
+            self.error(msg % args)
 
         # if exactly one action matched, this segmentation is good,
         # so return the parsed action
@@ -2229,8 +2249,9 @@
         # TypeErrors or ValueErrors also indicate errors
         except (TypeError, ValueError):
             name = getattr(action.type, '__name__', repr(action.type))
-            msg = _('invalid %s value: %r')
-            raise ArgumentError(action, msg % (name, arg_string))
+            args = {'type': name, 'value': arg_string}
+            msg = _('invalid %(type)s value: %(value)r')
+            raise ArgumentError(action, msg % args)
 
         # return the converted value
         return result
@@ -2238,9 +2259,10 @@
     def _check_value(self, action, value):
         # converted value must be one of the choices (if specified)
         if action.choices is not None and value not in action.choices:
-            tup = value, ', '.join(map(repr, action.choices))
-            msg = _('invalid choice: %r (choose from %s)') % tup
-            raise ArgumentError(action, msg)
+            args = {'value': value,
+                    'choices': ', '.join(map(repr, action.choices))}
+            msg = _('invalid choice: %(value)r (choose from %(choices)s)')
+            raise ArgumentError(action, msg % args)
 
     # =======================
     # Help-formatting methods
@@ -2332,4 +2354,5 @@
         should either exit or raise an exception.
         """
         self.print_usage(_sys.stderr)
-        self.exit(2, _('%s: error: %s\n') % (self.prog, message))
+        args = {'prog': self.prog, 'message': message}
+        self.exit(2, _('%(prog)s: error: %(message)s\n') % args)

Modified: python/branches/pep-3151/Lib/ast.py
==============================================================================
--- python/branches/pep-3151/Lib/ast.py	(original)
+++ python/branches/pep-3151/Lib/ast.py	Sat Feb 26 08:16:32 2011
@@ -28,12 +28,12 @@
 from _ast import __version__
 
 
-def parse(expr, filename='<unknown>', mode='exec'):
+def parse(source, filename='<unknown>', mode='exec'):
     """
-    Parse an expression into an AST node.
-    Equivalent to compile(expr, filename, mode, PyCF_ONLY_AST).
+    Parse the source into an AST node.
+    Equivalent to compile(source, filename, mode, PyCF_ONLY_AST).
     """
-    return compile(expr, filename, mode, PyCF_ONLY_AST)
+    return compile(source, filename, mode, PyCF_ONLY_AST)
 
 
 def literal_eval(node_or_string):
@@ -159,8 +159,6 @@
     Increment the line number of each node in the tree starting at *node* by *n*.
     This is useful to "move code" to a different location in a file.
     """
-    if 'lineno' in node._attributes:
-        node.lineno = getattr(node, 'lineno', 0) + n
     for child in walk(node):
         if 'lineno' in child._attributes:
             child.lineno = getattr(child, 'lineno', 0) + n
@@ -211,9 +209,9 @@
 
 def walk(node):
     """
-    Recursively yield all child nodes of *node*, in no specified order.  This is
-    useful if you only want to modify nodes in place and don't care about the
-    context.
+    Recursively yield all descendant nodes in the tree starting at *node*
+    (including *node* itself), in no specified order.  This is useful if you
+    only want to modify nodes in place and don't care about the context.
     """
     from collections import deque
     todo = deque([node])

Modified: python/branches/pep-3151/Lib/asynchat.py
==============================================================================
--- python/branches/pep-3151/Lib/asynchat.py	(original)
+++ python/branches/pep-3151/Lib/asynchat.py	Sat Feb 26 08:16:32 2011
@@ -75,7 +75,7 @@
     # sign of an application bug that we don't want to pass silently
 
     use_encoding            = 0
-    encoding                = 'latin1'
+    encoding                = 'latin-1'
 
     def __init__ (self, sock=None, map=None):
         # for string terminator matching

Modified: python/branches/pep-3151/Lib/asyncore.py
==============================================================================
--- python/branches/pep-3151/Lib/asyncore.py	(original)
+++ python/branches/pep-3151/Lib/asyncore.py	Sat Feb 26 08:16:32 2011
@@ -287,7 +287,7 @@
             del map[fd]
         self._fileno = None
 
-    def create_socket(self, family, type):
+    def create_socket(self, family=socket.AF_INET, type=socket.SOCK_STREAM):
         self.family_and_type = family, type
         sock = socket.socket(family, type)
         sock.setblocking(0)

Modified: python/branches/pep-3151/Lib/base64.py
==============================================================================
--- python/branches/pep-3151/Lib/base64.py	(original)
+++ python/branches/pep-3151/Lib/base64.py	Sat Feb 26 08:16:32 2011
@@ -65,16 +65,19 @@
     return encoded
 
 
-def b64decode(s, altchars=None):
+def b64decode(s, altchars=None, validate=False):
     """Decode a Base64 encoded byte string.
 
     s is the byte string to decode.  Optional altchars must be a
     string of length 2 which specifies the alternative alphabet used
     instead of the '+' and '/' characters.
 
-    The decoded byte string is returned.  binascii.Error is raised if
-    s were incorrectly padded or if there are non-alphabet characters
-    present in the string.
+    The decoded string is returned.  A binascii.Error is raised if s is
+    incorrectly padded.
+
+    If validate is False (the default), non-base64-alphabet characters are
+    discarded prior to the padding check.  If validate is True,
+    non-base64-alphabet characters in the input result in a binascii.Error.
     """
     if not isinstance(s, bytes_types):
         raise TypeError("expected bytes, not %s" % s.__class__.__name__)
@@ -84,6 +87,8 @@
                             % altchars.__class__.__name__)
         assert len(altchars) == 2, repr(altchars)
         s = _translate(s, {chr(altchars[0]): b'+', chr(altchars[1]): b'/'})
+    if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
+        raise binascii.Error('Non-base64 digit found')
     return binascii.a2b_base64(s)
 
 

Modified: python/branches/pep-3151/Lib/bdb.py
==============================================================================
--- python/branches/pep-3151/Lib/bdb.py	(original)
+++ python/branches/pep-3151/Lib/bdb.py	Sat Feb 26 08:16:32 2011
@@ -3,16 +3,14 @@
 import fnmatch
 import sys
 import os
-import types
 
-__all__ = ["BdbQuit","Bdb","Breakpoint"]
+__all__ = ["BdbQuit", "Bdb", "Breakpoint"]
 
 class BdbQuit(Exception):
-    """Exception to give up completely"""
+    """Exception to give up completely."""
 
 
 class Bdb:
-
     """Generic Python debugger base class.
 
     This class takes care of details of the trace facility;
@@ -120,14 +118,14 @@
 
     def break_here(self, frame):
         filename = self.canonic(frame.f_code.co_filename)
-        if not filename in self.breaks:
+        if filename not in self.breaks:
             return False
         lineno = frame.f_lineno
-        if not lineno in self.breaks[filename]:
+        if lineno not in self.breaks[filename]:
             # The line itself has no breakpoint, but maybe the line is the
             # first line of a function with breakpoint set by function name.
             lineno = frame.f_code.co_firstlineno
-            if not lineno in self.breaks[filename]:
+            if lineno not in self.breaks[filename]:
                 return False
 
         # flag says ok to delete temp. bp
@@ -170,7 +168,7 @@
     def _set_stopinfo(self, stopframe, returnframe, stoplineno=0):
         self.stopframe = stopframe
         self.returnframe = returnframe
-        self.quitting = 0
+        self.quitting = False
         # stoplineno >= 0 means: stop at line >= the stoplineno
         # stoplineno -1 means: don't stop at all
         self.stoplineno = stoplineno
@@ -227,7 +225,7 @@
     def set_quit(self):
         self.stopframe = self.botframe
         self.returnframe = None
-        self.quitting = 1
+        self.quitting = True
         sys.settrace(None)
 
     # Derived classes and clients can call the following methods
@@ -237,47 +235,47 @@
     # Call self.get_*break*() to see the breakpoints or better
     # for bp in Breakpoint.bpbynumber: if bp: bp.bpprint().
 
-    def set_break(self, filename, lineno, temporary=0, cond = None,
+    def set_break(self, filename, lineno, temporary=False, cond=None,
                   funcname=None):
         filename = self.canonic(filename)
         import linecache # Import as late as possible
         line = linecache.getline(filename, lineno)
         if not line:
-            return 'Line %s:%d does not exist' % (filename,
-                                   lineno)
-        if not filename in self.breaks:
-            self.breaks[filename] = []
-        list = self.breaks[filename]
-        if not lineno in list:
+            return 'Line %s:%d does not exist' % (filename, lineno)
+        list = self.breaks.setdefault(filename, [])
+        if lineno not in list:
             list.append(lineno)
         bp = Breakpoint(filename, lineno, temporary, cond, funcname)
 
+    def _prune_breaks(self, filename, lineno):
+        if (filename, lineno) not in Breakpoint.bplist:
+            self.breaks[filename].remove(lineno)
+        if not self.breaks[filename]:
+            del self.breaks[filename]
+
     def clear_break(self, filename, lineno):
         filename = self.canonic(filename)
-        if not filename in self.breaks:
+        if filename not in self.breaks:
             return 'There are no breakpoints in %s' % filename
         if lineno not in self.breaks[filename]:
-            return 'There is no breakpoint at %s:%d' % (filename,
-                                    lineno)
+            return 'There is no breakpoint at %s:%d' % (filename, lineno)
         # If there's only one bp in the list for that file,line
         # pair, then remove the breaks entry
         for bp in Breakpoint.bplist[filename, lineno][:]:
             bp.deleteMe()
-        if (filename, lineno) not in Breakpoint.bplist:
-            self.breaks[filename].remove(lineno)
-        if not self.breaks[filename]:
-            del self.breaks[filename]
+        self._prune_breaks(filename, lineno)
 
     def clear_bpbynumber(self, arg):
         try:
             bp = self.get_bpbynumber(arg)
         except ValueError as err:
             return str(err)
-        self.clear_break(bp.file, bp.line)
+        bp.deleteMe()
+        self._prune_breaks(bp.file, bp.line)
 
     def clear_all_file_breaks(self, filename):
         filename = self.canonic(filename)
-        if not filename in self.breaks:
+        if filename not in self.breaks:
             return 'There are no breakpoints in %s' % filename
         for line in self.breaks[filename]:
             blist = Breakpoint.bplist[filename, line]
@@ -350,31 +348,30 @@
             i = max(0, len(stack) - 1)
         return stack, i
 
-    #
-
     def format_stack_entry(self, frame_lineno, lprefix=': '):
         import linecache, reprlib
         frame, lineno = frame_lineno
         filename = self.canonic(frame.f_code.co_filename)
         s = '%s(%r)' % (filename, lineno)
         if frame.f_code.co_name:
-            s = s + frame.f_code.co_name
+            s += frame.f_code.co_name
         else:
-            s = s + "<lambda>"
+            s += "<lambda>"
         if '__args__' in frame.f_locals:
             args = frame.f_locals['__args__']
         else:
             args = None
         if args:
-            s = s + reprlib.repr(args)
+            s += reprlib.repr(args)
         else:
-            s = s + '()'
+            s += '()'
         if '__return__' in frame.f_locals:
             rv = frame.f_locals['__return__']
-            s = s + '->'
-            s = s + reprlib.repr(rv)
+            s += '->'
+            s += reprlib.repr(rv)
         line = linecache.getline(filename, lineno, frame.f_globals)
-        if line: s = s + lprefix + line.strip()
+        if line:
+            s += lprefix + line.strip()
         return s
 
     # The following methods can be called by clients to use
@@ -388,13 +385,15 @@
         if locals is None:
             locals = globals
         self.reset()
+        if isinstance(cmd, str):
+            cmd = compile(cmd, "<string>", "exec")
         sys.settrace(self.trace_dispatch)
         try:
             exec(cmd, globals, locals)
         except BdbQuit:
             pass
         finally:
-            self.quitting = 1
+            self.quitting = True
             sys.settrace(None)
 
     def runeval(self, expr, globals=None, locals=None):
@@ -410,7 +409,7 @@
         except BdbQuit:
             pass
         finally:
-            self.quitting = 1
+            self.quitting = True
             sys.settrace(None)
 
     def runctx(self, cmd, globals, locals):
@@ -428,7 +427,7 @@
         except BdbQuit:
             pass
         finally:
-            self.quitting = 1
+            self.quitting = True
             sys.settrace(None)
         return res
 
@@ -438,8 +437,7 @@
 
 
 class Breakpoint:
-
-    """Breakpoint class
+    """Breakpoint class.
 
     Implements temporary breakpoints, ignore counts, disabling and
     (re)-enabling, and conditionals.
@@ -461,7 +459,7 @@
                 # index 0 is unused, except for marking an
                 # effective break .... see effective()
 
-    def __init__(self, file, line, temporary=0, cond=None, funcname=None):
+    def __init__(self, file, line, temporary=False, cond=None, funcname=None):
         self.funcname = funcname
         # Needed if funcname is not None.
         self.func_first_executable_line = None
@@ -469,11 +467,11 @@
         self.line = line
         self.temporary = temporary
         self.cond = cond
-        self.enabled = 1
+        self.enabled = True
         self.ignore = 0
         self.hits = 0
         self.number = Breakpoint.next
-        Breakpoint.next = Breakpoint.next + 1
+        Breakpoint.next += 1
         # Build the two lists
         self.bpbynumber.append(self)
         if (file, line) in self.bplist:
@@ -481,7 +479,6 @@
         else:
             self.bplist[file, line] = [self]
 
-
     def deleteMe(self):
         index = (self.file, self.line)
         self.bpbynumber[self.number] = None   # No longer in list
@@ -491,10 +488,10 @@
             del self.bplist[index]
 
     def enable(self):
-        self.enabled = 1
+        self.enabled = True
 
     def disable(self):
-        self.enabled = 0
+        self.enabled = False
 
     def bpprint(self, out=None):
         if out is None:
@@ -565,49 +562,44 @@
     that indicates if it is ok to delete a temporary bp.
 
     """
-    possibles = Breakpoint.bplist[file,line]
-    for i in range(0, len(possibles)):
-        b = possibles[i]
-        if b.enabled == 0:
+    possibles = Breakpoint.bplist[file, line]
+    for b in possibles:
+        if not b.enabled:
             continue
         if not checkfuncname(b, frame):
             continue
         # Count every hit when bp is enabled
-        b.hits = b.hits + 1
+        b.hits += 1
         if not b.cond:
-            # If unconditional, and ignoring,
-            # go on to next, else break
+            # If unconditional, and ignoring go on to next, else break
             if b.ignore > 0:
-                b.ignore = b.ignore -1
+                b.ignore -= 1
                 continue
             else:
-                # breakpoint and marker that's ok
-                # to delete if temporary
-                return (b,1)
+                # breakpoint and marker that it's ok to delete if temporary
+                return (b, True)
         else:
             # Conditional bp.
             # Ignore count applies only to those bpt hits where the
             # condition evaluates to true.
             try:
-                val = eval(b.cond, frame.f_globals,
-                       frame.f_locals)
+                val = eval(b.cond, frame.f_globals, frame.f_locals)
                 if val:
                     if b.ignore > 0:
-                        b.ignore = b.ignore -1
+                        b.ignore -= 1
                         # continue
                     else:
-                        return (b,1)
+                        return (b, True)
                 # else:
                 #   continue
             except:
-                # if eval fails, most conservative
-                # thing is to stop on breakpoint
-                # regardless of ignore count.
-                # Don't delete temporary,
-                # as another hint to user.
-                return (b,0)
+                # if eval fails, most conservative thing is to stop on
+                # breakpoint regardless of ignore count.  Don't delete
+                # temporary, as another hint to user.
+                return (b, False)
     return (None, None)
 
+
 # -------------------- testing --------------------
 
 class Tdb(Bdb):
@@ -640,5 +632,3 @@
 def test():
     t = Tdb()
     t.run('import bdb; bdb.foo(10)')
-
-# end

Modified: python/branches/pep-3151/Lib/cgi.py
==============================================================================
--- python/branches/pep-3151/Lib/cgi.py	(original)
+++ python/branches/pep-3151/Lib/cgi.py	Sat Feb 26 08:16:32 2011
@@ -31,13 +31,15 @@
 # Imports
 # =======
 
-from io import StringIO
+from io import StringIO, BytesIO, TextIOWrapper
 import sys
 import os
 import urllib.parse
-import email.parser
+from email.parser import FeedParser
 from warnings import warn
 import html
+import locale
+import tempfile
 
 __all__ = ["MiniFieldStorage", "FieldStorage",
            "parse", "parse_qs", "parse_qsl", "parse_multipart",
@@ -109,7 +111,7 @@
 
         Arguments, all optional:
 
-        fp              : file pointer; default: sys.stdin
+        fp              : file pointer; default: sys.stdin.buffer
 
         environ         : environment dictionary; default: os.environ
 
@@ -126,6 +128,18 @@
     """
     if fp is None:
         fp = sys.stdin
+
+    # field keys and values (except for files) are returned as strings
+    # an encoding is required to decode the bytes read from self.fp
+    if hasattr(fp,'encoding'):
+        encoding = fp.encoding
+    else:
+        encoding = 'latin-1'
+
+    # fp.read() must return bytes
+    if isinstance(fp, TextIOWrapper):
+        fp = fp.buffer
+
     if not 'REQUEST_METHOD' in environ:
         environ['REQUEST_METHOD'] = 'GET'       # For testing stand-alone
     if environ['REQUEST_METHOD'] == 'POST':
@@ -136,7 +150,7 @@
             clength = int(environ['CONTENT_LENGTH'])
             if maxlen and clength > maxlen:
                 raise ValueError('Maximum content length exceeded')
-            qs = fp.read(clength)
+            qs = fp.read(clength).decode(encoding)
         else:
             qs = ''                     # Unknown content-type
         if 'QUERY_STRING' in environ:
@@ -154,7 +168,8 @@
         else:
             qs = ""
         environ['QUERY_STRING'] = qs    # XXX Shouldn't, really
-    return urllib.parse.parse_qs(qs, keep_blank_values, strict_parsing)
+    return urllib.parse.parse_qs(qs, keep_blank_values, strict_parsing,
+                                 encoding=encoding)
 
 
 # parse query string function called from urlparse,
@@ -236,8 +251,8 @@
             if not line:
                 terminator = lastpart # End outer loop
                 break
-            if line[:2] == "--":
-                terminator = line.strip()
+            if line.startswith("--"):
+                terminator = line.rstrip()
                 if terminator in (nextpart, lastpart):
                     break
             lines.append(line)
@@ -352,9 +367,10 @@
 
     value: the value as a *string*; for file uploads, this
         transparently reads the file every time you request the value
+        and returns *bytes*
 
-    file: the file(-like) object from which you can read the data;
-        None if the data is stored a simple string
+    file: the file(-like) object from which you can read the data *as
+        bytes* ; None if the data is stored a simple string
 
     type: the content-type, or None if not specified
 
@@ -375,15 +391,18 @@
     directory and unlinking them as soon as they have been opened.
 
     """
-
-    def __init__(self, fp=None, headers=None, outerboundary="",
-                 environ=os.environ, keep_blank_values=0, strict_parsing=0):
+    def __init__(self, fp=None, headers=None, outerboundary=b'',
+                 environ=os.environ, keep_blank_values=0, strict_parsing=0,
+                 limit=None, encoding='utf-8', errors='replace'):
         """Constructor.  Read multipart/* until last part.
 
         Arguments, all optional:
 
-        fp              : file pointer; default: sys.stdin
+        fp              : file pointer; default: sys.stdin.buffer
             (not used when the request method is GET)
+            Can be :
+            1. a TextIOWrapper object
+            2. an object whose read() and readline() methods return bytes
 
         headers         : header dictionary-like object; default:
             taken from environ as per CGI spec
@@ -404,6 +423,16 @@
             If false (the default), errors are silently ignored.
             If true, errors raise a ValueError exception.
 
+        limit : used internally to read parts of multipart/form-data forms,
+            to exit from the reading loop when reached. It is the difference
+            between the form content-length and the number of bytes already
+            read
+
+        encoding, errors : the encoding and error handler used to decode the
+            binary stream to strings. Must be the same as the charset defined
+            for the page sending the form (content-type : meta http-equiv or
+            header)
+
         """
         method = 'GET'
         self.keep_blank_values = keep_blank_values
@@ -418,7 +447,8 @@
                 qs = sys.argv[1]
             else:
                 qs = ""
-            fp = StringIO(qs)
+            qs = qs.encode(locale.getpreferredencoding(), 'surrogateescape')
+            fp = BytesIO(qs)
             if headers is None:
                 headers = {'content-type':
                            "application/x-www-form-urlencoded"}
@@ -433,10 +463,26 @@
                 self.qs_on_post = environ['QUERY_STRING']
             if 'CONTENT_LENGTH' in environ:
                 headers['content-length'] = environ['CONTENT_LENGTH']
-        self.fp = fp or sys.stdin
+        if fp is None:
+            self.fp = sys.stdin.buffer
+        # self.fp.read() must return bytes
+        elif isinstance(fp, TextIOWrapper):
+            self.fp = fp.buffer
+        else:
+            self.fp = fp
+
+        self.encoding = encoding
+        self.errors = errors
+
         self.headers = headers
+        if not isinstance(outerboundary, bytes):
+            raise TypeError('outerboundary must be bytes, not %s'
+                            % type(outerboundary).__name__)
         self.outerboundary = outerboundary
 
+        self.bytes_read = 0
+        self.limit = limit
+
         # Process content-disposition header
         cdisp, pdict = "", {}
         if 'content-disposition' in self.headers:
@@ -449,6 +495,7 @@
         self.filename = None
         if 'filename' in pdict:
             self.filename = pdict['filename']
+        self._binary_file = self.filename is not None
 
         # Process content-type header
         #
@@ -470,9 +517,11 @@
             ctype, pdict = 'application/x-www-form-urlencoded', {}
         self.type = ctype
         self.type_options = pdict
-        self.innerboundary = ""
         if 'boundary' in pdict:
-            self.innerboundary = pdict['boundary']
+            self.innerboundary = pdict['boundary'].encode(self.encoding)
+        else:
+            self.innerboundary = b""
+
         clen = -1
         if 'content-length' in self.headers:
             try:
@@ -482,6 +531,8 @@
             if maxlen and clen > maxlen:
                 raise ValueError('Maximum content length exceeded')
         self.length = clen
+        if self.limit is None and clen:
+            self.limit = clen
 
         self.list = self.file = None
         self.done = 0
@@ -531,7 +582,7 @@
         """Dictionary style get() method, including 'value' lookup."""
         if key in self:
             value = self[key]
-            if type(value) is type([]):
+            if isinstance(value, list):
                 return [x.value for x in value]
             else:
                 return value.value
@@ -542,7 +593,7 @@
         """ Return the first value received."""
         if key in self:
             value = self[key]
-            if type(value) is type([]):
+            if isinstance(value, list):
                 return value[0].value
             else:
                 return value.value
@@ -553,7 +604,7 @@
         """ Return list of received values."""
         if key in self:
             value = self[key]
-            if type(value) is type([]):
+            if isinstance(value, list):
                 return [x.value for x in value]
             else:
                 return [value.value]
@@ -582,12 +633,18 @@
     def read_urlencoded(self):
         """Internal: read data in query string format."""
         qs = self.fp.read(self.length)
+        if not isinstance(qs, bytes):
+            raise ValueError("%s should return bytes, got %s" \
+                             % (self.fp, type(qs).__name__))
+        qs = qs.decode(self.encoding, self.errors)
         if self.qs_on_post:
             qs += '&' + self.qs_on_post
-        self.list = list = []
-        for key, value in urllib.parse.parse_qsl(qs, self.keep_blank_values,
-                                self.strict_parsing):
-            list.append(MiniFieldStorage(key, value))
+        self.list = []
+        query = urllib.parse.parse_qsl(
+            qs, self.keep_blank_values, self.strict_parsing,
+            encoding=self.encoding, errors=self.errors)
+        for key, value in query:
+            self.list.append(MiniFieldStorage(key, value))
         self.skip_lines()
 
     FieldStorageClass = None
@@ -599,24 +656,42 @@
             raise ValueError('Invalid boundary in multipart form: %r' % (ib,))
         self.list = []
         if self.qs_on_post:
-            for key, value in urllib.parse.parse_qsl(self.qs_on_post,
-                                    self.keep_blank_values, self.strict_parsing):
+            query = urllib.parse.parse_qsl(
+                self.qs_on_post, self.keep_blank_values, self.strict_parsing,
+                encoding=self.encoding, errors=self.errors)
+            for key, value in query:
                 self.list.append(MiniFieldStorage(key, value))
             FieldStorageClass = None
 
         klass = self.FieldStorageClass or self.__class__
-        parser = email.parser.FeedParser()
-        # Create bogus content-type header for proper multipart parsing
-        parser.feed('Content-Type: %s; boundary=%s\r\n\r\n' % (self.type, ib))
-        parser.feed(self.fp.read())
-        full_msg = parser.close()
-        # Get subparts
-        msgs = full_msg.get_payload()
-        for msg in msgs:
-            fp = StringIO(msg.get_payload())
-            part = klass(fp, msg, ib, environ, keep_blank_values,
-                         strict_parsing)
+        first_line = self.fp.readline() # bytes
+        if not isinstance(first_line, bytes):
+            raise ValueError("%s should return bytes, got %s" \
+                             % (self.fp, type(first_line).__name__))
+        self.bytes_read += len(first_line)
+        # first line holds boundary ; ignore it, or check that
+        # b"--" + ib == first_line.strip() ?
+        while True:
+            parser = FeedParser()
+            hdr_text = b""
+            while True:
+                data = self.fp.readline()
+                hdr_text += data
+                if not data.strip():
+                    break
+            if not hdr_text:
+                break
+            # parser takes strings, not bytes
+            self.bytes_read += len(hdr_text)
+            parser.feed(hdr_text.decode(self.encoding, self.errors))
+            headers = parser.close()
+            part = klass(self.fp, headers, ib, environ, keep_blank_values,
+                         strict_parsing,self.limit-self.bytes_read,
+                         self.encoding, self.errors)
+            self.bytes_read += part.bytes_read
             self.list.append(part)
+            if self.bytes_read >= self.length:
+                break
         self.skip_lines()
 
     def read_single(self):
@@ -636,7 +711,11 @@
         todo = self.length
         if todo >= 0:
             while todo > 0:
-                data = self.fp.read(min(todo, self.bufsize))
+                data = self.fp.read(min(todo, self.bufsize)) # bytes
+                if not isinstance(data, bytes):
+                    raise ValueError("%s should return bytes, got %s"
+                                     % (self.fp, type(data).__name__))
+                self.bytes_read += len(data)
                 if not data:
                     self.done = -1
                     break
@@ -645,59 +724,77 @@
 
     def read_lines(self):
         """Internal: read lines until EOF or outerboundary."""
-        self.file = self.__file = StringIO()
+        if self._binary_file:
+            self.file = self.__file = BytesIO() # store data as bytes for files
+        else:
+            self.file = self.__file = StringIO() # as strings for other fields
         if self.outerboundary:
             self.read_lines_to_outerboundary()
         else:
             self.read_lines_to_eof()
 
     def __write(self, line):
+        """line is always bytes, not string"""
         if self.__file is not None:
             if self.__file.tell() + len(line) > 1000:
                 self.file = self.make_file()
                 data = self.__file.getvalue()
                 self.file.write(data)
                 self.__file = None
-        self.file.write(line)
+        if self._binary_file:
+            # keep bytes
+            self.file.write(line)
+        else:
+            # decode to string
+            self.file.write(line.decode(self.encoding, self.errors))
 
     def read_lines_to_eof(self):
         """Internal: read lines until EOF."""
         while 1:
-            line = self.fp.readline(1<<16)
+            line = self.fp.readline(1<<16) # bytes
+            self.bytes_read += len(line)
             if not line:
                 self.done = -1
                 break
             self.__write(line)
 
     def read_lines_to_outerboundary(self):
-        """Internal: read lines until outerboundary."""
-        next = "--" + self.outerboundary
-        last = next + "--"
-        delim = ""
+        """Internal: read lines until outerboundary.
+        Data is read as bytes: boundaries and line ends must be converted
+        to bytes for comparisons.
+        """
+        next_boundary = b"--" + self.outerboundary
+        last_boundary = next_boundary + b"--"
+        delim = b""
         last_line_lfend = True
+        _read = 0
         while 1:
-            line = self.fp.readline(1<<16)
+            if _read >= self.limit:
+                break
+            line = self.fp.readline(1<<16) # bytes
+            self.bytes_read += len(line)
+            _read += len(line)
             if not line:
                 self.done = -1
                 break
-            if line[:2] == "--" and last_line_lfend:
-                strippedline = line.strip()
-                if strippedline == next:
+            if line.startswith(b"--") and last_line_lfend:
+                strippedline = line.rstrip()
+                if strippedline == next_boundary:
                     break
-                if strippedline == last:
+                if strippedline == last_boundary:
                     self.done = 1
                     break
             odelim = delim
-            if line[-2:] == "\r\n":
-                delim = "\r\n"
+            if line.endswith(b"\r\n"):
+                delim = b"\r\n"
                 line = line[:-2]
                 last_line_lfend = True
-            elif line[-1] == "\n":
-                delim = "\n"
+            elif line.endswith(b"\n"):
+                delim = b"\n"
                 line = line[:-1]
                 last_line_lfend = True
             else:
-                delim = ""
+                delim = b""
                 last_line_lfend = False
             self.__write(odelim + line)
 
@@ -705,22 +802,23 @@
         """Internal: skip lines until outer boundary if defined."""
         if not self.outerboundary or self.done:
             return
-        next = "--" + self.outerboundary
-        last = next + "--"
+        next_boundary = b"--" + self.outerboundary
+        last_boundary = next_boundary + b"--"
         last_line_lfend = True
-        while 1:
+        while True:
             line = self.fp.readline(1<<16)
+            self.bytes_read += len(line)
             if not line:
                 self.done = -1
                 break
-            if line[:2] == "--" and last_line_lfend:
+            if line.endswith(b"--") and last_line_lfend:
                 strippedline = line.strip()
-                if strippedline == next:
+                if strippedline == next_boundary:
                     break
-                if strippedline == last:
+                if strippedline == last_boundary:
                     self.done = 1
                     break
-            last_line_lfend = line.endswith('\n')
+            last_line_lfend = line.endswith(b'\n')
 
     def make_file(self):
         """Overridable: return a readable & writable file.
@@ -730,7 +828,8 @@
         - seek(0)
         - data is read from it
 
-        The file is always opened in text mode.
+        The file is opened in binary mode for files, in text mode
+        for other fields
 
         This version opens a temporary file for reading and writing,
         and immediately deletes (unlinks) it.  The trick (on Unix!) is
@@ -745,8 +844,11 @@
         which unlinks the temporary files you have created.
 
         """
-        import tempfile
-        return tempfile.TemporaryFile("w+", encoding="utf-8", newline="\n")
+        if self._binary_file:
+            return tempfile.TemporaryFile("wb+")
+        else:
+            return tempfile.TemporaryFile("w+",
+                encoding=self.encoding, newline = '\n')
 
 
 # Test/debug code
@@ -910,8 +1012,12 @@
     return s
 
 
-def valid_boundary(s, _vb_pattern="^[ -~]{0,200}[!-~]$"):
+def valid_boundary(s, _vb_pattern=None):
     import re
+    if isinstance(s, bytes):
+        _vb_pattern = b"^[ -~]{0,200}[!-~]$"
+    else:
+        _vb_pattern = "^[ -~]{0,200}[!-~]$"
     return re.match(_vb_pattern, s)
 
 # Invoke mainline

Modified: python/branches/pep-3151/Lib/codecs.py
==============================================================================
--- python/branches/pep-3151/Lib/codecs.py	(original)
+++ python/branches/pep-3151/Lib/codecs.py	Sat Feb 26 08:16:32 2011
@@ -396,6 +396,8 @@
 
 class StreamReader(Codec):
 
+    charbuffertype = str
+
     def __init__(self, stream, errors='strict'):
 
         """ Creates a StreamReader instance.
@@ -417,9 +419,8 @@
         self.stream = stream
         self.errors = errors
         self.bytebuffer = b""
-        # For str->str decoding this will stay a str
-        # For str->unicode decoding the first read will promote it to unicode
-        self.charbuffer = ""
+        self._empty_charbuffer = self.charbuffertype()
+        self.charbuffer = self._empty_charbuffer
         self.linebuffer = None
 
     def decode(self, input, errors='strict'):
@@ -455,7 +456,7 @@
         """
         # If we have lines cached, first merge them back into characters
         if self.linebuffer:
-            self.charbuffer = "".join(self.linebuffer)
+            self.charbuffer = self._empty_charbuffer.join(self.linebuffer)
             self.linebuffer = None
 
         # read until we get the required number of characters (if available)
@@ -498,7 +499,7 @@
         if chars < 0:
             # Return everything we've got
             result = self.charbuffer
-            self.charbuffer = ""
+            self.charbuffer = self._empty_charbuffer
         else:
             # Return the first chars characters
             result = self.charbuffer[:chars]
@@ -529,7 +530,7 @@
             return line
 
         readsize = size or 72
-        line = ""
+        line = self._empty_charbuffer
         # If size is given, we call read() only once
         while True:
             data = self.read(readsize, firstline=True)
@@ -537,7 +538,8 @@
                 # If we're at a "\r" read one extra character (which might
                 # be a "\n") to get a proper line ending. If the stream is
                 # temporarily exhausted we return the wrong line ending.
-                if data.endswith("\r"):
+                if (isinstance(data, str) and data.endswith("\r")) or \
+                   (isinstance(data, bytes) and data.endswith(b"\r")):
                     data += self.read(size=1, chars=1)
 
             line += data
@@ -563,7 +565,8 @@
                 line0withoutend = lines[0].splitlines(False)[0]
                 if line0withend != line0withoutend: # We really have a line end
                     # Put the rest back together and keep it until the next call
-                    self.charbuffer = "".join(lines[1:]) + self.charbuffer
+                    self.charbuffer = self._empty_charbuffer.join(lines[1:]) + \
+                                      self.charbuffer
                     if keepends:
                         line = line0withend
                     else:
@@ -574,7 +577,7 @@
                 if line and not keepends:
                     line = line.splitlines(False)[0]
                 break
-            if readsize<8000:
+            if readsize < 8000:
                 readsize *= 2
         return line
 
@@ -603,7 +606,7 @@
 
         """
         self.bytebuffer = b""
-        self.charbuffer = ""
+        self.charbuffer = self._empty_charbuffer
         self.linebuffer = None
 
     def seek(self, offset, whence=0):

Deleted: python/branches/pep-3151/Lib/collections.py
==============================================================================
--- python/branches/pep-3151/Lib/collections.py	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,911 +0,0 @@
-__all__ = ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList',
-            'UserString', 'Counter', 'OrderedDict']
-# For bootstrapping reasons, the collection ABCs are defined in _abcoll.py.
-# They should however be considered an integral part of collections.py.
-from _abcoll import *
-import _abcoll
-__all__ += _abcoll.__all__
-
-from _collections import deque, defaultdict
-from operator import itemgetter as _itemgetter
-from keyword import iskeyword as _iskeyword
-import sys as _sys
-import heapq as _heapq
-from weakref import proxy as _proxy
-from itertools import repeat as _repeat, chain as _chain, starmap as _starmap
-from reprlib import recursive_repr as _recursive_repr
-
-################################################################################
-### OrderedDict
-################################################################################
-
-class _Link(object):
-    __slots__ = 'prev', 'next', 'key', '__weakref__'
-
-class OrderedDict(dict, MutableMapping):
-    'Dictionary that remembers insertion order'
-    # An inherited dict maps keys to values.
-    # The inherited dict provides __getitem__, __len__, __contains__, and get.
-    # The remaining methods are order-aware.
-    # Big-O running times for all methods are the same as for regular dictionaries.
-
-    # The internal self.__map dictionary maps keys to links in a doubly linked list.
-    # The circular doubly linked list starts and ends with a sentinel element.
-    # The sentinel element never gets deleted (this simplifies the algorithm).
-    # The sentinel is stored in self.__hardroot with a weakref proxy in self.__root.
-    # The prev/next links are weakref proxies (to prevent circular references).
-    # Individual links are kept alive by the hard reference in self.__map.
-    # Those hard references disappear when a key is deleted from an OrderedDict.
-
-    def __init__(self, *args, **kwds):
-        '''Initialize an ordered dictionary.  Signature is the same as for
-        regular dictionaries, but keyword arguments are not recommended
-        because their insertion order is arbitrary.
-
-        '''
-        if len(args) > 1:
-            raise TypeError('expected at most 1 arguments, got %d' % len(args))
-        try:
-            self.__root
-        except AttributeError:
-            self.__hardroot = _Link()
-            self.__root = root = _proxy(self.__hardroot)
-            root.prev = root.next = root
-            self.__map = {}
-        self.update(*args, **kwds)
-
-    def __setitem__(self, key, value,
-                    dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
-        'od.__setitem__(i, y) <==> od[i]=y'
-        # Setting a new item creates a new link which goes at the end of the linked
-        # list, and the inherited dictionary is updated with the new key/value pair.
-        if key not in self:
-            self.__map[key] = link = Link()
-            root = self.__root
-            last = root.prev
-            link.prev, link.next, link.key = last, root, key
-            last.next = link
-            root.prev = proxy(link)
-        dict_setitem(self, key, value)
-
-    def __delitem__(self, key, dict_delitem=dict.__delitem__):
-        'od.__delitem__(y) <==> del od[y]'
-        # Deleting an existing item uses self.__map to find the link which is
-        # then removed by updating the links in the predecessor and successor nodes.
-        dict_delitem(self, key)
-        link = self.__map.pop(key)
-        link_prev = link.prev
-        link_next = link.next
-        link_prev.next = link_next
-        link_next.prev = link_prev
-
-    def __iter__(self):
-        'od.__iter__() <==> iter(od)'
-        # Traverse the linked list in order.
-        root = self.__root
-        curr = root.next
-        while curr is not root:
-            yield curr.key
-            curr = curr.next
-
-    def __reversed__(self):
-        'od.__reversed__() <==> reversed(od)'
-        # Traverse the linked list in reverse order.
-        root = self.__root
-        curr = root.prev
-        while curr is not root:
-            yield curr.key
-            curr = curr.prev
-
-    def clear(self):
-        'od.clear() -> None.  Remove all items from od.'
-        root = self.__root
-        root.prev = root.next = root
-        self.__map.clear()
-        dict.clear(self)
-
-    def popitem(self, last=True):
-        '''od.popitem() -> (k, v), return and remove a (key, value) pair.
-        Pairs are returned in LIFO order if last is true or FIFO order if false.
-
-        '''
-        if not self:
-            raise KeyError('dictionary is empty')
-        root = self.__root
-        if last:
-            link = root.prev
-            link_prev = link.prev
-            link_prev.next = root
-            root.prev = link_prev
-        else:
-            link = root.next
-            link_next = link.next
-            root.next = link_next
-            link_next.prev = root
-        key = link.key
-        del self.__map[key]
-        value = dict.pop(self, key)
-        return key, value
-
-    def move_to_end(self, key, last=True):
-        '''Move an existing element to the end (or beginning if last==False).
-
-        Raises KeyError if the element does not exist.
-        When last=True, acts like a fast version of self[key]=self.pop(key).
-
-        '''
-        link = self.__map[key]
-        link_prev = link.prev
-        link_next = link.next
-        link_prev.next = link_next
-        link_next.prev = link_prev
-        root = self.__root
-        if last:
-            last = root.prev
-            link.prev = last
-            link.next = root
-            last.next = root.prev = link
-        else:
-            first = root.next
-            link.prev = root
-            link.next = first
-            root.next = first.prev = link
-
-    def __reduce__(self):
-        'Return state information for pickling'
-        items = [[k, self[k]] for k in self]
-        tmp = self.__map, self.__root, self.__hardroot
-        del self.__map, self.__root, self.__hardroot
-        inst_dict = vars(self).copy()
-        self.__map, self.__root, self.__hardroot = tmp
-        if inst_dict:
-            return (self.__class__, (items,), inst_dict)
-        return self.__class__, (items,)
-
-    def __sizeof__(self):
-        sizeof = _sys.getsizeof
-        n = len(self) + 1                       # number of links including root
-        size = sizeof(self.__dict__)            # instance dictionary
-        size += sizeof(self.__map) * 2          # internal dict and inherited dict
-        size += sizeof(self.__hardroot) * n     # link objects
-        size += sizeof(self.__root) * n         # proxy objects
-        return size
-
-    setdefault = MutableMapping.setdefault
-    update = MutableMapping.update
-    pop = MutableMapping.pop
-    keys = MutableMapping.keys
-    values = MutableMapping.values
-    items = MutableMapping.items
-    __ne__ = MutableMapping.__ne__
-
-    @_recursive_repr()
-    def __repr__(self):
-        'od.__repr__() <==> repr(od)'
-        if not self:
-            return '%s()' % (self.__class__.__name__,)
-        return '%s(%r)' % (self.__class__.__name__, list(self.items()))
-
-    def copy(self):
-        'od.copy() -> a shallow copy of od'
-        return self.__class__(self)
-
-    @classmethod
-    def fromkeys(cls, iterable, value=None):
-        '''OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
-        and values equal to v (which defaults to None).
-
-        '''
-        d = cls()
-        for key in iterable:
-            d[key] = value
-        return d
-
-    def __eq__(self, other):
-        '''od.__eq__(y) <==> od==y.  Comparison to another OD is order-sensitive
-        while comparison to a regular mapping is order-insensitive.
-
-        '''
-        if isinstance(other, OrderedDict):
-            return len(self)==len(other) and \
-                   all(p==q for p, q in zip(self.items(), other.items()))
-        return dict.__eq__(self, other)
-
-
-################################################################################
-### namedtuple
-################################################################################
-
-def namedtuple(typename, field_names, verbose=False, rename=False):
-    """Returns a new subclass of tuple with named fields.
-
-    >>> Point = namedtuple('Point', 'x y')
-    >>> Point.__doc__                   # docstring for the new class
-    'Point(x, y)'
-    >>> p = Point(11, y=22)             # instantiate with positional args or keywords
-    >>> p[0] + p[1]                     # indexable like a plain tuple
-    33
-    >>> x, y = p                        # unpack like a regular tuple
-    >>> x, y
-    (11, 22)
-    >>> p.x + p.y                       # fields also accessable by name
-    33
-    >>> d = p._asdict()                 # convert to a dictionary
-    >>> d['x']
-    11
-    >>> Point(**d)                      # convert from a dictionary
-    Point(x=11, y=22)
-    >>> p._replace(x=100)               # _replace() is like str.replace() but targets named fields
-    Point(x=100, y=22)
-
-    """
-
-    # Parse and validate the field names.  Validation serves two purposes,
-    # generating informative error messages and preventing template injection attacks.
-    if isinstance(field_names, str):
-        field_names = field_names.replace(',', ' ').split() # names separated by whitespace and/or commas
-    field_names = tuple(map(str, field_names))
-    if rename:
-        names = list(field_names)
-        seen = set()
-        for i, name in enumerate(names):
-            if (not all(c.isalnum() or c=='_' for c in name) or _iskeyword(name)
-                or not name or name[0].isdigit() or name.startswith('_')
-                or name in seen):
-                names[i] = '_%d' % i
-            seen.add(name)
-        field_names = tuple(names)
-    for name in (typename,) + field_names:
-        if not all(c.isalnum() or c=='_' for c in name):
-            raise ValueError('Type names and field names can only contain alphanumeric characters and underscores: %r' % name)
-        if _iskeyword(name):
-            raise ValueError('Type names and field names cannot be a keyword: %r' % name)
-        if name[0].isdigit():
-            raise ValueError('Type names and field names cannot start with a number: %r' % name)
-    seen_names = set()
-    for name in field_names:
-        if name.startswith('_') and not rename:
-            raise ValueError('Field names cannot start with an underscore: %r' % name)
-        if name in seen_names:
-            raise ValueError('Encountered duplicate field name: %r' % name)
-        seen_names.add(name)
-
-    # Create and fill-in the class template
-    numfields = len(field_names)
-    argtxt = repr(field_names).replace("'", "")[1:-1]   # tuple repr without parens or quotes
-    reprtxt = ', '.join('%s=%%r' % name for name in field_names)
-    template = '''class %(typename)s(tuple):
-        '%(typename)s(%(argtxt)s)' \n
-        __slots__ = () \n
-        _fields = %(field_names)r \n
-        def __new__(_cls, %(argtxt)s):
-            'Create new instance of %(typename)s(%(argtxt)s)'
-            return _tuple.__new__(_cls, (%(argtxt)s)) \n
-        @classmethod
-        def _make(cls, iterable, new=tuple.__new__, len=len):
-            'Make a new %(typename)s object from a sequence or iterable'
-            result = new(cls, iterable)
-            if len(result) != %(numfields)d:
-                raise TypeError('Expected %(numfields)d arguments, got %%d' %% len(result))
-            return result \n
-        def __repr__(self):
-            'Return a nicely formatted representation string'
-            return self.__class__.__name__ + '(%(reprtxt)s)' %% self \n
-        def _asdict(self):
-            'Return a new OrderedDict which maps field names to their values'
-            return OrderedDict(zip(self._fields, self)) \n
-        def _replace(_self, **kwds):
-            'Return a new %(typename)s object replacing specified fields with new values'
-            result = _self._make(map(kwds.pop, %(field_names)r, _self))
-            if kwds:
-                raise ValueError('Got unexpected field names: %%r' %% kwds.keys())
-            return result \n
-        def __getnewargs__(self):
-            'Return self as a plain tuple.  Used by copy and pickle.'
-            return tuple(self) \n\n''' % locals()
-    for i, name in enumerate(field_names):
-        template += "        %s = _property(_itemgetter(%d), doc='Alias for field number %d')\n" % (name, i, i)
-    if verbose:
-        print(template)
-
-    # Execute the template string in a temporary namespace and
-    # support tracing utilities by setting a value for frame.f_globals['__name__']
-    namespace = dict(_itemgetter=_itemgetter, __name__='namedtuple_%s' % typename,
-                     OrderedDict=OrderedDict, _property=property, _tuple=tuple)
-    try:
-        exec(template, namespace)
-    except SyntaxError as e:
-        raise SyntaxError(e.msg + ':\n\n' + template)
-    result = namespace[typename]
-
-    # For pickling to work, the __module__ variable needs to be set to the frame
-    # where the named tuple is created.  Bypass this step in enviroments where
-    # sys._getframe is not defined (Jython for example) or sys._getframe is not
-    # defined for arguments greater than 0 (IronPython).
-    try:
-        result.__module__ = _sys._getframe(1).f_globals.get('__name__', '__main__')
-    except (AttributeError, ValueError):
-        pass
-
-    return result
-
-
-########################################################################
-###  Counter
-########################################################################
-
-class Counter(dict):
-    '''Dict subclass for counting hashable items.  Sometimes called a bag
-    or multiset.  Elements are stored as dictionary keys and their counts
-    are stored as dictionary values.
-
-    >>> c = Counter('abracadabra')      # count elements from a string
-
-    >>> c.most_common(3)                # three most common elements
-    [('a', 5), ('r', 2), ('b', 2)]
-    >>> sorted(c)                       # list all unique elements
-    ['a', 'b', 'c', 'd', 'r']
-    >>> ''.join(sorted(c.elements()))   # list elements with repetitions
-    'aaaaabbcdrr'
-    >>> sum(c.values())                 # total of all counts
-    11
-
-    >>> c['a']                          # count of letter 'a'
-    5
-    >>> for elem in 'shazam':           # update counts from an iterable
-    ...     c[elem] += 1                # by adding 1 to each element's count
-    >>> c['a']                          # now there are seven 'a'
-    7
-    >>> del c['r']                      # remove all 'r'
-    >>> c['r']                          # now there are zero 'r'
-    0
-
-    >>> d = Counter('simsalabim')       # make another counter
-    >>> c.update(d)                     # add in the second counter
-    >>> c['a']                          # now there are nine 'a'
-    9
-
-    >>> c.clear()                       # empty the counter
-    >>> c
-    Counter()
-
-    Note:  If a count is set to zero or reduced to zero, it will remain
-    in the counter until the entry is deleted or the counter is cleared:
-
-    >>> c = Counter('aaabbc')
-    >>> c['b'] -= 2                     # reduce the count of 'b' by two
-    >>> c.most_common()                 # 'b' is still in, but its count is zero
-    [('a', 3), ('c', 1), ('b', 0)]
-
-    '''
-    # References:
-    #   http://en.wikipedia.org/wiki/Multiset
-    #   http://www.gnu.org/software/smalltalk/manual-base/html_node/Bag.html
-    #   http://www.demo2s.com/Tutorial/Cpp/0380__set-multiset/Catalog0380__set-multiset.htm
-    #   http://code.activestate.com/recipes/259174/
-    #   Knuth, TAOCP Vol. II section 4.6.3
-
-    def __init__(self, iterable=None, **kwds):
-        '''Create a new, empty Counter object.  And if given, count elements
-        from an input iterable.  Or, initialize the count from another mapping
-        of elements to their counts.
-
-        >>> c = Counter()                           # a new, empty counter
-        >>> c = Counter('gallahad')                 # a new counter from an iterable
-        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping
-        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args
-
-        '''
-        self.update(iterable, **kwds)
-
-    def __missing__(self, key):
-        'The count of elements not in the Counter is zero.'
-        # Needed so that self[missing_item] does not raise KeyError
-        return 0
-
-    def most_common(self, n=None):
-        '''List the n most common elements and their counts from the most
-        common to the least.  If n is None, then list all element counts.
-
-        >>> Counter('abracadabra').most_common(3)
-        [('a', 5), ('r', 2), ('b', 2)]
-
-        '''
-        # Emulate Bag.sortedByCount from Smalltalk
-        if n is None:
-            return sorted(self.items(), key=_itemgetter(1), reverse=True)
-        return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
-
-    def elements(self):
-        '''Iterator over elements repeating each as many times as its count.
-
-        >>> c = Counter('ABCABC')
-        >>> sorted(c.elements())
-        ['A', 'A', 'B', 'B', 'C', 'C']
-
-        # Knuth's example for prime factors of 1836:  2**2 * 3**3 * 17**1
-        >>> prime_factors = Counter({2: 2, 3: 3, 17: 1})
-        >>> product = 1
-        >>> for factor in prime_factors.elements():     # loop over factors
-        ...     product *= factor                       # and multiply them
-        >>> product
-        1836
-
-        Note, if an element's count has been set to zero or is a negative
-        number, elements() will ignore it.
-
-        '''
-        # Emulate Bag.do from Smalltalk and Multiset.begin from C++.
-        return _chain.from_iterable(_starmap(_repeat, self.items()))
-
-    # Override dict methods where necessary
-
-    @classmethod
-    def fromkeys(cls, iterable, v=None):
-        # There is no equivalent method for counters because setting v=1
-        # means that no element can have a count greater than one.
-        raise NotImplementedError(
-            'Counter.fromkeys() is undefined.  Use Counter(iterable) instead.')
-
-    def update(self, iterable=None, **kwds):
-        '''Like dict.update() but add counts instead of replacing them.
-
-        Source can be an iterable, a dictionary, or another Counter instance.
-
-        >>> c = Counter('which')
-        >>> c.update('witch')           # add elements from another iterable
-        >>> d = Counter('watch')
-        >>> c.update(d)                 # add elements from another counter
-        >>> c['h']                      # four 'h' in which, witch, and watch
-        4
-
-        '''
-        # The regular dict.update() operation makes no sense here because the
-        # replace behavior results in the some of original untouched counts
-        # being mixed-in with all of the other counts for a mismash that
-        # doesn't have a straight-forward interpretation in most counting
-        # contexts.  Instead, we implement straight-addition.  Both the inputs
-        # and outputs are allowed to contain zero and negative counts.
-
-        if iterable is not None:
-            if isinstance(iterable, Mapping):
-                if self:
-                    self_get = self.get
-                    for elem, count in iterable.items():
-                        self[elem] = count + self_get(elem, 0)
-                else:
-                    dict.update(self, iterable) # fast path when counter is empty
-            else:
-                self_get = self.get
-                for elem in iterable:
-                    self[elem] = 1 + self_get(elem, 0)
-        if kwds:
-            self.update(kwds)
-
-    def subtract(self, iterable=None, **kwds):
-        '''Like dict.update() but subtracts counts instead of replacing them.
-        Counts can be reduced below zero.  Both the inputs and outputs are
-        allowed to contain zero and negative counts.
-
-        Source can be an iterable, a dictionary, or another Counter instance.
-
-        >>> c = Counter('which')
-        >>> c.subtract('witch')             # subtract elements from another iterable
-        >>> c.subtract(Counter('watch'))    # subtract elements from another counter
-        >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
-        0
-        >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
-        -1
-
-        '''
-        if iterable is not None:
-            self_get = self.get
-            if isinstance(iterable, Mapping):
-                for elem, count in iterable.items():
-                    self[elem] = self_get(elem, 0) - count
-            else:
-                for elem in iterable:
-                    self[elem] = self_get(elem, 0) - 1
-        if kwds:
-            self.subtract(kwds)
-
-    def copy(self):
-        'Like dict.copy() but returns a Counter instance instead of a dict.'
-        return Counter(self)
-
-    def __delitem__(self, elem):
-        'Like dict.__delitem__() but does not raise KeyError for missing values.'
-        if elem in self:
-            dict.__delitem__(self, elem)
-
-    def __repr__(self):
-        if not self:
-            return '%s()' % self.__class__.__name__
-        items = ', '.join(map('%r: %r'.__mod__, self.most_common()))
-        return '%s({%s})' % (self.__class__.__name__, items)
-
-    # Multiset-style mathematical operations discussed in:
-    #       Knuth TAOCP Volume II section 4.6.3 exercise 19
-    #       and at http://en.wikipedia.org/wiki/Multiset
-    #
-    # Outputs guaranteed to only include positive counts.
-    #
-    # To strip negative and zero counts, add-in an empty counter:
-    #       c += Counter()
-
-    def __add__(self, other):
-        '''Add counts from two counters.
-
-        >>> Counter('abbb') + Counter('bcc')
-        Counter({'b': 4, 'c': 2, 'a': 1})
-
-        '''
-        if not isinstance(other, Counter):
-            return NotImplemented
-        result = Counter()
-        for elem in set(self) | set(other):
-            newcount = self[elem] + other[elem]
-            if newcount > 0:
-                result[elem] = newcount
-        return result
-
-    def __sub__(self, other):
-        ''' Subtract count, but keep only results with positive counts.
-
-        >>> Counter('abbbc') - Counter('bccd')
-        Counter({'b': 2, 'a': 1})
-
-        '''
-        if not isinstance(other, Counter):
-            return NotImplemented
-        result = Counter()
-        for elem in set(self) | set(other):
-            newcount = self[elem] - other[elem]
-            if newcount > 0:
-                result[elem] = newcount
-        return result
-
-    def __or__(self, other):
-        '''Union is the maximum of value in either of the input counters.
-
-        >>> Counter('abbb') | Counter('bcc')
-        Counter({'b': 3, 'c': 2, 'a': 1})
-
-        '''
-        if not isinstance(other, Counter):
-            return NotImplemented
-        result = Counter()
-        for elem in set(self) | set(other):
-            p, q = self[elem], other[elem]
-            newcount = q if p < q else p
-            if newcount > 0:
-                result[elem] = newcount
-        return result
-
-    def __and__(self, other):
-        ''' Intersection is the minimum of corresponding counts.
-
-        >>> Counter('abbb') & Counter('bcc')
-        Counter({'b': 1})
-
-        '''
-        if not isinstance(other, Counter):
-            return NotImplemented
-        result = Counter()
-        if len(self) < len(other):
-            self, other = other, self
-        for elem in filter(self.__contains__, other):
-            p, q = self[elem], other[elem]
-            newcount = p if p < q else q
-            if newcount > 0:
-                result[elem] = newcount
-        return result
-
-
-################################################################################
-### UserDict
-################################################################################
-
-class UserDict(MutableMapping):
-
-    # Start by filling-out the abstract methods
-    def __init__(self, dict=None, **kwargs):
-        self.data = {}
-        if dict is not None:
-            self.update(dict)
-        if len(kwargs):
-            self.update(kwargs)
-    def __len__(self): return len(self.data)
-    def __getitem__(self, key):
-        if key in self.data:
-            return self.data[key]
-        if hasattr(self.__class__, "__missing__"):
-            return self.__class__.__missing__(self, key)
-        raise KeyError(key)
-    def __setitem__(self, key, item): self.data[key] = item
-    def __delitem__(self, key): del self.data[key]
-    def __iter__(self):
-        return iter(self.data)
-
-    # Modify __contains__ to work correctly when __missing__ is present
-    def __contains__(self, key):
-        return key in self.data
-
-    # Now, add the methods in dicts but not in MutableMapping
-    def __repr__(self): return repr(self.data)
-    def copy(self):
-        if self.__class__ is UserDict:
-            return UserDict(self.data.copy())
-        import copy
-        data = self.data
-        try:
-            self.data = {}
-            c = copy.copy(self)
-        finally:
-            self.data = data
-        c.update(self)
-        return c
-    @classmethod
-    def fromkeys(cls, iterable, value=None):
-        d = cls()
-        for key in iterable:
-            d[key] = value
-        return d
-
-
-
-################################################################################
-### UserList
-################################################################################
-
-class UserList(MutableSequence):
-    """A more or less complete user-defined wrapper around list objects."""
-    def __init__(self, initlist=None):
-        self.data = []
-        if initlist is not None:
-            # XXX should this accept an arbitrary sequence?
-            if type(initlist) == type(self.data):
-                self.data[:] = initlist
-            elif isinstance(initlist, UserList):
-                self.data[:] = initlist.data[:]
-            else:
-                self.data = list(initlist)
-    def __repr__(self): return repr(self.data)
-    def __lt__(self, other): return self.data <  self.__cast(other)
-    def __le__(self, other): return self.data <= self.__cast(other)
-    def __eq__(self, other): return self.data == self.__cast(other)
-    def __ne__(self, other): return self.data != self.__cast(other)
-    def __gt__(self, other): return self.data >  self.__cast(other)
-    def __ge__(self, other): return self.data >= self.__cast(other)
-    def __cast(self, other):
-        return other.data if isinstance(other, UserList) else other
-    def __contains__(self, item): return item in self.data
-    def __len__(self): return len(self.data)
-    def __getitem__(self, i): return self.data[i]
-    def __setitem__(self, i, item): self.data[i] = item
-    def __delitem__(self, i): del self.data[i]
-    def __add__(self, other):
-        if isinstance(other, UserList):
-            return self.__class__(self.data + other.data)
-        elif isinstance(other, type(self.data)):
-            return self.__class__(self.data + other)
-        return self.__class__(self.data + list(other))
-    def __radd__(self, other):
-        if isinstance(other, UserList):
-            return self.__class__(other.data + self.data)
-        elif isinstance(other, type(self.data)):
-            return self.__class__(other + self.data)
-        return self.__class__(list(other) + self.data)
-    def __iadd__(self, other):
-        if isinstance(other, UserList):
-            self.data += other.data
-        elif isinstance(other, type(self.data)):
-            self.data += other
-        else:
-            self.data += list(other)
-        return self
-    def __mul__(self, n):
-        return self.__class__(self.data*n)
-    __rmul__ = __mul__
-    def __imul__(self, n):
-        self.data *= n
-        return self
-    def append(self, item): self.data.append(item)
-    def insert(self, i, item): self.data.insert(i, item)
-    def pop(self, i=-1): return self.data.pop(i)
-    def remove(self, item): self.data.remove(item)
-    def count(self, item): return self.data.count(item)
-    def index(self, item, *args): return self.data.index(item, *args)
-    def reverse(self): self.data.reverse()
-    def sort(self, *args, **kwds): self.data.sort(*args, **kwds)
-    def extend(self, other):
-        if isinstance(other, UserList):
-            self.data.extend(other.data)
-        else:
-            self.data.extend(other)
-
-
-
-################################################################################
-### UserString
-################################################################################
-
-class UserString(Sequence):
-    def __init__(self, seq):
-        if isinstance(seq, str):
-            self.data = seq
-        elif isinstance(seq, UserString):
-            self.data = seq.data[:]
-        else:
-            self.data = str(seq)
-    def __str__(self): return str(self.data)
-    def __repr__(self): return repr(self.data)
-    def __int__(self): return int(self.data)
-    def __float__(self): return float(self.data)
-    def __complex__(self): return complex(self.data)
-    def __hash__(self): return hash(self.data)
-
-    def __eq__(self, string):
-        if isinstance(string, UserString):
-            return self.data == string.data
-        return self.data == string
-    def __ne__(self, string):
-        if isinstance(string, UserString):
-            return self.data != string.data
-        return self.data != string
-    def __lt__(self, string):
-        if isinstance(string, UserString):
-            return self.data < string.data
-        return self.data < string
-    def __le__(self, string):
-        if isinstance(string, UserString):
-            return self.data <= string.data
-        return self.data <= string
-    def __gt__(self, string):
-        if isinstance(string, UserString):
-            return self.data > string.data
-        return self.data > string
-    def __ge__(self, string):
-        if isinstance(string, UserString):
-            return self.data >= string.data
-        return self.data >= string
-
-    def __contains__(self, char):
-        if isinstance(char, UserString):
-            char = char.data
-        return char in self.data
-
-    def __len__(self): return len(self.data)
-    def __getitem__(self, index): return self.__class__(self.data[index])
-    def __add__(self, other):
-        if isinstance(other, UserString):
-            return self.__class__(self.data + other.data)
-        elif isinstance(other, str):
-            return self.__class__(self.data + other)
-        return self.__class__(self.data + str(other))
-    def __radd__(self, other):
-        if isinstance(other, str):
-            return self.__class__(other + self.data)
-        return self.__class__(str(other) + self.data)
-    def __mul__(self, n):
-        return self.__class__(self.data*n)
-    __rmul__ = __mul__
-    def __mod__(self, args):
-        return self.__class__(self.data % args)
-
-    # the following methods are defined in alphabetical order:
-    def capitalize(self): return self.__class__(self.data.capitalize())
-    def center(self, width, *args):
-        return self.__class__(self.data.center(width, *args))
-    def count(self, sub, start=0, end=_sys.maxsize):
-        if isinstance(sub, UserString):
-            sub = sub.data
-        return self.data.count(sub, start, end)
-    def encode(self, encoding=None, errors=None): # XXX improve this?
-        if encoding:
-            if errors:
-                return self.__class__(self.data.encode(encoding, errors))
-            return self.__class__(self.data.encode(encoding))
-        return self.__class__(self.data.encode())
-    def endswith(self, suffix, start=0, end=_sys.maxsize):
-        return self.data.endswith(suffix, start, end)
-    def expandtabs(self, tabsize=8):
-        return self.__class__(self.data.expandtabs(tabsize))
-    def find(self, sub, start=0, end=_sys.maxsize):
-        if isinstance(sub, UserString):
-            sub = sub.data
-        return self.data.find(sub, start, end)
-    def format(self, *args, **kwds):
-        return self.data.format(*args, **kwds)
-    def index(self, sub, start=0, end=_sys.maxsize):
-        return self.data.index(sub, start, end)
-    def isalpha(self): return self.data.isalpha()
-    def isalnum(self): return self.data.isalnum()
-    def isdecimal(self): return self.data.isdecimal()
-    def isdigit(self): return self.data.isdigit()
-    def isidentifier(self): return self.data.isidentifier()
-    def islower(self): return self.data.islower()
-    def isnumeric(self): return self.data.isnumeric()
-    def isspace(self): return self.data.isspace()
-    def istitle(self): return self.data.istitle()
-    def isupper(self): return self.data.isupper()
-    def join(self, seq): return self.data.join(seq)
-    def ljust(self, width, *args):
-        return self.__class__(self.data.ljust(width, *args))
-    def lower(self): return self.__class__(self.data.lower())
-    def lstrip(self, chars=None): return self.__class__(self.data.lstrip(chars))
-    def partition(self, sep):
-        return self.data.partition(sep)
-    def replace(self, old, new, maxsplit=-1):
-        if isinstance(old, UserString):
-            old = old.data
-        if isinstance(new, UserString):
-            new = new.data
-        return self.__class__(self.data.replace(old, new, maxsplit))
-    def rfind(self, sub, start=0, end=_sys.maxsize):
-        if isinstance(sub, UserString):
-            sub = sub.data
-        return self.data.rfind(sub, start, end)
-    def rindex(self, sub, start=0, end=_sys.maxsize):
-        return self.data.rindex(sub, start, end)
-    def rjust(self, width, *args):
-        return self.__class__(self.data.rjust(width, *args))
-    def rpartition(self, sep):
-        return self.data.rpartition(sep)
-    def rstrip(self, chars=None):
-        return self.__class__(self.data.rstrip(chars))
-    def split(self, sep=None, maxsplit=-1):
-        return self.data.split(sep, maxsplit)
-    def rsplit(self, sep=None, maxsplit=-1):
-        return self.data.rsplit(sep, maxsplit)
-    def splitlines(self, keepends=0): return self.data.splitlines(keepends)
-    def startswith(self, prefix, start=0, end=_sys.maxsize):
-        return self.data.startswith(prefix, start, end)
-    def strip(self, chars=None): return self.__class__(self.data.strip(chars))
-    def swapcase(self): return self.__class__(self.data.swapcase())
-    def title(self): return self.__class__(self.data.title())
-    def translate(self, *args):
-        return self.__class__(self.data.translate(*args))
-    def upper(self): return self.__class__(self.data.upper())
-    def zfill(self, width): return self.__class__(self.data.zfill(width))
-
-
-
-################################################################################
-### Simple tests
-################################################################################
-
-if __name__ == '__main__':
-    # verify that instances can be pickled
-    from pickle import loads, dumps
-    Point = namedtuple('Point', 'x, y', True)
-    p = Point(x=10, y=20)
-    assert p == loads(dumps(p))
-
-    # test and demonstrate ability to override methods
-    class Point(namedtuple('Point', 'x y')):
-        __slots__ = ()
-        @property
-        def hypot(self):
-            return (self.x ** 2 + self.y ** 2) ** 0.5
-        def __str__(self):
-            return 'Point: x=%6.3f  y=%6.3f  hypot=%6.3f' % (self.x, self.y, self.hypot)
-
-    for p in Point(3, 4), Point(14, 5/7.):
-        print (p)
-
-    class Point(namedtuple('Point', 'x y')):
-        'Point class with optimized _make() and _replace() without error-checking'
-        __slots__ = ()
-        _make = classmethod(tuple.__new__)
-        def _replace(self, _map=map, **kwds):
-            return self._make(_map(kwds.get, ('x', 'y'), self))
-
-    print(Point(11, 22)._replace(x=100))
-
-    Point3D = namedtuple('Point3D', Point._fields + ('z',))
-    print(Point3D.__doc__)
-
-    import doctest
-    TestResults = namedtuple('TestResults', 'failed attempted')
-    print(TestResults(*doctest.testmod()))

Modified: python/branches/pep-3151/Lib/compileall.py
==============================================================================
--- python/branches/pep-3151/Lib/compileall.py	(original)
+++ python/branches/pep-3151/Lib/compileall.py	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,4 @@
-"""Module/script to "compile" all .py files to .pyc (or .pyo) file.
+"""Module/script to byte-compile all .py files to .pyc (or .pyo) files.
 
 When called as a script with arguments, this compiles the directories
 given as arguments recursively; the -l option prevents it from
@@ -9,38 +9,37 @@
 packages -- for now, you'll have to deal with packages separately.)
 
 See module py_compile for details of the actual byte-compilation.
-
 """
 import os
-import errno
 import sys
+import errno
+import imp
 import py_compile
 import struct
-import imp
 
 __all__ = ["compile_dir","compile_file","compile_path"]
 
-def compile_dir(dir, maxlevels=10, ddir=None,
-                force=False, rx=None, quiet=False, legacy=False):
+def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
+                quiet=False, legacy=False, optimize=-1):
     """Byte-compile all modules in the given directory tree.
 
     Arguments (only dir is required):
 
     dir:       the directory to byte-compile
     maxlevels: maximum recursion level (default 10)
-    ddir:      if given, purported directory name (this is the
-               directory name that will show up in error messages)
+    ddir:      the directory that will be prepended to the path to the
+               file as it is compiled into each byte-code file.
     force:     if True, force compilation, even if timestamps are up-to-date
     quiet:     if True, be quiet during compilation
     legacy:    if True, produce legacy pyc paths instead of PEP 3147 paths
-
+    optimize:  optimization level or -1 for level of the interpreter
     """
     if not quiet:
-        print('Listing', dir, '...')
+        print('Listing {!r}...'.format(dir))
     try:
         names = os.listdir(dir)
     except os.error:
-        print("Can't list", dir)
+        print("Can't list {!r}".format(dir))
         names = []
     names.sort()
     success = 1
@@ -53,27 +52,29 @@
         else:
             dfile = None
         if not os.path.isdir(fullname):
-            if not compile_file(fullname, ddir, force, rx, quiet, legacy):
+            if not compile_file(fullname, ddir, force, rx, quiet,
+                                legacy, optimize):
                 success = 0
-        elif maxlevels > 0 and \
-             name != os.curdir and name != os.pardir and \
-             os.path.isdir(fullname) and \
-             not os.path.islink(fullname):
+        elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
+              os.path.isdir(fullname) and not os.path.islink(fullname)):
             if not compile_dir(fullname, maxlevels - 1, dfile, force, rx,
-                               quiet, legacy):
+                               quiet, legacy, optimize):
                 success = 0
     return success
 
-def compile_file(fullname, ddir=None, force=0, rx=None, quiet=False,
-                 legacy=False):
-    """Byte-compile file.
+def compile_file(fullname, ddir=None, force=False, rx=None, quiet=False,
+                 legacy=False, optimize=-1):
+    """Byte-compile one file.
+
+    Arguments (only fullname is required):
+
     fullname:  the file to byte-compile
-    ddir:      if given, purported directory name (this is the
-               directory name that will show up in error messages)
+    ddir:      if given, the directory name compiled in to the
+               byte-code file.
     force:     if True, force compilation, even if timestamps are up-to-date
     quiet:     if True, be quiet during compilation
     legacy:    if True, produce legacy pyc paths instead of PEP 3147 paths
-
+    optimize:  optimization level or -1 for level of the interpreter
     """
     success = 1
     name = os.path.basename(fullname)
@@ -89,7 +90,11 @@
         if legacy:
             cfile = fullname + ('c' if __debug__ else 'o')
         else:
-            cfile = imp.cache_from_source(fullname)
+            if optimize >= 0:
+                cfile = imp.cache_from_source(fullname,
+                                              debug_override=not optimize)
+            else:
+                cfile = imp.cache_from_source(fullname)
             cache_dir = os.path.dirname(cfile)
         head, tail = name[:-3], name[-3:]
         if tail == '.py':
@@ -104,12 +109,13 @@
                 except IOError:
                     pass
             if not quiet:
-                print('Compiling', fullname, '...')
+                print('Compiling {!r}...'.format(fullname))
             try:
-                ok = py_compile.compile(fullname, cfile, dfile, True)
+                ok = py_compile.compile(fullname, cfile, dfile, True,
+                                        optimize=optimize)
             except py_compile.PyCompileError as err:
                 if quiet:
-                    print('*** Error compiling', fullname, '...')
+                    print('*** Error compiling {!r}...'.format(fullname))
                 else:
                     print('*** ', end='')
                 # escape non-printable characters in msg
@@ -120,7 +126,7 @@
                 success = 0
             except (SyntaxError, UnicodeError, IOError) as e:
                 if quiet:
-                    print('*** Error compiling', fullname, '...')
+                    print('*** Error compiling {!r}...'.format(fullname))
                 else:
                     print('*** ', end='')
                 print(e.__class__.__name__ + ':', e)
@@ -131,7 +137,7 @@
     return success
 
 def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=False,
-                 legacy=False):
+                 legacy=False, optimize=-1):
     """Byte-compile all module on sys.path.
 
     Arguments (all optional):
@@ -141,7 +147,7 @@
     force: as for compile_dir() (default False)
     quiet: as for compile_dir() (default False)
     legacy: as for compile_dir() (default False)
-
+    optimize: as for compile_dir() (default -1)
     """
     success = 1
     for dir in sys.path:
@@ -150,93 +156,84 @@
         else:
             success = success and compile_dir(dir, maxlevels, None,
                                               force, quiet=quiet,
-                                              legacy=legacy)
+                                              legacy=legacy, optimize=optimize)
     return success
 
-def expand_args(args, flist):
-    """read names in flist and append to args"""
-    expanded = args[:]
-    if flist:
-        try:
-            if flist == '-':
-                fd = sys.stdin
-            else:
-                fd = open(flist)
-            while 1:
-                line = fd.readline()
-                if not line:
-                    break
-                expanded.append(line[:-1])
-        except IOError:
-            print("Error reading file list %s" % flist)
-            raise
-    return expanded
 
 def main():
     """Script main program."""
-    import getopt
-    try:
-        opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:i:b')
-    except getopt.error as msg:
-        print(msg)
-        print("usage: python compileall.py [-l] [-f] [-q] [-d destdir] "
-              "[-x regexp] [-i list] [directory|file ...]")
-        print("-l: don't recurse down")
-        print("-f: force rebuild even if timestamps are up-to-date")
-        print("-q: quiet operation")
-        print("-d destdir: purported directory name for error messages")
-        print("   if no directory arguments, -l sys.path is assumed")
-        print("-x regexp: skip files matching the regular expression regexp")
-        print("   the regexp is searched for in the full path of the file")
-        print("-i list: expand list with its content "
-              "(file and directory names)")
-        print("-b: Produce legacy byte-compile file paths")
-        sys.exit(2)
-    maxlevels = 10
-    ddir = None
-    force = False
-    quiet = False
-    rx = None
-    flist = None
-    legacy = False
-    for o, a in opts:
-        if o == '-l': maxlevels = 0
-        if o == '-d': ddir = a
-        if o == '-f': force = True
-        if o == '-q': quiet = True
-        if o == '-x':
-            import re
-            rx = re.compile(a)
-        if o == '-i': flist = a
-        if o == '-b': legacy = True
-    if ddir:
-        if len(args) != 1 and not os.path.isdir(args[0]):
-            print("-d destdir require exactly one directory argument")
-            sys.exit(2)
-    success = 1
+    import argparse
+
+    parser = argparse.ArgumentParser(
+        description='Utilities to support installing Python libraries.')
+    parser.add_argument('-l', action='store_const', const=0,
+                        default=10, dest='maxlevels',
+                        help="don't recurse into subdirectories")
+    parser.add_argument('-f', action='store_true', dest='force',
+                        help='force rebuild even if timestamps are up to date')
+    parser.add_argument('-q', action='store_true', dest='quiet',
+                        help='output only error messages')
+    parser.add_argument('-b', action='store_true', dest='legacy',
+                        help='use legacy (pre-PEP3147) compiled file locations')
+    parser.add_argument('-d', metavar='DESTDIR',  dest='ddir', default=None,
+                        help=('directory to prepend to file paths for use in '
+                              'compile time tracebacks and in runtime '
+                              'tracebacks in cases where the source file is '
+                              'unavailable'))
+    parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
+                        help=('skip files matching the regular expression. '
+                              'The regexp is searched for in the full path '
+                              'to each file considered for compilation.'))
+    parser.add_argument('-i', metavar='FILE', dest='flist',
+                        help=('add all the files and directories listed in '
+                              'FILE to the list considered for compilation. '
+                              'If "-", names are read from stdin.'))
+    parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
+                        help=('zero or more file and directory names '
+                              'to compile; if no arguments given, defaults '
+                              'to the equivalent of -l sys.path'))
+    args = parser.parse_args()
+
+    compile_dests = args.compile_dest
+
+    if (args.ddir and (len(compile_dests) != 1
+            or not os.path.isdir(compile_dests[0]))):
+        parser.exit('-d destdir requires exactly one directory argument')
+    if args.rx:
+        import re
+        args.rx = re.compile(args.rx)
+
+    # if flist is provided then load it
+    if args.flist:
+        try:
+            with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
+                for line in f:
+                    compile_dests.append(line.strip())
+        except EnvironmentError:
+            print("Error reading file list {}".format(args.flist))
+            return False
+
+    success = True
     try:
-        if args or flist:
-            try:
-                if flist:
-                    args = expand_args(args, flist)
-            except IOError:
-                success = 0
-            if success:
-                for arg in args:
-                    if os.path.isdir(arg):
-                        if not compile_dir(arg, maxlevels, ddir,
-                                           force, rx, quiet, legacy):
-                            success = 0
-                    else:
-                        if not compile_file(arg, ddir, force, rx,
-                                            quiet, legacy):
-                            success = 0
+        if compile_dests:
+            for dest in compile_dests:
+                if os.path.isfile(dest):
+                    if not compile_file(dest, args.ddir, args.force, args.rx,
+                                        args.quiet, args.legacy):
+                        success = False
+                else:
+                    if not compile_dir(dest, args.maxlevels, args.ddir,
+                                       args.force, args.rx, args.quiet,
+                                       args.legacy):
+                        success = False
+            return success
         else:
-            success = compile_path(legacy=legacy)
+            return compile_path(legacy=args.legacy)
     except KeyboardInterrupt:
-        print("\n[interrupt]")
-        success = 0
-    return success
+        print("\n[interrupted]")
+        return False
+    return True
+
 
 if __name__ == '__main__':
     exit_status = int(not main())

Modified: python/branches/pep-3151/Lib/concurrent/futures/_base.py
==============================================================================
--- python/branches/pep-3151/Lib/concurrent/futures/_base.py	(original)
+++ python/branches/pep-3151/Lib/concurrent/futures/_base.py	Sat Feb 26 08:16:32 2011
@@ -12,6 +12,7 @@
 FIRST_COMPLETED = 'FIRST_COMPLETED'
 FIRST_EXCEPTION = 'FIRST_EXCEPTION'
 ALL_COMPLETED = 'ALL_COMPLETED'
+_AS_COMPLETED = '_AS_COMPLETED'
 
 # Possible future states (for internal use by the futures package).
 PENDING = 'PENDING'
@@ -40,8 +41,6 @@
 
 # Logger for internal use by the futures package.
 LOGGER = logging.getLogger("concurrent.futures")
-STDERR_HANDLER = logging.StreamHandler()
-LOGGER.addHandler(STDERR_HANDLER)
 
 class Error(Exception):
     """Base class for all future-related exceptions."""
@@ -70,8 +69,30 @@
     def add_cancelled(self, future):
         self.finished_futures.append(future)
 
+class _AsCompletedWaiter(_Waiter):
+    """Used by as_completed()."""
+
+    def __init__(self):
+        super(_AsCompletedWaiter, self).__init__()
+        self.lock = threading.Lock()
+
+    def add_result(self, future):
+        with self.lock:
+            super(_AsCompletedWaiter, self).add_result(future)
+            self.event.set()
+
+    def add_exception(self, future):
+        with self.lock:
+            super(_AsCompletedWaiter, self).add_exception(future)
+            self.event.set()
+
+    def add_cancelled(self, future):
+        with self.lock:
+            super(_AsCompletedWaiter, self).add_cancelled(future)
+            self.event.set()
+
 class _FirstCompletedWaiter(_Waiter):
-    """Used by wait(return_when=FIRST_COMPLETED) and as_completed()."""
+    """Used by wait(return_when=FIRST_COMPLETED)."""
 
     def add_result(self, future):
         super().add_result(future)
@@ -128,7 +149,9 @@
             future._condition.release()
 
 def _create_and_install_waiters(fs, return_when):
-    if return_when == FIRST_COMPLETED:
+    if return_when == _AS_COMPLETED:
+        waiter = _AsCompletedWaiter()
+    elif return_when == FIRST_COMPLETED:
         waiter = _FirstCompletedWaiter()
     else:
         pending_count = sum(
@@ -171,7 +194,7 @@
                 f for f in fs
                 if f._state in [CANCELLED_AND_NOTIFIED, FINISHED])
         pending = set(fs) - finished
-        waiter = _create_and_install_waiters(fs, FIRST_COMPLETED)
+        waiter = _create_and_install_waiters(fs, _AS_COMPLETED)
 
     try:
         for future in finished:
@@ -187,11 +210,15 @@
                             '%d (of %d) futures unfinished' % (
                             len(pending), len(fs)))
 
-            waiter.event.wait(timeout)
+            waiter.event.wait(wait_timeout)
+
+            with waiter.lock:
+                finished = waiter.finished_futures
+                waiter.finished_futures = []
+                waiter.event.clear()
 
-            for future in waiter.finished_futures[:]:
+            for future in finished:
                 yield future
-                waiter.finished_futures.remove(future)
                 pending.remove(future)
 
     finally:

Modified: python/branches/pep-3151/Lib/concurrent/futures/process.py
==============================================================================
--- python/branches/pep-3151/Lib/concurrent/futures/process.py	(original)
+++ python/branches/pep-3151/Lib/concurrent/futures/process.py	Sat Feb 26 08:16:32 2011
@@ -118,7 +118,7 @@
 def _process_worker(call_queue, result_queue, shutdown):
     """Evaluates calls from call_queue and places the results in result_queue.
 
-    This worker is run in a seperate process.
+    This worker is run in a separate process.
 
     Args:
         call_queue: A multiprocessing.Queue of _CallItems that will be read and
@@ -244,6 +244,31 @@
             else:
                 work_item.future.set_result(result_item.result)
 
+_system_limits_checked = False
+_system_limited = None
+def _check_system_limits():
+    global _system_limits_checked, _system_limited
+    if _system_limits_checked:
+        if _system_limited:
+            raise NotImplementedError(_system_limited)
+    _system_limits_checked = True
+    try:
+        import os
+        nsems_max = os.sysconf("SC_SEM_NSEMS_MAX")
+    except (AttributeError, ValueError):
+        # sysconf not available or setting not available
+        return
+    if nsems_max == -1:
+        # indetermine limit, assume that limit is determined
+        # by available memory only
+        return
+    if nsems_max >= 256:
+        # minimum number of semaphores available
+        # according to POSIX
+        return
+    _system_limited = "system provides too few semaphores (%d available, 256 necessary)" % nsems_max
+    raise NotImplementedError(_system_limited)
+
 class ProcessPoolExecutor(_base.Executor):
     def __init__(self, max_workers=None):
         """Initializes a new ProcessPoolExecutor instance.
@@ -253,6 +278,7 @@
                 execute the given calls. If None or not given then as many
                 worker processes will be created as the machine has processors.
         """
+        _check_system_limits()
         _remove_dead_thread_references()
 
         if max_workers is None:

Modified: python/branches/pep-3151/Lib/configparser.py
==============================================================================
--- python/branches/pep-3151/Lib/configparser.py	(original)
+++ python/branches/pep-3151/Lib/configparser.py	Sat Feb 26 08:16:32 2011
@@ -4,33 +4,23 @@
 and followed by "name: value" entries, with continuations and such in
 the style of RFC 822.
 
-The option values can contain format strings which refer to other values in
-the same section, or values in a special [DEFAULT] section.
-
-For example:
-
-    something: %(dir)s/whatever
-
-would resolve the "%(dir)s" to the value of dir.  All reference
-expansions are done late, on demand.
-
 Intrinsic defaults can be specified by passing them into the
 ConfigParser constructor as a dictionary.
 
 class:
 
 ConfigParser -- responsible for parsing a list of
-                configuration files, and managing the parsed database.
+                    configuration files, and managing the parsed database.
 
     methods:
 
     __init__(defaults=None, dict_type=_default_dict, allow_no_value=False,
-             delimiters=('=', ':'), comment_prefixes=_COMPATIBLE,
-             strict=False, empty_lines_in_values=True):
+             delimiters=('=', ':'), comment_prefixes=('#', ';'),
+             inline_comment_prefixes=None, strict=True,
+             empty_lines_in_values=True):
         Create the parser. When `defaults' is given, it is initialized into the
         dictionary or intrinsic defaults. The keys must be strings, the values
-        must be appropriate for %()s string interpolation. Note that `__name__'
-        is always an intrinsic default; its value is the section's name.
+        must be appropriate for %()s string interpolation.
 
         When `dict_type' is given, it will be used to create the dictionary
         objects for the list of sections, for the options within a section, and
@@ -40,11 +30,15 @@
         that divide keys from values.
 
         When `comment_prefixes' is given, it will be used as the set of
-        substrings that prefix comments in a line.
+        substrings that prefix comments in empty lines. Comments can be
+        indented.
+
+        When `inline_comment_prefixes' is given, it will be used as the set of
+        substrings that prefix comments in non-empty lines.
 
         When `strict` is True, the parser won't allow for any section or option
         duplicates while reading from a single source (file, string or
-        dictionary). Default is False.
+        dictionary). Default is True.
 
         When `empty_lines_in_values' is False (default: True), each empty line
         marks the end of an option. Otherwise, internal empty lines of
@@ -104,8 +98,10 @@
         insensitively defined as 0, false, no, off for False, and 1, true,
         yes, on for True).  Returns False or True.
 
-    items(section, raw=False, vars=None)
-        Return a list of tuples with (name, value) for each option
+    items(section=_UNSET, raw=False, vars=None)
+        If section is given, return a list of tuples with (section_name,
+        section_proxy) for each section, including DEFAULTSECT. Otherwise,
+        return a list of tuples with (name, value) for each option
         in the section.
 
     remove_section(section)
@@ -123,7 +119,8 @@
         between keys and values are surrounded by spaces.
 """
 
-from collections import MutableMapping, OrderedDict as _default_dict
+from collections.abc import MutableMapping
+from collections import OrderedDict as _default_dict, ChainMap as _ChainMap
 import functools
 import io
 import itertools
@@ -276,9 +273,8 @@
 class InterpolationSyntaxError(InterpolationError):
     """Raised when the source text contains invalid syntax.
 
-    Current implementation raises this exception only for SafeConfigParser
-    instances when the source text into which substitutions are made
-    does not conform to the required syntax.
+    Current implementation raises this exception when the source text into
+    which substitutions are made does not conform to the required syntax.
     """
 
 
@@ -317,9 +313,9 @@
     def filename(self):
         """Deprecated, use `source'."""
         warnings.warn(
-            "This 'filename' attribute will be removed in future versions.  "
+            "The 'filename' attribute will be removed in future versions.  "
             "Use 'source' instead.",
-            PendingDeprecationWarning, stacklevel=2
+            DeprecationWarning, stacklevel=2
         )
         return self.source
 
@@ -329,7 +325,7 @@
         warnings.warn(
             "The 'filename' attribute will be removed in future versions.  "
             "Use 'source' instead.",
-            PendingDeprecationWarning, stacklevel=2
+            DeprecationWarning, stacklevel=2
         )
         self.source = value
 
@@ -352,17 +348,210 @@
         self.args = (filename, lineno, line)
 
 
-# Used in parsers to denote selecting a backwards-compatible inline comment
-# character behavior (; and # are comments at the start of a line, but ; only
-# inline)
-_COMPATIBLE = object()
-
 # Used in parser getters to indicate the default behaviour when a specific
 # option is not found it to raise an exception. Created to enable `None' as
 # a valid fallback value.
 _UNSET = object()
 
 
+class Interpolation:
+    """Dummy interpolation that passes the value through with no changes."""
+
+    def before_get(self, parser, section, option, value, defaults):
+        return value
+
+    def before_set(self, parser, section, option, value):
+        return value
+
+    def before_read(self, parser, section, option, value):
+        return value
+
+    def before_write(self, parser, section, option, value):
+        return value
+
+
+class BasicInterpolation(Interpolation):
+    """Interpolation as implemented in the classic ConfigParser.
+
+    The option values can contain format strings which refer to other values in
+    the same section, or values in the special default section.
+
+    For example:
+
+        something: %(dir)s/whatever
+
+    would resolve the "%(dir)s" to the value of dir.  All reference
+    expansions are done late, on demand. If a user needs to use a bare % in
+    a configuration file, she can escape it by writing %%. Other other % usage
+    is considered a user error and raises `InterpolationSyntaxError'."""
+
+    _KEYCRE = re.compile(r"%\(([^)]+)\)s")
+
+    def before_get(self, parser, section, option, value, defaults):
+        L = []
+        self._interpolate_some(parser, option, L, value, section, defaults, 1)
+        return ''.join(L)
+
+    def before_set(self, parser, section, option, value):
+        tmp_value = value.replace('%%', '') # escaped percent signs
+        tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
+        if '%' in tmp_value:
+            raise ValueError("invalid interpolation syntax in %r at "
+                             "position %d" % (value, tmp_value.find('%')))
+        return value
+
+    def _interpolate_some(self, parser, option, accum, rest, section, map,
+                          depth):
+        if depth > MAX_INTERPOLATION_DEPTH:
+            raise InterpolationDepthError(option, section, rest)
+        while rest:
+            p = rest.find("%")
+            if p < 0:
+                accum.append(rest)
+                return
+            if p > 0:
+                accum.append(rest[:p])
+                rest = rest[p:]
+            # p is no longer used
+            c = rest[1:2]
+            if c == "%":
+                accum.append("%")
+                rest = rest[2:]
+            elif c == "(":
+                m = self._KEYCRE.match(rest)
+                if m is None:
+                    raise InterpolationSyntaxError(option, section,
+                        "bad interpolation variable reference %r" % rest)
+                var = parser.optionxform(m.group(1))
+                rest = rest[m.end():]
+                try:
+                    v = map[var]
+                except KeyError:
+                    raise InterpolationMissingOptionError(
+                        option, section, rest, var)
+                if "%" in v:
+                    self._interpolate_some(parser, option, accum, v,
+                                           section, map, depth + 1)
+                else:
+                    accum.append(v)
+            else:
+                raise InterpolationSyntaxError(
+                    option, section,
+                    "'%%' must be followed by '%%' or '(', "
+                    "found: %r" % (rest,))
+
+
+class ExtendedInterpolation(Interpolation):
+    """Advanced variant of interpolation, supports the syntax used by
+    `zc.buildout'. Enables interpolation between sections."""
+
+    _KEYCRE = re.compile(r"\$\{([^}]+)\}")
+
+    def before_get(self, parser, section, option, value, defaults):
+        L = []
+        self._interpolate_some(parser, option, L, value, section, defaults, 1)
+        return ''.join(L)
+
+    def before_set(self, parser, section, option, value):
+        tmp_value = value.replace('$$', '') # escaped dollar signs
+        tmp_value = self._KEYCRE.sub('', tmp_value) # valid syntax
+        if '$' in tmp_value:
+            raise ValueError("invalid interpolation syntax in %r at "
+                             "position %d" % (value, tmp_value.find('%')))
+        return value
+
+    def _interpolate_some(self, parser, option, accum, rest, section, map,
+                          depth):
+        if depth > MAX_INTERPOLATION_DEPTH:
+            raise InterpolationDepthError(option, section, rest)
+        while rest:
+            p = rest.find("$")
+            if p < 0:
+                accum.append(rest)
+                return
+            if p > 0:
+                accum.append(rest[:p])
+                rest = rest[p:]
+            # p is no longer used
+            c = rest[1:2]
+            if c == "$":
+                accum.append("$")
+                rest = rest[2:]
+            elif c == "{":
+                m = self._KEYCRE.match(rest)
+                if m is None:
+                    raise InterpolationSyntaxError(option, section,
+                        "bad interpolation variable reference %r" % rest)
+                path = parser.optionxform(m.group(1)).split(':')
+                rest = rest[m.end():]
+                sect = section
+                opt = option
+                try:
+                    if len(path) == 1:
+                        opt = path[0]
+                        v = map[opt]
+                    elif len(path) == 2:
+                        sect = path[0]
+                        opt = path[1]
+                        v = parser.get(sect, opt, raw=True)
+                    else:
+                        raise InterpolationSyntaxError(
+                            option, section,
+                            "More than one ':' found: %r" % (rest,))
+                except (KeyError, NoSectionError, NoOptionError):
+                    raise InterpolationMissingOptionError(
+                        option, section, rest, ":".join(path))
+                if "$" in v:
+                    self._interpolate_some(parser, opt, accum, v, sect,
+                                           dict(parser.items(sect, raw=True)),
+                                           depth + 1)
+                else:
+                    accum.append(v)
+            else:
+                raise InterpolationSyntaxError(
+                    option, section,
+                    "'$' must be followed by '$' or '{', "
+                    "found: %r" % (rest,))
+
+
+class LegacyInterpolation(Interpolation):
+    """Deprecated interpolation used in old versions of ConfigParser.
+    Use BasicInterpolation or ExtendedInterpolation instead."""
+
+    _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
+
+    def before_get(self, parser, section, option, value, vars):
+        rawval = value
+        depth = MAX_INTERPOLATION_DEPTH
+        while depth:                    # Loop through this until it's done
+            depth -= 1
+            if value and "%(" in value:
+                replace = functools.partial(self._interpolation_replace,
+                                            parser=parser)
+                value = self._KEYCRE.sub(replace, value)
+                try:
+                    value = value % vars
+                except KeyError as e:
+                    raise InterpolationMissingOptionError(
+                        option, section, rawval, e.args[0])
+            else:
+                break
+        if value and "%(" in value:
+            raise InterpolationDepthError(option, section, rawval)
+        return value
+
+    def before_set(self, parser, section, option, value):
+        return value
+
+    @staticmethod
+    def _interpolation_replace(match, parser):
+        s = match.group(1)
+        if s is None:
+            return match.group()
+        else:
+            return "%%(%s)s" % parser.optionxform(s)
+
+
 class RawConfigParser(MutableMapping):
     """ConfigParser that does not do interpolation."""
 
@@ -389,7 +578,8 @@
                                            # space/tab
         (?P<value>.*))?$                   # everything up to eol
         """
-
+    # Interpolation algorithm to be used if the user does not specify another
+    _DEFAULT_INTERPOLATION = Interpolation()
     # Compiled regular expression for matching sections
     SECTCRE = re.compile(_SECT_TMPL, re.VERBOSE)
     # Compiled regular expression for matching options with typical separators
@@ -405,13 +595,16 @@
 
     def __init__(self, defaults=None, dict_type=_default_dict,
                  allow_no_value=False, *, delimiters=('=', ':'),
-                 comment_prefixes=_COMPATIBLE, strict=False,
-                 empty_lines_in_values=True):
+                 comment_prefixes=('#', ';'), inline_comment_prefixes=None,
+                 strict=True, empty_lines_in_values=True,
+                 default_section=DEFAULTSECT,
+                 interpolation=_UNSET):
+
         self._dict = dict_type
         self._sections = self._dict()
         self._defaults = self._dict()
-        self._views = self._dict()
-        self._views[DEFAULTSECT] = SectionProxy(self, DEFAULTSECT)
+        self._proxies = self._dict()
+        self._proxies[default_section] = SectionProxy(self, default_section)
         if defaults:
             for key, value in defaults.items():
                 self._defaults[self.optionxform(key)] = value
@@ -426,15 +619,16 @@
             else:
                 self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
                                           re.VERBOSE)
-        if comment_prefixes is _COMPATIBLE:
-            self._startonly_comment_prefixes = ('#',)
-            self._comment_prefixes = (';',)
-        else:
-            self._startonly_comment_prefixes = ()
-            self._comment_prefixes = tuple(comment_prefixes or ())
+        self._comment_prefixes = tuple(comment_prefixes or ())
+        self._inline_comment_prefixes = tuple(inline_comment_prefixes or ())
         self._strict = strict
         self._allow_no_value = allow_no_value
         self._empty_lines_in_values = empty_lines_in_values
+        if interpolation is _UNSET:
+            self._interpolation = self._DEFAULT_INTERPOLATION
+        else:
+            self._interpolation = interpolation
+        self.default_section=default_section
 
     def defaults(self):
         return self._defaults
@@ -448,16 +642,15 @@
         """Create a new section in the configuration.
 
         Raise DuplicateSectionError if a section by the specified name
-        already exists. Raise ValueError if name is DEFAULT or any of it's
-        case-insensitive variants.
+        already exists. Raise ValueError if name is DEFAULT.
         """
-        if section.upper() == DEFAULTSECT:
-            raise ValueError('Invalid section name: %s' % section)
+        if section == self.default_section:
+            raise ValueError('Invalid section name: %r' % section)
 
         if section in self._sections:
             raise DuplicateSectionError(section)
         self._sections[section] = self._dict()
-        self._views[section] = SectionProxy(self, section)
+        self._proxies[section] = SectionProxy(self, section)
 
     def has_section(self, section):
         """Indicate whether the named section is present in the configuration.
@@ -473,8 +666,6 @@
         except KeyError:
             raise NoSectionError(section)
         opts.update(self._defaults)
-        if '__name__' in opts:
-            del opts['__name__']
         return list(opts.keys())
 
     def read(self, filenames, encoding=None):
@@ -528,19 +719,23 @@
         that should be present in the section. If the used dictionary type
         preserves order, sections and their keys will be added in order.
 
+        All types held in the dictionary are converted to strings during
+        reading, including section names, option names and keys.
+
         Optional second argument is the `source' specifying the name of the
         dictionary being read.
         """
         elements_added = set()
         for section, keys in dictionary.items():
+            section = str(section)
             try:
                 self.add_section(section)
             except (DuplicateSectionError, ValueError):
                 if self._strict and section in elements_added:
                     raise
-                elements_added.add(section)
+            elements_added.add(section)
             for key, value in keys.items():
-                key = self.optionxform(key)
+                key = self.optionxform(str(key))
                 if value is not None:
                     value = str(value)
                 if self._strict and (section, key) in elements_added:
@@ -553,11 +748,11 @@
         warnings.warn(
             "This method will be removed in future versions.  "
             "Use 'parser.read_file()' instead.",
-            PendingDeprecationWarning, stacklevel=2
+            DeprecationWarning, stacklevel=2
         )
         self.read_file(fp, source=filename)
 
-    def get(self, section, option, *, vars=None, fallback=_UNSET):
+    def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
         """Get an option value for a given section.
 
         If `vars' is provided, it must be a dictionary. The option is looked up
@@ -565,7 +760,12 @@
         If the key is not found and `fallback' is provided, it is used as
         a fallback value. `None' can be provided as a `fallback' value.
 
-        Arguments `vars' and `fallback' are keyword only.
+        If interpolation is enabled and the optional argument `raw' is False,
+        all interpolations are expanded in the return values.
+
+        Arguments `raw', `vars', and `fallback' are keyword only.
+
+        The section DEFAULT is special.
         """
         try:
             d = self._unify_values(section, vars)
@@ -576,63 +776,90 @@
                 return fallback
         option = self.optionxform(option)
         try:
-            return d[option]
+            value = d[option]
         except KeyError:
             if fallback is _UNSET:
                 raise NoOptionError(option, section)
             else:
                 return fallback
 
-    def items(self, section):
-        try:
-            d2 = self._sections[section]
-        except KeyError:
-            if section != DEFAULTSECT:
-                raise NoSectionError(section)
-            d2 = self._dict()
-        d = self._defaults.copy()
-        d.update(d2)
-        if "__name__" in d:
-            del d["__name__"]
-        return d.items()
+        if raw or value is None:
+            return value
+        else:
+            return self._interpolation.before_get(self, section, option, value,
+                                                  d)
 
     def _get(self, section, conv, option, **kwargs):
         return conv(self.get(section, option, **kwargs))
 
-    def getint(self, section, option, *, vars=None, fallback=_UNSET):
+    def getint(self, section, option, *, raw=False, vars=None,
+               fallback=_UNSET):
         try:
-            return self._get(section, int, option, vars=vars)
+            return self._get(section, int, option, raw=raw, vars=vars)
         except (NoSectionError, NoOptionError):
             if fallback is _UNSET:
                 raise
             else:
                 return fallback
 
-    def getfloat(self, section, option, *, vars=None, fallback=_UNSET):
+    def getfloat(self, section, option, *, raw=False, vars=None,
+                 fallback=_UNSET):
         try:
-            return self._get(section, float, option, vars=vars)
+            return self._get(section, float, option, raw=raw, vars=vars)
         except (NoSectionError, NoOptionError):
             if fallback is _UNSET:
                 raise
             else:
                 return fallback
 
-    def getboolean(self, section, option, *, vars=None, fallback=_UNSET):
+    def getboolean(self, section, option, *, raw=False, vars=None,
+                   fallback=_UNSET):
         try:
             return self._get(section, self._convert_to_boolean, option,
-                             vars=vars)
+                             raw=raw, vars=vars)
         except (NoSectionError, NoOptionError):
             if fallback is _UNSET:
                 raise
             else:
                 return fallback
 
+    def items(self, section=_UNSET, raw=False, vars=None):
+        """Return a list of (name, value) tuples for each option in a section.
+
+        All % interpolations are expanded in the return values, based on the
+        defaults passed into the constructor, unless the optional argument
+        `raw' is true.  Additional substitutions may be provided using the
+        `vars' argument, which must be a dictionary whose contents overrides
+        any pre-existing defaults.
+
+        The section DEFAULT is special.
+        """
+        if section is _UNSET:
+            return super().items()
+        d = self._defaults.copy()
+        try:
+            d.update(self._sections[section])
+        except KeyError:
+            if section != self.default_section:
+                raise NoSectionError(section)
+        # Update with the entry specific variables
+        if vars:
+            for key, value in vars.items():
+                d[self.optionxform(key)] = value
+        value_getter = lambda option: self._interpolation.before_get(self,
+            section, option, d[option], d)
+        if raw:
+            value_getter = lambda option: d[option]
+        return [(option, value_getter(option)) for option in d.keys()]
+
     def optionxform(self, optionstr):
         return optionstr.lower()
 
     def has_option(self, section, option):
-        """Check for the existence of a given option in a given section."""
-        if not section or section == DEFAULTSECT:
+        """Check for the existence of a given option in a given section.
+        If the specified `section' is None or an empty string, DEFAULT is
+        assumed. If the specified `section' does not exist, returns False."""
+        if not section or section == self.default_section:
             option = self.optionxform(option)
             return option in self._defaults
         elif section not in self._sections:
@@ -644,7 +871,10 @@
 
     def set(self, section, option, value=None):
         """Set an option."""
-        if not section or section == DEFAULTSECT:
+        if value:
+            value = self._interpolation.before_set(self, section, option,
+                                                   value)
+        if not section or section == self.default_section:
             sectdict = self._defaults
         else:
             try:
@@ -664,7 +894,8 @@
         else:
             d = self._delimiters[0]
         if self._defaults:
-            self._write_section(fp, DEFAULTSECT, self._defaults.items(), d)
+            self._write_section(fp, self.default_section,
+                                    self._defaults.items(), d)
         for section in self._sections:
             self._write_section(fp, section,
                                 self._sections[section].items(), d)
@@ -673,8 +904,8 @@
         """Write a single section to the specified `fp'."""
         fp.write("[{}]\n".format(section_name))
         for key, value in section_items:
-            if key == "__name__":
-                continue
+            value = self._interpolation.before_write(self, section_name, key,
+                                                     value)
             if value is not None or not self._allow_no_value:
                 value = delimiter + str(value).replace('\n', '\n\t')
             else:
@@ -684,7 +915,7 @@
 
     def remove_option(self, section, option):
         """Remove an option."""
-        if not section or section == DEFAULTSECT:
+        if not section or section == self.default_section:
             sectdict = self._defaults
         else:
             try:
@@ -702,13 +933,13 @@
         existed = section in self._sections
         if existed:
             del self._sections[section]
-            del self._views[section]
+            del self._proxies[section]
         return existed
 
     def __getitem__(self, key):
-        if key != DEFAULTSECT and not self.has_section(key):
+        if key != self.default_section and not self.has_section(key):
             raise KeyError(key)
-        return self._views[key]
+        return self._proxies[key]
 
     def __setitem__(self, key, value):
         # To conform with the mapping protocol, overwrites existing values in
@@ -720,21 +951,21 @@
         self.read_dict({key: value})
 
     def __delitem__(self, key):
-        if key == DEFAULTSECT:
+        if key == self.default_section:
             raise ValueError("Cannot remove the default section.")
         if not self.has_section(key):
             raise KeyError(key)
         self.remove_section(key)
 
     def __contains__(self, key):
-        return key == DEFAULTSECT or self.has_section(key)
+        return key == self.default_section or self.has_section(key)
 
     def __len__(self):
         return len(self._sections) + 1 # the default section
 
     def __iter__(self):
         # XXX does it break when underlying container state changed?
-        return itertools.chain((DEFAULTSECT,), self._sections.keys())
+        return itertools.chain((self.default_section,), self._sections.keys())
 
     def _read(self, fp, fpname):
         """Parse a sectioned configuration file.
@@ -761,18 +992,18 @@
         indent_level = 0
         e = None                              # None, or an exception
         for lineno, line in enumerate(fp, start=1):
-            # strip full line comments
             comment_start = None
-            for prefix in self._startonly_comment_prefixes:
-                if line.strip().startswith(prefix):
-                    comment_start = 0
-                    break
             # strip inline comments
-            for prefix in self._comment_prefixes:
+            for prefix in self._inline_comment_prefixes:
                 index = line.find(prefix)
                 if index == 0 or (index > 0 and line[index-1].isspace()):
                     comment_start = index
                     break
+            # strip full line comments
+            for prefix in self._comment_prefixes:
+                if line.strip().startswith(prefix):
+                    comment_start = 0
+                    break
             value = line[:comment_start].strip()
             if not value:
                 if self._empty_lines_in_values:
@@ -806,13 +1037,12 @@
                                                         lineno)
                         cursect = self._sections[sectname]
                         elements_added.add(sectname)
-                    elif sectname == DEFAULTSECT:
+                    elif sectname == self.default_section:
                         cursect = self._defaults
                     else:
                         cursect = self._dict()
-                        cursect['__name__'] = sectname
                         self._sections[sectname] = cursect
-                        self._views[sectname] = SectionProxy(self, sectname)
+                        self._proxies[sectname] = SectionProxy(self, sectname)
                         elements_added.add(sectname)
                     # So sections can't start with a continuation line
                     optname = None
@@ -836,13 +1066,10 @@
                         # match if it would set optval to None
                         if optval is not None:
                             optval = optval.strip()
-                            # allow empty values
-                            if optval == '""':
-                                optval = ''
                             cursect[optname] = [optval]
                         else:
                             # valueless option handling
-                            cursect[optname] = optval
+                            cursect[optname] = None
                     else:
                         # a non-fatal parsing error occurred. set up the
                         # exception but keep going. the exception will be
@@ -855,12 +1082,16 @@
         self._join_multiline_values()
 
     def _join_multiline_values(self):
-        all_sections = itertools.chain((self._defaults,),
-                                       self._sections.values())
-        for options in all_sections:
+        defaults = self.default_section, self._defaults
+        all_sections = itertools.chain((defaults,),
+                                       self._sections.items())
+        for section, options in all_sections:
             for name, val in options.items():
                 if isinstance(val, list):
-                    options[name] = '\n'.join(val).rstrip()
+                    val = '\n'.join(val).rstrip()
+                options[name] = self._interpolation.before_read(self,
+                                                                section,
+                                                                name, val)
 
     def _handle_error(self, exc, fpname, lineno, line):
         if not exc:
@@ -869,23 +1100,24 @@
         return exc
 
     def _unify_values(self, section, vars):
-        """Create a copy of the DEFAULTSECT with values from a specific
-        `section' and the `vars' dictionary. If provided, values in `vars'
-        take precendence.
+        """Create a sequence of lookups with 'vars' taking priority over
+        the 'section' which takes priority over the DEFAULTSECT.
+
         """
-        d = self._defaults.copy()
+        sectiondict = {}
         try:
-            d.update(self._sections[section])
+            sectiondict = self._sections[section]
         except KeyError:
-            if section != DEFAULTSECT:
+            if section != self.default_section:
                 raise NoSectionError(section)
         # Update with the entry specific variables
+        vardict = {}
         if vars:
             for key, value in vars.items():
                 if value is not None:
                     value = str(value)
-                d[self.optionxform(key)] = value
-        return d
+                vardict[self.optionxform(key)] = value
+        return _ChainMap(vardict, sectiondict, self._defaults)
 
     def _convert_to_boolean(self, value):
         """Return a boolean value translating from other types if necessary.
@@ -894,7 +1126,7 @@
             raise ValueError('Not a boolean: %s' % value)
         return self.BOOLEAN_STATES[value.lower()]
 
-    def _validate_value_type(self, value):
+    def _validate_value_types(self, *, section="", option="", value=""):
         """Raises a TypeError for non-string values.
 
         The only legal non-string value if we allow valueless
@@ -904,261 +1136,112 @@
         - we allow valueless options but the value is not None
 
         For compatibility reasons this method is not used in classic set()
-        for RawConfigParsers and ConfigParsers. It is invoked in every
-        case for mapping protocol access and in SafeConfigParser.set().
+        for RawConfigParsers. It is invoked in every case for mapping protocol
+        access and in ConfigParser.set().
         """
+        if not isinstance(section, str):
+            raise TypeError("section names must be strings")
+        if not isinstance(option, str):
+            raise TypeError("option keys must be strings")
         if not self._allow_no_value or value:
             if not isinstance(value, str):
                 raise TypeError("option values must be strings")
 
 
-
 class ConfigParser(RawConfigParser):
     """ConfigParser implementing interpolation."""
 
-    def get(self, section, option, *, raw=False, vars=None, fallback=_UNSET):
-        """Get an option value for a given section.
-
-        If `vars' is provided, it must be a dictionary. The option is looked up
-        in `vars' (if provided), `section', and in `DEFAULTSECT' in that order.
-        If the key is not found and `fallback' is provided, it is used as
-        a fallback value. `None' can be provided as a `fallback' value.
-
-        All % interpolations are expanded in the return values, unless the
-        optional argument `raw' is true.  Values for interpolation keys are
-        looked up in the same manner as the option.
-
-        Arguments `raw', `vars', and `fallback' are keyword only.
-
-        The section DEFAULT is special.
-        """
-        try:
-            d = self._unify_values(section, vars)
-        except NoSectionError:
-            if fallback is _UNSET:
-                raise
-            else:
-                return fallback
-        option = self.optionxform(option)
-        try:
-            value = d[option]
-        except KeyError:
-            if fallback is _UNSET:
-                raise NoOptionError(option, section)
-            else:
-                return fallback
-
-        if raw or value is None:
-            return value
-        else:
-            return self._interpolate(section, option, value, d)
-
-    def getint(self, section, option, *, raw=False, vars=None,
-               fallback=_UNSET):
-        try:
-            return self._get(section, int, option, raw=raw, vars=vars)
-        except (NoSectionError, NoOptionError):
-            if fallback is _UNSET:
-                raise
-            else:
-                return fallback
-
-    def getfloat(self, section, option, *, raw=False, vars=None,
-                 fallback=_UNSET):
-        try:
-            return self._get(section, float, option, raw=raw, vars=vars)
-        except (NoSectionError, NoOptionError):
-            if fallback is _UNSET:
-                raise
-            else:
-                return fallback
-
-    def getboolean(self, section, option, *, raw=False, vars=None,
-                   fallback=_UNSET):
-        try:
-            return self._get(section, self._convert_to_boolean, option,
-                             raw=raw, vars=vars)
-        except (NoSectionError, NoOptionError):
-            if fallback is _UNSET:
-                raise
-            else:
-                return fallback
-
-    def items(self, section, raw=False, vars=None):
-        """Return a list of (name, value) tuples for each option in a section.
-
-        All % interpolations are expanded in the return values, based on the
-        defaults passed into the constructor, unless the optional argument
-        `raw' is true.  Additional substitutions may be provided using the
-        `vars' argument, which must be a dictionary whose contents overrides
-        any pre-existing defaults.
-
-        The section DEFAULT is special.
-        """
-        d = self._defaults.copy()
-        try:
-            d.update(self._sections[section])
-        except KeyError:
-            if section != DEFAULTSECT:
-                raise NoSectionError(section)
-        # Update with the entry specific variables
-        if vars:
-            for key, value in vars.items():
-                d[self.optionxform(key)] = value
-        options = list(d.keys())
-        if "__name__" in options:
-            options.remove("__name__")
-        if raw:
-            return [(option, d[option])
-                    for option in options]
-        else:
-            return [(option, self._interpolate(section, option, d[option], d))
-                    for option in options]
-
-    def _interpolate(self, section, option, rawval, vars):
-        # do the string interpolation
-        value = rawval
-        depth = MAX_INTERPOLATION_DEPTH
-        while depth:                    # Loop through this until it's done
-            depth -= 1
-            if value and "%(" in value:
-                value = self._KEYCRE.sub(self._interpolation_replace, value)
-                try:
-                    value = value % vars
-                except KeyError as e:
-                    raise InterpolationMissingOptionError(
-                        option, section, rawval, e.args[0])
-            else:
-                break
-        if value and "%(" in value:
-            raise InterpolationDepthError(option, section, rawval)
-        return value
+    _DEFAULT_INTERPOLATION = BasicInterpolation()
 
-    _KEYCRE = re.compile(r"%\(([^)]*)\)s|.")
+    def set(self, section, option, value=None):
+        """Set an option.  Extends RawConfigParser.set by validating type and
+        interpolation syntax on the value."""
+        self._validate_value_types(option=option, value=value)
+        super().set(section, option, value)
 
-    def _interpolation_replace(self, match):
-        s = match.group(1)
-        if s is None:
-            return match.group()
-        else:
-            return "%%(%s)s" % self.optionxform(s)
+    def add_section(self, section):
+        """Create a new section in the configuration.  Extends
+        RawConfigParser.add_section by validating if the section name is
+        a string."""
+        self._validate_value_types(section=section)
+        super().add_section(section)
 
 
 class SafeConfigParser(ConfigParser):
-    """ConfigParser implementing sane interpolation."""
-
-    def _interpolate(self, section, option, rawval, vars):
-        # do the string interpolation
-        L = []
-        self._interpolate_some(option, L, rawval, section, vars, 1)
-        return ''.join(L)
-
-    _interpvar_re = re.compile(r"%\(([^)]+)\)s")
+    """ConfigParser alias for backwards compatibility purposes."""
 
-    def _interpolate_some(self, option, accum, rest, section, map, depth):
-        if depth > MAX_INTERPOLATION_DEPTH:
-            raise InterpolationDepthError(option, section, rest)
-        while rest:
-            p = rest.find("%")
-            if p < 0:
-                accum.append(rest)
-                return
-            if p > 0:
-                accum.append(rest[:p])
-                rest = rest[p:]
-            # p is no longer used
-            c = rest[1:2]
-            if c == "%":
-                accum.append("%")
-                rest = rest[2:]
-            elif c == "(":
-                m = self._interpvar_re.match(rest)
-                if m is None:
-                    raise InterpolationSyntaxError(option, section,
-                        "bad interpolation variable reference %r" % rest)
-                var = self.optionxform(m.group(1))
-                rest = rest[m.end():]
-                try:
-                    v = map[var]
-                except KeyError:
-                    raise InterpolationMissingOptionError(
-                        option, section, rest, var)
-                if "%" in v:
-                    self._interpolate_some(option, accum, v,
-                                           section, map, depth + 1)
-                else:
-                    accum.append(v)
-            else:
-                raise InterpolationSyntaxError(
-                    option, section,
-                    "'%%' must be followed by '%%' or '(', "
-                    "found: %r" % (rest,))
-
-    def set(self, section, option, value=None):
-        """Set an option.  Extend ConfigParser.set: check for string values."""
-        self._validate_value_type(value)
-        # check for bad percent signs
-        if value:
-            tmp_value = value.replace('%%', '') # escaped percent signs
-            tmp_value = self._interpvar_re.sub('', tmp_value) # valid syntax
-            if '%' in tmp_value:
-                raise ValueError("invalid interpolation syntax in %r at "
-                                "position %d" % (value, tmp_value.find('%')))
-        ConfigParser.set(self, section, option, value)
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        warnings.warn(
+            "The SafeConfigParser class has been renamed to ConfigParser "
+            "in Python 3.2. This alias will be removed in future versions."
+            " Use ConfigParser directly instead.",
+            DeprecationWarning, stacklevel=2
+        )
 
 
 class SectionProxy(MutableMapping):
     """A proxy for a single section from a parser."""
 
-    _noname = ("__name__ special key access and modification "
-               "not supported through the mapping interface.")
-
-    def __init__(self, parser, section_name):
-        """Creates a view on a section named `section_name` in `parser`."""
+    def __init__(self, parser, name):
+        """Creates a view on a section of the specified `name` in `parser`."""
         self._parser = parser
-        self._section = section_name
-        self.getint = functools.partial(self._parser.getint,
-                                        self._section)
-        self.getfloat = functools.partial(self._parser.getfloat,
-                                          self._section)
-        self.getboolean = functools.partial(self._parser.getboolean,
-                                            self._section)
+        self._name = name
 
     def __repr__(self):
-        return '<Section: {}>'.format(self._section)
+        return '<Section: {}>'.format(self._name)
 
     def __getitem__(self, key):
-        if key == '__name__':
-            raise ValueError(self._noname)
-        if not self._parser.has_option(self._section, key):
+        if not self._parser.has_option(self._name, key):
             raise KeyError(key)
-        return self._parser.get(self._section, key)
+        return self._parser.get(self._name, key)
 
     def __setitem__(self, key, value):
-        if key == '__name__':
-            raise ValueError(self._noname)
-        self._parser._validate_value_type(value)
-        return self._parser.set(self._section, key, value)
+        self._parser._validate_value_types(option=key, value=value)
+        return self._parser.set(self._name, key, value)
 
     def __delitem__(self, key):
-        if key == '__name__':
-            raise ValueError(self._noname)
-        if not self._parser.has_option(self._section, key):
+        if not (self._parser.has_option(self._name, key) and
+                self._parser.remove_option(self._name, key)):
             raise KeyError(key)
-        return self._parser.remove_option(self._section, key)
 
     def __contains__(self, key):
-        if key == '__name__':
-            return False
-        return self._parser.has_option(self._section, key)
+        return self._parser.has_option(self._name, key)
 
     def __len__(self):
-        # __name__ is properly hidden by .options()
-        # XXX weak performance
-        return len(self._parser.options(self._section))
+        return len(self._options())
 
     def __iter__(self):
-        # __name__ is properly hidden by .options()
-        # XXX weak performance
-        # XXX does not break when underlying container state changed
-        return self._parser.options(self._section).__iter__()
+        return self._options().__iter__()
+
+    def _options(self):
+        if self._name != self._parser.default_section:
+            return self._parser.options(self._name)
+        else:
+            return self._parser.defaults()
+
+    def get(self, option, fallback=None, *, raw=False, vars=None):
+        return self._parser.get(self._name, option, raw=raw, vars=vars,
+                                fallback=fallback)
+
+    def getint(self, option, fallback=None, *, raw=False, vars=None):
+        return self._parser.getint(self._name, option, raw=raw, vars=vars,
+                                   fallback=fallback)
+
+    def getfloat(self, option, fallback=None, *, raw=False, vars=None):
+        return self._parser.getfloat(self._name, option, raw=raw, vars=vars,
+                                     fallback=fallback)
+
+    def getboolean(self, option, fallback=None, *, raw=False, vars=None):
+        return self._parser.getboolean(self._name, option, raw=raw, vars=vars,
+                                       fallback=fallback)
+
+    @property
+    def parser(self):
+        # The parser object of the proxy is read-only.
+        return self._parser
+
+    @property
+    def name(self):
+        # The name of the section on a proxy is read-only.
+        return self._name

Modified: python/branches/pep-3151/Lib/contextlib.py
==============================================================================
--- python/branches/pep-3151/Lib/contextlib.py	(original)
+++ python/branches/pep-3151/Lib/contextlib.py	Sat Feb 26 08:16:32 2011
@@ -17,7 +17,7 @@
         return inner
 
 
-class GeneratorContextManager(ContextDecorator):
+class _GeneratorContextManager(ContextDecorator):
     """Helper for @contextmanager decorator."""
 
     def __init__(self, gen):
@@ -92,7 +92,7 @@
     """
     @wraps(func)
     def helper(*args, **kwds):
-        return GeneratorContextManager(func(*args, **kwds))
+        return _GeneratorContextManager(func(*args, **kwds))
     return helper
 
 

Modified: python/branches/pep-3151/Lib/ctypes/test/test_callbacks.py
==============================================================================
--- python/branches/pep-3151/Lib/ctypes/test/test_callbacks.py	(original)
+++ python/branches/pep-3151/Lib/ctypes/test/test_callbacks.py	Sat Feb 26 08:16:32 2011
@@ -200,6 +200,42 @@
 
             windll.user32.EnumWindows(EnumWindowsCallbackFunc, 0)
 
+    def test_callback_register_int(self):
+        # Issue #8275: buggy handling of callback args under Win64
+        # NOTE: should be run on release builds as well
+        dll = CDLL(_ctypes_test.__file__)
+        CALLBACK = CFUNCTYPE(c_int, c_int, c_int, c_int, c_int, c_int)
+        # All this function does is call the callback with its args squared
+        func = dll._testfunc_cbk_reg_int
+        func.argtypes = (c_int, c_int, c_int, c_int, c_int, CALLBACK)
+        func.restype = c_int
+
+        def callback(a, b, c, d, e):
+            return a + b + c + d + e
+
+        result = func(2, 3, 4, 5, 6, CALLBACK(callback))
+        self.assertEqual(result, callback(2*2, 3*3, 4*4, 5*5, 6*6))
+
+    def test_callback_register_double(self):
+        # Issue #8275: buggy handling of callback args under Win64
+        # NOTE: should be run on release builds as well
+        dll = CDLL(_ctypes_test.__file__)
+        CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
+                             c_double, c_double)
+        # All this function does is call the callback with its args squared
+        func = dll._testfunc_cbk_reg_double
+        func.argtypes = (c_double, c_double, c_double,
+                         c_double, c_double, CALLBACK)
+        func.restype = c_double
+
+        def callback(a, b, c, d, e):
+            return a + b + c + d + e
+
+        result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
+        self.assertEqual(result,
+                         callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
+
+
 ################################################################
 
 if __name__ == '__main__':

Modified: python/branches/pep-3151/Lib/ctypes/test/test_keeprefs.py
==============================================================================
--- python/branches/pep-3151/Lib/ctypes/test/test_keeprefs.py	(original)
+++ python/branches/pep-3151/Lib/ctypes/test/test_keeprefs.py	Sat Feb 26 08:16:32 2011
@@ -4,19 +4,19 @@
 class SimpleTestCase(unittest.TestCase):
     def test_cint(self):
         x = c_int()
-        self.assertEquals(x._objects, None)
+        self.assertEqual(x._objects, None)
         x.value = 42
-        self.assertEquals(x._objects, None)
+        self.assertEqual(x._objects, None)
         x = c_int(99)
-        self.assertEquals(x._objects, None)
+        self.assertEqual(x._objects, None)
 
     def test_ccharp(self):
         x = c_char_p()
-        self.assertEquals(x._objects, None)
+        self.assertEqual(x._objects, None)
         x.value = b"abc"
-        self.assertEquals(x._objects, b"abc")
+        self.assertEqual(x._objects, b"abc")
         x = c_char_p(b"spam")
-        self.assertEquals(x._objects, b"spam")
+        self.assertEqual(x._objects, b"spam")
 
 class StructureTestCase(unittest.TestCase):
     def test_cint_struct(self):
@@ -25,21 +25,21 @@
                         ("b", c_int)]
 
         x = X()
-        self.assertEquals(x._objects, None)
+        self.assertEqual(x._objects, None)
         x.a = 42
         x.b = 99
-        self.assertEquals(x._objects, None)
+        self.assertEqual(x._objects, None)
 
     def test_ccharp_struct(self):
         class X(Structure):
             _fields_ = [("a", c_char_p),
                         ("b", c_char_p)]
         x = X()
-        self.assertEquals(x._objects, None)
+        self.assertEqual(x._objects, None)
 
         x.a = b"spam"
         x.b = b"foo"
-        self.assertEquals(x._objects, {"0": b"spam", "1": b"foo"})
+        self.assertEqual(x._objects, {"0": b"spam", "1": b"foo"})
 
     def test_struct_struct(self):
         class POINT(Structure):
@@ -52,28 +52,28 @@
         r.ul.y = 1
         r.lr.x = 2
         r.lr.y = 3
-        self.assertEquals(r._objects, None)
+        self.assertEqual(r._objects, None)
 
         r = RECT()
         pt = POINT(1, 2)
         r.ul = pt
-        self.assertEquals(r._objects, {'0': {}})
+        self.assertEqual(r._objects, {'0': {}})
         r.ul.x = 22
         r.ul.y = 44
-        self.assertEquals(r._objects, {'0': {}})
+        self.assertEqual(r._objects, {'0': {}})
         r.lr = POINT()
-        self.assertEquals(r._objects, {'0': {}, '1': {}})
+        self.assertEqual(r._objects, {'0': {}, '1': {}})
 
 class ArrayTestCase(unittest.TestCase):
     def test_cint_array(self):
         INTARR = c_int * 3
 
         ia = INTARR()
-        self.assertEquals(ia._objects, None)
+        self.assertEqual(ia._objects, None)
         ia[0] = 1
         ia[1] = 2
         ia[2] = 3
-        self.assertEquals(ia._objects, None)
+        self.assertEqual(ia._objects, None)
 
         class X(Structure):
             _fields_ = [("x", c_int),
@@ -83,9 +83,9 @@
         x.x = 1000
         x.a[0] = 42
         x.a[1] = 96
-        self.assertEquals(x._objects, None)
+        self.assertEqual(x._objects, None)
         x.a = ia
-        self.assertEquals(x._objects, {'1': {}})
+        self.assertEqual(x._objects, {'1': {}})
 
 class PointerTestCase(unittest.TestCase):
     def test_p_cint(self):

Modified: python/branches/pep-3151/Lib/ctypes/test/test_memfunctions.py
==============================================================================
--- python/branches/pep-3151/Lib/ctypes/test/test_memfunctions.py	(original)
+++ python/branches/pep-3151/Lib/ctypes/test/test_memfunctions.py	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,5 @@
 import sys
+from test import support
 import unittest
 from ctypes import *
 
@@ -49,6 +50,7 @@
         self.assertEqual(cast(a, POINTER(c_byte))[:7:7],
                              [97])
 
+    @support.refcount_test
     def test_string_at(self):
         s = string_at(b"foo bar")
         # XXX The following may be wrong, depending on how Python

Modified: python/branches/pep-3151/Lib/ctypes/test/test_python_api.py
==============================================================================
--- python/branches/pep-3151/Lib/ctypes/test/test_python_api.py	(original)
+++ python/branches/pep-3151/Lib/ctypes/test/test_python_api.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,6 @@
 from ctypes import *
 import unittest, sys
+from test import support
 from ctypes.test import is_resource_enabled
 
 ################################################################
@@ -25,6 +26,7 @@
 
         self.assertEqual(PyBytes_FromStringAndSize(b"abcdefghi", 3), b"abc")
 
+    @support.refcount_test
     def test_PyString_FromString(self):
         pythonapi.PyBytes_FromString.restype = py_object
         pythonapi.PyBytes_FromString.argtypes = (c_char_p,)
@@ -56,6 +58,7 @@
             del res
             self.assertEqual(grc(42), ref42)
 
+    @support.refcount_test
     def test_PyObj_FromPtr(self):
         s = "abc def ghi jkl"
         ref = grc(s)

Modified: python/branches/pep-3151/Lib/ctypes/test/test_refcounts.py
==============================================================================
--- python/branches/pep-3151/Lib/ctypes/test/test_refcounts.py	(original)
+++ python/branches/pep-3151/Lib/ctypes/test/test_refcounts.py	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,5 @@
 import unittest
+from test import support
 import ctypes
 import gc
 
@@ -10,6 +11,7 @@
 
 class RefcountTestCase(unittest.TestCase):
 
+    @support.refcount_test
     def test_1(self):
         from sys import getrefcount as grc
 
@@ -34,6 +36,7 @@
         self.assertEqual(grc(callback), 2)
 
 
+    @support.refcount_test
     def test_refcount(self):
         from sys import getrefcount as grc
         def func(*args):

Modified: python/branches/pep-3151/Lib/ctypes/test/test_stringptr.py
==============================================================================
--- python/branches/pep-3151/Lib/ctypes/test/test_stringptr.py	(original)
+++ python/branches/pep-3151/Lib/ctypes/test/test_stringptr.py	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,5 @@
 import unittest
+from test import support
 from ctypes import *
 
 import _ctypes_test
@@ -7,6 +8,7 @@
 
 class StringPtrTestCase(unittest.TestCase):
 
+    @support.refcount_test
     def test__POINTER_c_char(self):
         class X(Structure):
             _fields_ = [("str", POINTER(c_char))]

Modified: python/branches/pep-3151/Lib/datetime.py
==============================================================================
--- python/branches/pep-3151/Lib/datetime.py	(original)
+++ python/branches/pep-3151/Lib/datetime.py	Sat Feb 26 08:16:32 2011
@@ -173,9 +173,9 @@
 # Correctly substitute for %z and %Z escapes in strftime formats.
 def _wrap_strftime(object, format, timetuple):
     year = timetuple[0]
-    if year < 1900:
-        raise ValueError("year=%d is before 1900; the datetime strftime() "
-                         "methods require year >= 1900" % year)
+    if year < 1000:
+        raise ValueError("year=%d is before 1000; the datetime strftime() "
+                         "methods require year >= 1000" % year)
     # Don't call utcoffset() or tzname() unless actually needed.
     freplace = None # the string to use for %f
     zreplace = None # the string to use for %z
@@ -1189,7 +1189,7 @@
         """Format using strftime().  The date part of the timestamp passed
         to underlying strftime should not be used.
         """
-        # The year must be >= 1900 else Python's strftime implementation
+        # The year must be >= 1000 else Python's strftime implementation
         # can raise a bogus exception.
         timetuple = (1900, 1, 1,
                      self._hour, self._minute, self._second,

Modified: python/branches/pep-3151/Lib/dbm/dumb.py
==============================================================================
--- python/branches/pep-3151/Lib/dbm/dumb.py	(original)
+++ python/branches/pep-3151/Lib/dbm/dumb.py	Sat Feb 26 08:16:32 2011
@@ -203,7 +203,7 @@
         # The blocks used by the associated value are lost.
         del self._index[key]
         # XXX It's unclear why we do a _commit() here (the code always
-        # XXX has, so I'm not changing it).  _setitem__ doesn't try to
+        # XXX has, so I'm not changing it).  __setitem__ doesn't try to
         # XXX keep the directory file in synch.  Why should we?  Or
         # XXX why shouldn't __setitem__?
         self._commit()
@@ -232,7 +232,7 @@
 
     __del__ = close
 
-    def _chmod (self, file):
+    def _chmod(self, file):
         if hasattr(self._os, 'chmod'):
             self._os.chmod(file, self._mode)
 

Modified: python/branches/pep-3151/Lib/decimal.py
==============================================================================
--- python/branches/pep-3151/Lib/decimal.py	(original)
+++ python/branches/pep-3151/Lib/decimal.py	Sat Feb 26 08:16:32 2011
@@ -132,6 +132,7 @@
 ]
 
 __version__ = '1.70'    # Highest version of the spec this complies with
+                        # See http://speleotrove.com/decimal/
 
 import copy as _copy
 import math as _math
@@ -957,7 +958,8 @@
         else:
             exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
         hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
-        return hash_ if self >= 0 else -hash_
+        ans = hash_ if self >= 0 else -hash_
+        return -2 if ans == -1 else ans
 
     def as_tuple(self):
         """Represents the number as a triple tuple.
@@ -5525,23 +5527,7 @@
 
 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
 
-# This function from Tim Peters was taken from here:
-# http://mail.python.org/pipermail/python-list/1999-July/007758.html
-# The correction being in the function definition is for speed, and
-# the whole function is not resolved with math.log because of avoiding
-# the use of floats.
-def _nbits(n, correction = {
-        '0': 4, '1': 3, '2': 2, '3': 2,
-        '4': 1, '5': 1, '6': 1, '7': 1,
-        '8': 0, '9': 0, 'a': 0, 'b': 0,
-        'c': 0, 'd': 0, 'e': 0, 'f': 0}):
-    """Number of bits in binary representation of the positive integer n,
-    or 0 if n == 0.
-    """
-    if n < 0:
-        raise ValueError("The argument to _nbits should be nonnegative.")
-    hex_n = "%x" % n
-    return 4*len(hex_n) - correction[hex_n[0]]
+_nbits = int.bit_length
 
 def _sqrt_nearest(n, a):
     """Closest integer to the square root of the positive integer n.  a is
@@ -5990,7 +5976,7 @@
 #
 # A format specifier for Decimal looks like:
 #
-#   [[fill]align][sign][0][minimumwidth][,][.precision][type]
+#   [[fill]align][sign][#][0][minimumwidth][,][.precision][type]
 
 _parse_format_specifier_regex = re.compile(r"""\A
 (?:
@@ -5998,6 +5984,7 @@
    (?P<align>[<>=^])
 )?
 (?P<sign>[-+ ])?
+(?P<alt>\#)?
 (?P<zeropad>0)?
 (?P<minimumwidth>(?!0)\d+)?
 (?P<thousands_sep>,)?
@@ -6213,7 +6200,7 @@
 
     sign = _format_sign(is_negative, spec)
 
-    if fracpart:
+    if fracpart or spec['alt']:
         fracpart = spec['decimal_point'] + fracpart
 
     if exp != 0 or spec['type'] in 'eE':
@@ -6258,5 +6245,5 @@
 
 
 if __name__ == '__main__':
-    import doctest, sys
-    doctest.testmod(sys.modules[__name__])
+    import doctest, decimal
+    doctest.testmod(decimal)

Modified: python/branches/pep-3151/Lib/difflib.py
==============================================================================
--- python/branches/pep-3151/Lib/difflib.py	(original)
+++ python/branches/pep-3151/Lib/difflib.py	Sat Feb 26 08:16:32 2011
@@ -32,6 +32,7 @@
            'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
            'unified_diff', 'HtmlDiff', 'Match']
 
+import warnings
 import heapq
 from collections import namedtuple as _namedtuple
 
@@ -150,7 +151,7 @@
         Return an upper bound on ratio() very quickly.
     """
 
-    def __init__(self, isjunk=None, a='', b=''):
+    def __init__(self, isjunk=None, a='', b='', autojunk=True):
         """Construct a SequenceMatcher.
 
         Optional arg isjunk is None (the default), or a one-argument
@@ -168,6 +169,10 @@
         Optional arg b is the second of two sequences to be compared.  By
         default, an empty string.  The elements of b must be hashable. See
         also .set_seqs() and .set_seq2().
+
+        Optional arg autojunk should be set to False to disable the
+        "automatic junk heuristic" that treats popular elements as junk
+        (see module documentation for more information).
         """
 
         # Members:
@@ -178,7 +183,7 @@
         #      we need to do to 'a' to change it into 'b'?"
         # b2j
         #      for x in b, b2j[x] is a list of the indices (into b)
-        #      at which x appears; junk elements do not appear
+        #      at which x appears; junk and popular elements do not appear
         # fullbcount
         #      for x in b, fullbcount[x] == the number of times x
         #      appears in b; only materialized if really needed (used
@@ -200,17 +205,14 @@
         #      subtle but helpful effects on the algorithm, which I'll
         #      get around to writing up someday <0.9 wink>.
         #      DON'T USE!  Only __chain_b uses this.  Use isbjunk.
-        # isbjunk
-        #      for x in b, isbjunk(x) == isjunk(x) but much faster;
-        #      it's really the __contains__ method of a hidden dict.
-        #      DOES NOT WORK for x in a!
-        # isbpopular
-        #      for x in b, isbpopular(x) is true iff b is reasonably long
-        #      (at least 200 elements) and x accounts for more than 1% of
-        #      its elements.  DOES NOT WORK for x in a!
+        # bjunk
+        #      the items in b for which isjunk is True.
+        # bpopular
+        #      nonjunk items in b treated as junk by the heuristic (if used).
 
         self.isjunk = isjunk
         self.a = self.b = None
+        self.autojunk = autojunk
         self.set_seqs(a, b)
 
     def set_seqs(self, a, b):
@@ -287,7 +289,7 @@
     # from starting any matching block at a junk element ...
     # also creates the fast isbjunk function ...
     # b2j also does not contain entries for "popular" elements, meaning
-    # elements that account for more than 1% of the total elements, and
+    # elements that account for more than 1 + 1% of the total elements, and
     # when the sequence is reasonably large (>= 200 elements); this can
     # be viewed as an adaptive notion of semi-junk, and yields an enormous
     # speedup when, e.g., comparing program files with hundreds of
@@ -308,44 +310,46 @@
         # out the junk later is much cheaper than building b2j "right"
         # from the start.
         b = self.b
-        n = len(b)
         self.b2j = b2j = {}
-        populardict = {}
+
         for i, elt in enumerate(b):
-            if elt in b2j:
-                indices = b2j[elt]
-                if n >= 200 and len(indices) * 100 > n:
-                    populardict[elt] = 1
-                    del indices[:]
-                else:
-                    indices.append(i)
-            else:
-                b2j[elt] = [i]
-
-        # Purge leftover indices for popular elements.
-        for elt in populardict:
-            del b2j[elt]
-
-        # Now b2j.keys() contains elements uniquely, and especially when
-        # the sequence is a string, that's usually a good deal smaller
-        # than len(string).  The difference is the number of isjunk calls
-        # saved.
+            indices = b2j.setdefault(elt, [])
+            indices.append(i)
+
+        # Purge junk elements
+        self.bjunk = junk = set()
         isjunk = self.isjunk
-        junkdict = {}
         if isjunk:
-            for d in populardict, b2j:
-                for elt in list(d.keys()):
-                    if isjunk(elt):
-                        junkdict[elt] = 1
-                        del d[elt]
-
-        # Now for x in b, isjunk(x) == x in junkdict, but the
-        # latter is much faster.  Note too that while there may be a
-        # lot of junk in the sequence, the number of *unique* junk
-        # elements is probably small.  So the memory burden of keeping
-        # this dict alive is likely trivial compared to the size of b2j.
-        self.isbjunk = junkdict.__contains__
-        self.isbpopular = populardict.__contains__
+            for elt in b2j.keys():
+                if isjunk(elt):
+                    junk.add(elt)
+            for elt in junk: # separate loop avoids separate list of keys
+                del b2j[elt]
+
+        # Purge popular elements that are not junk
+        self.bpopular = popular = set()
+        n = len(b)
+        if self.autojunk and n >= 200:
+            ntest = n // 100 + 1
+            for elt, idxs in b2j.items():
+                if len(idxs) > ntest:
+                    popular.add(elt)
+            for elt in popular: # ditto; as fast for 1% deletion
+                del b2j[elt]
+
+    def isbjunk(self, item):
+        "Deprecated; use 'item in SequenceMatcher().bjunk'."
+        warnings.warn("'SequenceMatcher().isbjunk(item)' is deprecated;\n"
+                      "use 'item in SMinstance.bjunk' instead.",
+                      DeprecationWarning, 2)
+        return item in self.bjunk
+
+    def isbpopular(self, item):
+        "Deprecated; use 'item in SequenceMatcher().bpopular'."
+        warnings.warn("'SequenceMatcher().isbpopular(item)' is deprecated;\n"
+                      "use 'item in SMinstance.bpopular' instead.",
+                      DeprecationWarning, 2)
+        return item in self.bpopular
 
     def find_longest_match(self, alo, ahi, blo, bhi):
         """Find longest matching block in a[alo:ahi] and b[blo:bhi].
@@ -403,7 +407,7 @@
         # Windiff ends up at the same place as diff, but by pairing up
         # the unique 'b's and then matching the first two 'a's.
 
-        a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
+        a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__
         besti, bestj, bestsize = alo, blo, 0
         # find longest junk-free match
         # during an iteration of the loop, j2len[j] = length of longest

Modified: python/branches/pep-3151/Lib/distutils/__init__.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/__init__.py	(original)
+++ python/branches/pep-3151/Lib/distutils/__init__.py	Sat Feb 26 08:16:32 2011
@@ -15,5 +15,5 @@
 # Updated automatically by the Python release process.
 #
 #--start constants--
-__version__ = "3.2a3"
+__version__ = "3.3a0"
 #--end constants--

Modified: python/branches/pep-3151/Lib/distutils/archive_util.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/archive_util.py	(original)
+++ python/branches/pep-3151/Lib/distutils/archive_util.py	Sat Feb 26 08:16:32 2011
@@ -68,7 +68,7 @@
 def make_zipfile(base_name, base_dir, verbose=0, dry_run=0):
     """Create a zip file from all the files under 'base_dir'.
 
-    The output zip file will be named 'base_dir' + ".zip".  Uses either the
+    The output zip file will be named 'base_name' + ".zip".  Uses either the
     "zipfile" Python module (if available) or the InfoZIP "zip" utility
     (if installed and found on the default search path).  If neither tool is
     available, raises DistutilsExecError.  Returns the name of the output zip

Modified: python/branches/pep-3151/Lib/distutils/command/bdist_wininst.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/command/bdist_wininst.py	(original)
+++ python/branches/pep-3151/Lib/distutils/command/bdist_wininst.py	Sat Feb 26 08:16:32 2011
@@ -263,11 +263,11 @@
         cfgdata = cfgdata + b"\0"
         if self.pre_install_script:
             # We need to normalize newlines, so we open in text mode and
-            # convert back to bytes. "latin1" simply avoids any possible
+            # convert back to bytes. "latin-1" simply avoids any possible
             # failures.
             with open(self.pre_install_script, "r",
-                encoding="latin1") as script:
-                script_data = script.read().encode("latin1")
+                encoding="latin-1") as script:
+                script_data = script.read().encode("latin-1")
             cfgdata = cfgdata + script_data + b"\n\0"
         else:
             # empty pre-install script

Modified: python/branches/pep-3151/Lib/distutils/command/build_ext.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/command/build_ext.py	(original)
+++ python/branches/pep-3151/Lib/distutils/command/build_ext.py	Sat Feb 26 08:16:32 2011
@@ -214,7 +214,7 @@
 
             elif MSVC_VERSION == 8:
                 self.library_dirs.append(os.path.join(sys.exec_prefix,
-                                         'PC', 'VS8.0', 'win32release'))
+                                         'PC', 'VS8.0'))
             elif MSVC_VERSION == 7:
                 self.library_dirs.append(os.path.join(sys.exec_prefix,
                                          'PC', 'VS7.1'))

Modified: python/branches/pep-3151/Lib/distutils/command/install.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/command/install.py	(original)
+++ python/branches/pep-3151/Lib/distutils/command/install.py	Sat Feb 26 08:16:32 2011
@@ -48,7 +48,7 @@
     'unix_prefix': {
         'purelib': '$base/lib/python$py_version_short/site-packages',
         'platlib': '$platbase/lib/python$py_version_short/site-packages',
-        'headers': '$base/include/python$py_version_short/$dist_name',
+        'headers': '$base/include/python$py_version_short$abiflags/$dist_name',
         'scripts': '$base/bin',
         'data'   : '$base',
         },
@@ -82,7 +82,8 @@
     INSTALL_SCHEMES['unix_user'] = {
         'purelib': '$usersite',
         'platlib': '$usersite',
-        'headers': '$userbase/include/python$py_version_short/$dist_name',
+        'headers':
+            '$userbase/include/python$py_version_short$abiflags/$dist_name',
         'scripts': '$userbase/bin',
         'data'   : '$userbase',
         }
@@ -312,6 +313,11 @@
 
         py_version = sys.version.split()[0]
         (prefix, exec_prefix) = get_config_vars('prefix', 'exec_prefix')
+        try:
+            abiflags = sys.abiflags
+        except AttributeError:
+            # sys.abiflags may not be defined on all platforms.
+            abiflags = ''
         self.config_vars = {'dist_name': self.distribution.get_name(),
                             'dist_version': self.distribution.get_version(),
                             'dist_fullname': self.distribution.get_fullname(),
@@ -322,6 +328,7 @@
                             'prefix': prefix,
                             'sys_exec_prefix': exec_prefix,
                             'exec_prefix': exec_prefix,
+                            'abiflags': abiflags,
                            }
 
         if HAS_USER_SITE:

Modified: python/branches/pep-3151/Lib/distutils/dir_util.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/dir_util.py	(original)
+++ python/branches/pep-3151/Lib/distutils/dir_util.py	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,7 @@
 __revision__ = "$Id$"
 
 import os, sys
+import errno
 from distutils.errors import DistutilsFileError, DistutilsInternalError
 from distutils import log
 

Modified: python/branches/pep-3151/Lib/distutils/msvc9compiler.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/msvc9compiler.py	(original)
+++ python/branches/pep-3151/Lib/distutils/msvc9compiler.py	Sat Feb 26 08:16:32 2011
@@ -282,7 +282,6 @@
                 result[key] = removeDuplicates(value)
 
     finally:
-        popen.stdin.close()
         popen.stdout.close()
         popen.stderr.close()
 

Modified: python/branches/pep-3151/Lib/distutils/sysconfig.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/sysconfig.py	(original)
+++ python/branches/pep-3151/Lib/distutils/sysconfig.py	Sat Feb 26 08:16:32 2011
@@ -11,7 +11,6 @@
 
 __revision__ = "$Id$"
 
-import io
 import os
 import re
 import sys
@@ -49,6 +48,18 @@
     return False
 python_build = _python_build()
 
+# Calculate the build qualifier flags if they are defined.  Adding the flags
+# to the include and lib directories only makes sense for an installation, not
+# an in-source build.
+build_flags = ''
+try:
+    if not python_build:
+        build_flags = sys.abiflags
+except AttributeError:
+    # It's not a configure-based build, so the sys module doesn't have
+    # this attribute, which is fine.
+    pass
+
 def get_python_version():
     """Return a string containing the major and minor Python version,
     leaving off the patchlevel.  Sample return values could be '1.5'
@@ -83,7 +94,8 @@
             else:
                 incdir = os.path.join(get_config_var('srcdir'), 'Include')
                 return os.path.normpath(incdir)
-        return os.path.join(prefix, "include", "python" + get_python_version())
+        python_dir = 'python' + get_python_version() + build_flags
+        return os.path.join(prefix, "include", python_dir)
     elif os.name == "nt":
         return os.path.join(prefix, "include")
     elif os.name == "os2":
@@ -209,7 +221,8 @@
     if python_build:
         return os.path.join(os.path.dirname(sys.executable), "Makefile")
     lib_dir = get_python_lib(plat_specific=1, standard_lib=1)
-    return os.path.join(lib_dir, "config", "Makefile")
+    config_file = 'config-{}{}'.format(get_python_version(), build_flags)
+    return os.path.join(lib_dir, config_file, 'Makefile')
 
 
 def parse_config_h(fp, g=None):

Modified: python/branches/pep-3151/Lib/distutils/tests/test_archive_util.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_archive_util.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_archive_util.py	Sat Feb 26 08:16:32 2011
@@ -113,7 +113,7 @@
 
         self.assertTrue(os.path.exists(tarball2))
         # let's compare both tarballs
-        self.assertEquals(self._tarinfo(tarball), self._tarinfo(tarball2))
+        self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
 
         # trying an uncompressed one
         base_name = os.path.join(tmpdir2, 'archive')
@@ -153,7 +153,7 @@
             os.chdir(old_dir)
         tarball = base_name + '.tar.Z'
         self.assertTrue(os.path.exists(tarball))
-        self.assertEquals(len(w.warnings), 1)
+        self.assertEqual(len(w.warnings), 1)
 
         # same test with dry_run
         os.remove(tarball)
@@ -167,7 +167,7 @@
         finally:
             os.chdir(old_dir)
         self.assertTrue(not os.path.exists(tarball))
-        self.assertEquals(len(w.warnings), 1)
+        self.assertEqual(len(w.warnings), 1)
 
     @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
     def test_make_zipfile(self):
@@ -184,9 +184,9 @@
         tarball = base_name + '.zip'
 
     def test_check_archive_formats(self):
-        self.assertEquals(check_archive_formats(['gztar', 'xxx', 'zip']),
-                          'xxx')
-        self.assertEquals(check_archive_formats(['gztar', 'zip']), None)
+        self.assertEqual(check_archive_formats(['gztar', 'xxx', 'zip']),
+                         'xxx')
+        self.assertEqual(check_archive_formats(['gztar', 'zip']), None)
 
     def test_make_archive(self):
         tmpdir = self.mkdtemp()
@@ -203,7 +203,7 @@
                 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
             except:
                 pass
-            self.assertEquals(os.getcwd(), current_dir)
+            self.assertEqual(os.getcwd(), current_dir)
         finally:
             del ARCHIVE_FORMATS['xxx']
 

Modified: python/branches/pep-3151/Lib/distutils/tests/test_bdist.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_bdist.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_bdist.py	Sat Feb 26 08:16:32 2011
@@ -24,7 +24,7 @@
         cmd = bdist(dist)
         cmd.formats = ['msi']
         cmd.ensure_finalized()
-        self.assertEquals(cmd.formats, ['msi'])
+        self.assertEqual(cmd.formats, ['msi'])
 
         # what format bdist offers ?
         # XXX an explicit list in bdist is
@@ -35,7 +35,7 @@
         formats.sort()
         founded = list(cmd.format_command.keys())
         founded.sort()
-        self.assertEquals(founded, formats)
+        self.assertEqual(founded, formats)
 
 def test_suite():
     return unittest.makeSuite(BuildTestCase)

Modified: python/branches/pep-3151/Lib/distutils/tests/test_bdist_dumb.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_bdist_dumb.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_bdist_dumb.py	Sat Feb 26 08:16:32 2011
@@ -69,7 +69,7 @@
             base = base.replace(':', '-')
 
         wanted = ['%s.zip' % base]
-        self.assertEquals(dist_created, wanted)
+        self.assertEqual(dist_created, wanted)
 
         # now let's check what we have in the zip file
         # XXX to be done

Modified: python/branches/pep-3151/Lib/distutils/tests/test_build.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_build.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_build.py	Sat Feb 26 08:16:32 2011
@@ -18,11 +18,11 @@
         cmd.finalize_options()
 
         # if not specified, plat_name gets the current platform
-        self.assertEquals(cmd.plat_name, get_platform())
+        self.assertEqual(cmd.plat_name, get_platform())
 
         # build_purelib is build + lib
         wanted = os.path.join(cmd.build_base, 'lib')
-        self.assertEquals(cmd.build_purelib, wanted)
+        self.assertEqual(cmd.build_purelib, wanted)
 
         # build_platlib is 'build/lib.platform-x.x[-pydebug]'
         # examples:
@@ -32,21 +32,21 @@
             self.assertTrue(cmd.build_platlib.endswith('-pydebug'))
             plat_spec += '-pydebug'
         wanted = os.path.join(cmd.build_base, 'lib' + plat_spec)
-        self.assertEquals(cmd.build_platlib, wanted)
+        self.assertEqual(cmd.build_platlib, wanted)
 
         # by default, build_lib = build_purelib
-        self.assertEquals(cmd.build_lib, cmd.build_purelib)
+        self.assertEqual(cmd.build_lib, cmd.build_purelib)
 
         # build_temp is build/temp.<plat>
         wanted = os.path.join(cmd.build_base, 'temp' + plat_spec)
-        self.assertEquals(cmd.build_temp, wanted)
+        self.assertEqual(cmd.build_temp, wanted)
 
         # build_scripts is build/scripts-x.x
         wanted = os.path.join(cmd.build_base, 'scripts-' +  sys.version[0:3])
-        self.assertEquals(cmd.build_scripts, wanted)
+        self.assertEqual(cmd.build_scripts, wanted)
 
         # executable is os.path.normpath(sys.executable)
-        self.assertEquals(cmd.executable, os.path.normpath(sys.executable))
+        self.assertEqual(cmd.executable, os.path.normpath(sys.executable))
 
 def test_suite():
     return unittest.makeSuite(BuildTestCase)

Modified: python/branches/pep-3151/Lib/distutils/tests/test_build_clib.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_build_clib.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_build_clib.py	Sat Feb 26 08:16:32 2011
@@ -57,14 +57,14 @@
         self.assertRaises(DistutilsSetupError, cmd.get_source_files)
 
         cmd.libraries = [('name', {'sources': ['a', 'b']})]
-        self.assertEquals(cmd.get_source_files(), ['a', 'b'])
+        self.assertEqual(cmd.get_source_files(), ['a', 'b'])
 
         cmd.libraries = [('name', {'sources': ('a', 'b')})]
-        self.assertEquals(cmd.get_source_files(), ['a', 'b'])
+        self.assertEqual(cmd.get_source_files(), ['a', 'b'])
 
         cmd.libraries = [('name', {'sources': ('a', 'b')}),
                          ('name2', {'sources': ['c', 'd']})]
-        self.assertEquals(cmd.get_source_files(), ['a', 'b', 'c', 'd'])
+        self.assertEqual(cmd.get_source_files(), ['a', 'b', 'c', 'd'])
 
     def test_build_libraries(self):
 
@@ -93,11 +93,11 @@
 
         cmd.include_dirs = 'one-dir'
         cmd.finalize_options()
-        self.assertEquals(cmd.include_dirs, ['one-dir'])
+        self.assertEqual(cmd.include_dirs, ['one-dir'])
 
         cmd.include_dirs = None
         cmd.finalize_options()
-        self.assertEquals(cmd.include_dirs, [])
+        self.assertEqual(cmd.include_dirs, [])
 
         cmd.distribution.libraries = 'WONTWORK'
         self.assertRaises(DistutilsSetupError, cmd.finalize_options)

Modified: python/branches/pep-3151/Lib/distutils/tests/test_build_ext.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_build_ext.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_build_ext.py	Sat Feb 26 08:16:32 2011
@@ -96,11 +96,11 @@
         for attr in ('error', 'foo', 'new', 'roj'):
             self.assertTrue(hasattr(xx, attr))
 
-        self.assertEquals(xx.foo(2, 5), 7)
-        self.assertEquals(xx.foo(13,15), 28)
-        self.assertEquals(xx.new().demo(), None)
+        self.assertEqual(xx.foo(2, 5), 7)
+        self.assertEqual(xx.foo(13,15), 28)
+        self.assertEqual(xx.new().demo(), None)
         doc = 'This is a template module just for instruction.'
-        self.assertEquals(xx.__doc__, doc)
+        self.assertEqual(xx.__doc__, doc)
         self.assertTrue(isinstance(xx.Null(), xx.Null))
         self.assertTrue(isinstance(xx.Str(), xx.Str))
 
@@ -206,7 +206,7 @@
         cmd = build_ext(dist)
         cmd.libraries = 'my_lib'
         cmd.finalize_options()
-        self.assertEquals(cmd.libraries, ['my_lib'])
+        self.assertEqual(cmd.libraries, ['my_lib'])
 
         # make sure cmd.library_dirs is turned into a list
         # if it's a string
@@ -220,7 +220,7 @@
         cmd = build_ext(dist)
         cmd.rpath = os.pathsep.join(['one', 'two'])
         cmd.finalize_options()
-        self.assertEquals(cmd.rpath, ['one', 'two'])
+        self.assertEqual(cmd.rpath, ['one', 'two'])
 
         # XXX more tests to perform for win32
 
@@ -229,25 +229,25 @@
         cmd = build_ext(dist)
         cmd.define = 'one,two'
         cmd.finalize_options()
-        self.assertEquals(cmd.define, [('one', '1'), ('two', '1')])
+        self.assertEqual(cmd.define, [('one', '1'), ('two', '1')])
 
         # make sure undef is turned into a list of
         # strings if they are ','-separated strings
         cmd = build_ext(dist)
         cmd.undef = 'one,two'
         cmd.finalize_options()
-        self.assertEquals(cmd.undef, ['one', 'two'])
+        self.assertEqual(cmd.undef, ['one', 'two'])
 
         # make sure swig_opts is turned into a list
         cmd = build_ext(dist)
         cmd.swig_opts = None
         cmd.finalize_options()
-        self.assertEquals(cmd.swig_opts, [])
+        self.assertEqual(cmd.swig_opts, [])
 
         cmd = build_ext(dist)
         cmd.swig_opts = '1 2'
         cmd.finalize_options()
-        self.assertEquals(cmd.swig_opts, ['1', '2'])
+        self.assertEqual(cmd.swig_opts, ['1', '2'])
 
     def test_check_extensions_list(self):
         dist = Distribution()
@@ -284,7 +284,7 @@
         # check_extensions_list adds in ext the values passed
         # when they are in ('include_dirs', 'library_dirs', 'libraries'
         # 'extra_objects', 'extra_compile_args', 'extra_link_args')
-        self.assertEquals(ext.libraries, 'foo')
+        self.assertEqual(ext.libraries, 'foo')
         self.assertTrue(not hasattr(ext, 'some'))
 
         # 'macros' element of build info dict must be 1- or 2-tuple
@@ -294,15 +294,15 @@
 
         exts[0][1]['macros'] = [('1', '2'), ('3',)]
         cmd.check_extensions_list(exts)
-        self.assertEquals(exts[0].undef_macros, ['3'])
-        self.assertEquals(exts[0].define_macros, [('1', '2')])
+        self.assertEqual(exts[0].undef_macros, ['3'])
+        self.assertEqual(exts[0].define_macros, [('1', '2')])
 
     def test_get_source_files(self):
         modules = [Extension('foo', ['xxx'], optional=False)]
         dist = Distribution({'name': 'xx', 'ext_modules': modules})
         cmd = build_ext(dist)
         cmd.ensure_finalized()
-        self.assertEquals(cmd.get_source_files(), ['xxx'])
+        self.assertEqual(cmd.get_source_files(), ['xxx'])
 
     def test_compiler_option(self):
         # cmd.compiler is an option and
@@ -313,7 +313,7 @@
         cmd.compiler = 'unix'
         cmd.ensure_finalized()
         cmd.run()
-        self.assertEquals(cmd.compiler, 'unix')
+        self.assertEqual(cmd.compiler, 'unix')
 
     def test_get_outputs(self):
         tmp_dir = self.mkdtemp()
@@ -325,7 +325,7 @@
         cmd = build_ext(dist)
         self._fixup_command(cmd)
         cmd.ensure_finalized()
-        self.assertEquals(len(cmd.get_outputs()), 1)
+        self.assertEqual(len(cmd.get_outputs()), 1)
 
         if os.name == "nt":
             cmd.debug = sys.executable.endswith("_d.exe")
@@ -348,7 +348,7 @@
         so_ext = sysconfig.get_config_var('SO')
         self.assertTrue(so_file.endswith(so_ext))
         so_dir = os.path.dirname(so_file)
-        self.assertEquals(so_dir, other_tmp_dir)
+        self.assertEqual(so_dir, other_tmp_dir)
 
         cmd.inplace = 0
         cmd.compiler = None
@@ -357,7 +357,7 @@
         self.assertTrue(os.path.exists(so_file))
         self.assertTrue(so_file.endswith(so_ext))
         so_dir = os.path.dirname(so_file)
-        self.assertEquals(so_dir, cmd.build_lib)
+        self.assertEqual(so_dir, cmd.build_lib)
 
         # inplace = 0, cmd.package = 'bar'
         build_py = cmd.get_finalized_command('build_py')
@@ -365,7 +365,7 @@
         path = cmd.get_ext_fullpath('foo')
         # checking that the last directory is the build_dir
         path = os.path.split(path)[0]
-        self.assertEquals(path, cmd.build_lib)
+        self.assertEqual(path, cmd.build_lib)
 
         # inplace = 1, cmd.package = 'bar'
         cmd.inplace = 1
@@ -379,7 +379,7 @@
         # checking that the last directory is bar
         path = os.path.split(path)[0]
         lastdir = os.path.split(path)[-1]
-        self.assertEquals(lastdir, 'bar')
+        self.assertEqual(lastdir, 'bar')
 
     def test_ext_fullpath(self):
         ext = sysconfig.get_config_vars()['SO']
@@ -395,14 +395,14 @@
         curdir = os.getcwd()
         wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
         path = cmd.get_ext_fullpath('lxml.etree')
-        self.assertEquals(wanted, path)
+        self.assertEqual(wanted, path)
 
         # building lxml.etree not inplace
         cmd.inplace = 0
         cmd.build_lib = os.path.join(curdir, 'tmpdir')
         wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext)
         path = cmd.get_ext_fullpath('lxml.etree')
-        self.assertEquals(wanted, path)
+        self.assertEqual(wanted, path)
 
         # building twisted.runner.portmap not inplace
         build_py = cmd.get_finalized_command('build_py')
@@ -411,13 +411,13 @@
         path = cmd.get_ext_fullpath('twisted.runner.portmap')
         wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner',
                               'portmap' + ext)
-        self.assertEquals(wanted, path)
+        self.assertEqual(wanted, path)
 
         # building twisted.runner.portmap inplace
         cmd.inplace = 1
         path = cmd.get_ext_fullpath('twisted.runner.portmap')
         wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
-        self.assertEquals(wanted, path)
+        self.assertEqual(wanted, path)
 
 def test_suite():
     src = _get_source_filename()

Modified: python/branches/pep-3151/Lib/distutils/tests/test_check.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_check.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_check.py	Sat Feb 26 08:16:32 2011
@@ -27,7 +27,7 @@
         # by default, check is checking the metadata
         # should have some warnings
         cmd = self._run()
-        self.assertEquals(cmd._warnings, 2)
+        self.assertEqual(cmd._warnings, 2)
 
         # now let's add the required fields
         # and run it again, to make sure we don't get
@@ -36,7 +36,7 @@
                     'author_email': 'xxx',
                     'name': 'xxx', 'version': 'xxx'}
         cmd = self._run(metadata)
-        self.assertEquals(cmd._warnings, 0)
+        self.assertEqual(cmd._warnings, 0)
 
         # now with the strict mode, we should
         # get an error if there are missing metadata
@@ -44,7 +44,7 @@
 
         # and of course, no error when all metadata are present
         cmd = self._run(metadata, strict=1)
-        self.assertEquals(cmd._warnings, 0)
+        self.assertEqual(cmd._warnings, 0)
 
     def test_check_document(self):
         if not HAS_DOCUTILS: # won't test without docutils
@@ -55,12 +55,12 @@
         # let's see if it detects broken rest
         broken_rest = 'title\n===\n\ntest'
         msgs = cmd._check_rst_data(broken_rest)
-        self.assertEquals(len(msgs), 1)
+        self.assertEqual(len(msgs), 1)
 
         # and non-broken rest
         rest = 'title\n=====\n\ntest'
         msgs = cmd._check_rst_data(rest)
-        self.assertEquals(len(msgs), 0)
+        self.assertEqual(len(msgs), 0)
 
     def test_check_restructuredtext(self):
         if not HAS_DOCUTILS: # won't test without docutils
@@ -70,7 +70,7 @@
         pkg_info, dist = self.create_dist(long_description=broken_rest)
         cmd = check(dist)
         cmd.check_restructuredtext()
-        self.assertEquals(cmd._warnings, 1)
+        self.assertEqual(cmd._warnings, 1)
 
         # let's see if we have an error with strict=1
         metadata = {'url': 'xxx', 'author': 'xxx',
@@ -83,7 +83,7 @@
         # and non-broken rest
         metadata['long_description'] = 'title\n=====\n\ntest'
         cmd = self._run(metadata, strict=1, restructuredtext=1)
-        self.assertEquals(cmd._warnings, 0)
+        self.assertEqual(cmd._warnings, 0)
 
     def test_check_all(self):
 

Modified: python/branches/pep-3151/Lib/distutils/tests/test_cmd.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_cmd.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_cmd.py	Sat Feb 26 08:16:32 2011
@@ -44,7 +44,7 @@
 
         # making sure execute gets called properly
         def _execute(func, args, exec_msg, level):
-            self.assertEquals(exec_msg, 'generating out from in')
+            self.assertEqual(exec_msg, 'generating out from in')
         cmd.force = True
         cmd.execute = _execute
         cmd.make_file(infiles='in', outfile='out', func='func', args=())
@@ -63,7 +63,7 @@
 
         wanted = ["command options for 'MyCmd':", '  option1 = 1',
                   '  option2 = 1']
-        self.assertEquals(msgs, wanted)
+        self.assertEqual(msgs, wanted)
 
     def test_ensure_string(self):
         cmd = self.cmd
@@ -81,7 +81,7 @@
         cmd = self.cmd
         cmd.option1 = 'ok,dok'
         cmd.ensure_string_list('option1')
-        self.assertEquals(cmd.option1, ['ok', 'dok'])
+        self.assertEqual(cmd.option1, ['ok', 'dok'])
 
         cmd.option2 = ['xxx', 'www']
         cmd.ensure_string_list('option2')
@@ -109,14 +109,14 @@
         with captured_stdout() as stdout:
             cmd.debug_print('xxx')
         stdout.seek(0)
-        self.assertEquals(stdout.read(), '')
+        self.assertEqual(stdout.read(), '')
 
         debug.DEBUG = True
         try:
             with captured_stdout() as stdout:
                 cmd.debug_print('xxx')
             stdout.seek(0)
-            self.assertEquals(stdout.read(), 'xxx\n')
+            self.assertEqual(stdout.read(), 'xxx\n')
         finally:
             debug.DEBUG = False
 

Modified: python/branches/pep-3151/Lib/distutils/tests/test_config.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_config.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_config.py	Sat Feb 26 08:16:32 2011
@@ -89,7 +89,7 @@
         waited = [('password', 'secret'), ('realm', 'pypi'),
                   ('repository', 'http://pypi.python.org/pypi'),
                   ('server', 'server1'), ('username', 'me')]
-        self.assertEquals(config, waited)
+        self.assertEqual(config, waited)
 
         # old format
         self.write_file(self.rc, PYPIRC_OLD)
@@ -98,7 +98,7 @@
         waited = [('password', 'secret'), ('realm', 'pypi'),
                   ('repository', 'http://pypi.python.org/pypi'),
                   ('server', 'server-login'), ('username', 'tarek')]
-        self.assertEquals(config, waited)
+        self.assertEqual(config, waited)
 
     def test_server_empty_registration(self):
         cmd = self._cmd(self.dist)
@@ -109,7 +109,7 @@
         f = open(rc)
         try:
             content = f.read()
-            self.assertEquals(content, WANTED)
+            self.assertEqual(content, WANTED)
         finally:
             f.close()
 

Modified: python/branches/pep-3151/Lib/distutils/tests/test_config_cmd.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_config_cmd.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_config_cmd.py	Sat Feb 26 08:16:32 2011
@@ -35,7 +35,7 @@
             f.close()
 
         dump_file(this_file, 'I am the header')
-        self.assertEquals(len(self._logs), numlines+1)
+        self.assertEqual(len(self._logs), numlines+1)
 
     def test_search_cpp(self):
         if sys.platform == 'win32':
@@ -45,10 +45,10 @@
 
         # simple pattern searches
         match = cmd.search_cpp(pattern='xxx', body='// xxx')
-        self.assertEquals(match, 0)
+        self.assertEqual(match, 0)
 
         match = cmd.search_cpp(pattern='_configtest', body='// xxx')
-        self.assertEquals(match, 1)
+        self.assertEqual(match, 1)
 
     def test_finalize_options(self):
         # finalize_options does a bit of transformation
@@ -60,9 +60,9 @@
         cmd.library_dirs = 'three%sfour' % os.pathsep
         cmd.ensure_finalized()
 
-        self.assertEquals(cmd.include_dirs, ['one', 'two'])
-        self.assertEquals(cmd.libraries, ['one'])
-        self.assertEquals(cmd.library_dirs, ['three', 'four'])
+        self.assertEqual(cmd.include_dirs, ['one', 'two'])
+        self.assertEqual(cmd.libraries, ['one'])
+        self.assertEqual(cmd.library_dirs, ['three', 'four'])
 
     def test_clean(self):
         # _clean removes files

Modified: python/branches/pep-3151/Lib/distutils/tests/test_core.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_core.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_core.py	Sat Feb 26 08:16:32 2011
@@ -89,7 +89,7 @@
         with captured_stdout() as stdout:
             distutils.core.setup(name='bar')
         stdout.seek(0)
-        self.assertEquals(stdout.read(), 'bar\n')
+        self.assertEqual(stdout.read(), 'bar\n')
 
         distutils.core.DEBUG = True
         try:
@@ -99,7 +99,7 @@
             distutils.core.DEBUG = False
         stdout.seek(0)
         wanted = "options (after parsing config files):\n"
-        self.assertEquals(stdout.readlines()[0], wanted)
+        self.assertEqual(stdout.readlines()[0], wanted)
 
 def test_suite():
     return unittest.makeSuite(CoreTestCase)

Modified: python/branches/pep-3151/Lib/distutils/tests/test_cygwinccompiler.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_cygwinccompiler.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_cygwinccompiler.py	Sat Feb 26 08:16:32 2011
@@ -66,82 +66,82 @@
         sys.version = ('2.6.1 (r261:67515, Dec  6 2008, 16:42:21) \n[GCC '
                        '4.0.1 (Apple Computer, Inc. build 5370)]')
 
-        self.assertEquals(check_config_h()[0], CONFIG_H_OK)
+        self.assertEqual(check_config_h()[0], CONFIG_H_OK)
 
         # then it tries to see if it can find "__GNUC__" in pyconfig.h
         sys.version = 'something without the *CC word'
 
         # if the file doesn't exist it returns  CONFIG_H_UNCERTAIN
-        self.assertEquals(check_config_h()[0], CONFIG_H_UNCERTAIN)
+        self.assertEqual(check_config_h()[0], CONFIG_H_UNCERTAIN)
 
         # if it exists but does not contain __GNUC__, it returns CONFIG_H_NOTOK
         self.write_file(self.python_h, 'xxx')
-        self.assertEquals(check_config_h()[0], CONFIG_H_NOTOK)
+        self.assertEqual(check_config_h()[0], CONFIG_H_NOTOK)
 
         # and CONFIG_H_OK if __GNUC__ is found
         self.write_file(self.python_h, 'xxx __GNUC__ xxx')
-        self.assertEquals(check_config_h()[0], CONFIG_H_OK)
+        self.assertEqual(check_config_h()[0], CONFIG_H_OK)
 
     def test_get_versions(self):
 
         # get_versions calls distutils.spawn.find_executable on
         # 'gcc', 'ld' and 'dllwrap'
-        self.assertEquals(get_versions(), (None, None, None))
+        self.assertEqual(get_versions(), (None, None, None))
 
         # Let's fake we have 'gcc' and it returns '3.4.5'
         self._exes['gcc'] = b'gcc (GCC) 3.4.5 (mingw special)\nFSF'
         res = get_versions()
-        self.assertEquals(str(res[0]), '3.4.5')
+        self.assertEqual(str(res[0]), '3.4.5')
 
         # and let's see what happens when the version
         # doesn't match the regular expression
         # (\d+\.\d+(\.\d+)*)
         self._exes['gcc'] = b'very strange output'
         res = get_versions()
-        self.assertEquals(res[0], None)
+        self.assertEqual(res[0], None)
 
         # same thing for ld
         self._exes['ld'] = b'GNU ld version 2.17.50 20060824'
         res = get_versions()
-        self.assertEquals(str(res[1]), '2.17.50')
+        self.assertEqual(str(res[1]), '2.17.50')
         self._exes['ld'] = b'@(#)PROGRAM:ld  PROJECT:ld64-77'
         res = get_versions()
-        self.assertEquals(res[1], None)
+        self.assertEqual(res[1], None)
 
         # and dllwrap
         self._exes['dllwrap'] = b'GNU dllwrap 2.17.50 20060824\nFSF'
         res = get_versions()
-        self.assertEquals(str(res[2]), '2.17.50')
+        self.assertEqual(str(res[2]), '2.17.50')
         self._exes['dllwrap'] = b'Cheese Wrap'
         res = get_versions()
-        self.assertEquals(res[2], None)
+        self.assertEqual(res[2], None)
 
     def test_get_msvcr(self):
 
         # none
         sys.version  = ('2.6.1 (r261:67515, Dec  6 2008, 16:42:21) '
                         '\n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]')
-        self.assertEquals(get_msvcr(), None)
+        self.assertEqual(get_msvcr(), None)
 
         # MSVC 7.0
         sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
                        '[MSC v.1300 32 bits (Intel)]')
-        self.assertEquals(get_msvcr(), ['msvcr70'])
+        self.assertEqual(get_msvcr(), ['msvcr70'])
 
         # MSVC 7.1
         sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
                        '[MSC v.1310 32 bits (Intel)]')
-        self.assertEquals(get_msvcr(), ['msvcr71'])
+        self.assertEqual(get_msvcr(), ['msvcr71'])
 
         # VS2005 / MSVC 8.0
         sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
                        '[MSC v.1400 32 bits (Intel)]')
-        self.assertEquals(get_msvcr(), ['msvcr80'])
+        self.assertEqual(get_msvcr(), ['msvcr80'])
 
         # VS2008 / MSVC 9.0
         sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
                        '[MSC v.1500 32 bits (Intel)]')
-        self.assertEquals(get_msvcr(), ['msvcr90'])
+        self.assertEqual(get_msvcr(), ['msvcr90'])
 
         # unknown
         sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '

Modified: python/branches/pep-3151/Lib/distutils/tests/test_dep_util.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_dep_util.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_dep_util.py	Sat Feb 26 08:16:32 2011
@@ -43,8 +43,8 @@
         self.write_file(two)
         self.write_file(four)
 
-        self.assertEquals(newer_pairwise([one, two], [three, four]),
-                          ([one],[three]))
+        self.assertEqual(newer_pairwise([one, two], [three, four]),
+                         ([one],[three]))
 
     def test_newer_group(self):
         tmpdir = self.mkdtemp()

Modified: python/branches/pep-3151/Lib/distutils/tests/test_dir_util.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_dir_util.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_dir_util.py	Sat Feb 26 08:16:32 2011
@@ -38,18 +38,18 @@
 
         mkpath(self.target, verbose=0)
         wanted = []
-        self.assertEquals(self._logs, wanted)
+        self.assertEqual(self._logs, wanted)
         remove_tree(self.root_target, verbose=0)
 
         mkpath(self.target, verbose=1)
         wanted = ['creating %s' % self.root_target,
                   'creating %s' % self.target]
-        self.assertEquals(self._logs, wanted)
+        self.assertEqual(self._logs, wanted)
         self._logs = []
 
         remove_tree(self.root_target, verbose=1)
         wanted = ["removing '%s' (and everything under it)" % self.root_target]
-        self.assertEquals(self._logs, wanted)
+        self.assertEqual(self._logs, wanted)
 
     @unittest.skipIf(sys.platform.startswith('win'),
                         "This test is only appropriate for POSIX-like systems.")
@@ -67,12 +67,12 @@
     def test_create_tree_verbosity(self):
 
         create_tree(self.root_target, ['one', 'two', 'three'], verbose=0)
-        self.assertEquals(self._logs, [])
+        self.assertEqual(self._logs, [])
         remove_tree(self.root_target, verbose=0)
 
         wanted = ['creating %s' % self.root_target]
         create_tree(self.root_target, ['one', 'two', 'three'], verbose=1)
-        self.assertEquals(self._logs, wanted)
+        self.assertEqual(self._logs, wanted)
 
         remove_tree(self.root_target, verbose=0)
 
@@ -82,7 +82,7 @@
         mkpath(self.target, verbose=0)
 
         copy_tree(self.target, self.target2, verbose=0)
-        self.assertEquals(self._logs, [])
+        self.assertEqual(self._logs, [])
 
         remove_tree(self.root_target, verbose=0)
 
@@ -96,18 +96,18 @@
 
         wanted = ['copying %s -> %s' % (a_file, self.target2)]
         copy_tree(self.target, self.target2, verbose=1)
-        self.assertEquals(self._logs, wanted)
+        self.assertEqual(self._logs, wanted)
 
         remove_tree(self.root_target, verbose=0)
         remove_tree(self.target2, verbose=0)
 
     def test_ensure_relative(self):
         if os.sep == '/':
-            self.assertEquals(ensure_relative('/home/foo'), 'home/foo')
-            self.assertEquals(ensure_relative('some/path'), 'some/path')
+            self.assertEqual(ensure_relative('/home/foo'), 'home/foo')
+            self.assertEqual(ensure_relative('some/path'), 'some/path')
         else:   # \\
-            self.assertEquals(ensure_relative('c:\\home\\foo'), 'c:home\\foo')
-            self.assertEquals(ensure_relative('home\\foo'), 'home\\foo')
+            self.assertEqual(ensure_relative('c:\\home\\foo'), 'c:home\\foo')
+            self.assertEqual(ensure_relative('home\\foo'), 'home\\foo')
 
 def test_suite():
     return unittest.makeSuite(DirUtilTestCase)

Modified: python/branches/pep-3151/Lib/distutils/tests/test_dist.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_dist.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_dist.py	Sat Feb 26 08:16:32 2011
@@ -124,7 +124,7 @@
         finally:
             warnings.warn = old_warn
 
-        self.assertEquals(len(warns), 0)
+        self.assertEqual(len(warns), 0)
 
     def test_finalize_options(self):
 
@@ -135,20 +135,20 @@
         dist.finalize_options()
 
         # finalize_option splits platforms and keywords
-        self.assertEquals(dist.metadata.platforms, ['one', 'two'])
-        self.assertEquals(dist.metadata.keywords, ['one', 'two'])
+        self.assertEqual(dist.metadata.platforms, ['one', 'two'])
+        self.assertEqual(dist.metadata.keywords, ['one', 'two'])
 
     def test_get_command_packages(self):
         dist = Distribution()
-        self.assertEquals(dist.command_packages, None)
+        self.assertEqual(dist.command_packages, None)
         cmds = dist.get_command_packages()
-        self.assertEquals(cmds, ['distutils.command'])
-        self.assertEquals(dist.command_packages,
-                          ['distutils.command'])
+        self.assertEqual(cmds, ['distutils.command'])
+        self.assertEqual(dist.command_packages,
+                         ['distutils.command'])
 
         dist.command_packages = 'one,two'
         cmds = dist.get_command_packages()
-        self.assertEquals(cmds, ['distutils.command', 'one', 'two'])
+        self.assertEqual(cmds, ['distutils.command', 'one', 'two'])
 
 
     def test_announce(self):
@@ -287,8 +287,8 @@
     def test_fix_help_options(self):
         help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
         fancy_options = fix_help_options(help_tuples)
-        self.assertEquals(fancy_options[0], ('a', 'b', 'c'))
-        self.assertEquals(fancy_options[1], (1, 2, 3))
+        self.assertEqual(fancy_options[0], ('a', 'b', 'c'))
+        self.assertEqual(fancy_options[1], (1, 2, 3))
 
     def test_show_help(self):
         # smoke test, just makes sure some help is displayed

Modified: python/branches/pep-3151/Lib/distutils/tests/test_extension.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_extension.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_extension.py	Sat Feb 26 08:16:32 2011
@@ -28,38 +28,38 @@
                   'rect', 'rwobject', 'scrap', 'surface', 'surflock',
                   'time', 'transform']
 
-        self.assertEquals(names, wanted)
+        self.assertEqual(names, wanted)
 
     def test_extension_init(self):
         # the first argument, which is the name, must be a string
         self.assertRaises(AssertionError, Extension, 1, [])
         ext = Extension('name', [])
-        self.assertEquals(ext.name, 'name')
+        self.assertEqual(ext.name, 'name')
 
         # the second argument, which is the list of files, must
         # be a list of strings
         self.assertRaises(AssertionError, Extension, 'name', 'file')
         self.assertRaises(AssertionError, Extension, 'name', ['file', 1])
         ext = Extension('name', ['file1', 'file2'])
-        self.assertEquals(ext.sources, ['file1', 'file2'])
+        self.assertEqual(ext.sources, ['file1', 'file2'])
 
         # others arguments have defaults
         for attr in ('include_dirs', 'define_macros', 'undef_macros',
                      'library_dirs', 'libraries', 'runtime_library_dirs',
                      'extra_objects', 'extra_compile_args', 'extra_link_args',
                      'export_symbols', 'swig_opts', 'depends'):
-            self.assertEquals(getattr(ext, attr), [])
+            self.assertEqual(getattr(ext, attr), [])
 
-        self.assertEquals(ext.language, None)
-        self.assertEquals(ext.optional, None)
+        self.assertEqual(ext.language, None)
+        self.assertEqual(ext.optional, None)
 
         # if there are unknown keyword options, warn about them
         with check_warnings() as w:
             warnings.simplefilter('always')
             ext = Extension('name', ['file1', 'file2'], chic=True)
 
-        self.assertEquals(len(w.warnings), 1)
-        self.assertEquals(str(w.warnings[0].message),
+        self.assertEqual(len(w.warnings), 1)
+        self.assertEqual(str(w.warnings[0].message),
                           "Unknown Extension options: 'chic'")
 
 def test_suite():

Modified: python/branches/pep-3151/Lib/distutils/tests/test_file_util.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_file_util.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_file_util.py	Sat Feb 26 08:16:32 2011
@@ -39,14 +39,14 @@
 
         move_file(self.source, self.target, verbose=0)
         wanted = []
-        self.assertEquals(self._logs, wanted)
+        self.assertEqual(self._logs, wanted)
 
         # back to original state
         move_file(self.target, self.source, verbose=0)
 
         move_file(self.source, self.target, verbose=1)
         wanted = ['moving %s -> %s' % (self.source, self.target)]
-        self.assertEquals(self._logs, wanted)
+        self.assertEqual(self._logs, wanted)
 
         # back to original state
         move_file(self.target, self.source, verbose=0)
@@ -56,7 +56,7 @@
         os.mkdir(self.target_dir)
         move_file(self.source, self.target_dir, verbose=1)
         wanted = ['moving %s -> %s' % (self.source, self.target_dir)]
-        self.assertEquals(self._logs, wanted)
+        self.assertEqual(self._logs, wanted)
 
 
 def test_suite():

Modified: python/branches/pep-3151/Lib/distutils/tests/test_filelist.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_filelist.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_filelist.py	Sat Feb 26 08:16:32 2011
@@ -9,29 +9,29 @@
 
     def test_glob_to_re(self):
         # simple cases
-        self.assertEquals(glob_to_re('foo*'), 'foo[^/]*\\Z(?ms)')
-        self.assertEquals(glob_to_re('foo?'), 'foo[^/]\\Z(?ms)')
-        self.assertEquals(glob_to_re('foo??'), 'foo[^/][^/]\\Z(?ms)')
+        self.assertEqual(glob_to_re('foo*'), 'foo[^/]*\\Z(?ms)')
+        self.assertEqual(glob_to_re('foo?'), 'foo[^/]\\Z(?ms)')
+        self.assertEqual(glob_to_re('foo??'), 'foo[^/][^/]\\Z(?ms)')
 
         # special cases
-        self.assertEquals(glob_to_re(r'foo\\*'), r'foo\\\\[^/]*\Z(?ms)')
-        self.assertEquals(glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*\Z(?ms)')
-        self.assertEquals(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)')
-        self.assertEquals(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)')
+        self.assertEqual(glob_to_re(r'foo\\*'), r'foo\\\\[^/]*\Z(?ms)')
+        self.assertEqual(glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*\Z(?ms)')
+        self.assertEqual(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)')
+        self.assertEqual(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)')
 
     def test_debug_print(self):
         file_list = FileList()
         with captured_stdout() as stdout:
             file_list.debug_print('xxx')
         stdout.seek(0)
-        self.assertEquals(stdout.read(), '')
+        self.assertEqual(stdout.read(), '')
 
         debug.DEBUG = True
         try:
             with captured_stdout() as stdout:
                 file_list.debug_print('xxx')
             stdout.seek(0)
-            self.assertEquals(stdout.read(), 'xxx\n')
+            self.assertEqual(stdout.read(), 'xxx\n')
         finally:
             debug.DEBUG = False
 

Modified: python/branches/pep-3151/Lib/distutils/tests/test_install.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_install.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_install.py	Sat Feb 26 08:16:32 2011
@@ -123,23 +123,23 @@
 
         # two elements
         cmd.handle_extra_path()
-        self.assertEquals(cmd.extra_path, ['path', 'dirs'])
-        self.assertEquals(cmd.extra_dirs, 'dirs')
-        self.assertEquals(cmd.path_file, 'path')
+        self.assertEqual(cmd.extra_path, ['path', 'dirs'])
+        self.assertEqual(cmd.extra_dirs, 'dirs')
+        self.assertEqual(cmd.path_file, 'path')
 
         # one element
         cmd.extra_path = ['path']
         cmd.handle_extra_path()
-        self.assertEquals(cmd.extra_path, ['path'])
-        self.assertEquals(cmd.extra_dirs, 'path')
-        self.assertEquals(cmd.path_file, 'path')
+        self.assertEqual(cmd.extra_path, ['path'])
+        self.assertEqual(cmd.extra_dirs, 'path')
+        self.assertEqual(cmd.path_file, 'path')
 
         # none
         dist.extra_path = cmd.extra_path = None
         cmd.handle_extra_path()
-        self.assertEquals(cmd.extra_path, None)
-        self.assertEquals(cmd.extra_dirs, '')
-        self.assertEquals(cmd.path_file, None)
+        self.assertEqual(cmd.extra_path, None)
+        self.assertEqual(cmd.extra_dirs, '')
+        self.assertEqual(cmd.path_file, None)
 
         # three elements (no way !)
         cmd.extra_path = 'path,dirs,again'
@@ -184,7 +184,7 @@
         # line (the egg info file)
         f = open(cmd.record)
         try:
-            self.assertEquals(len(f.readlines()), 1)
+            self.assertEqual(len(f.readlines()), 1)
         finally:
             f.close()
 

Modified: python/branches/pep-3151/Lib/distutils/tests/test_install_data.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_install_data.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_install_data.py	Sat Feb 26 08:16:32 2011
@@ -28,14 +28,14 @@
         self.write_file(two, 'xxx')
 
         cmd.data_files = [one, (inst2, [two])]
-        self.assertEquals(cmd.get_inputs(), [one, (inst2, [two])])
+        self.assertEqual(cmd.get_inputs(), [one, (inst2, [two])])
 
         # let's run the command
         cmd.ensure_finalized()
         cmd.run()
 
         # let's check the result
-        self.assertEquals(len(cmd.get_outputs()), 2)
+        self.assertEqual(len(cmd.get_outputs()), 2)
         rtwo = os.path.split(two)[-1]
         self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
         rone = os.path.split(one)[-1]
@@ -48,7 +48,7 @@
         cmd.run()
 
         # let's check the result
-        self.assertEquals(len(cmd.get_outputs()), 2)
+        self.assertEqual(len(cmd.get_outputs()), 2)
         self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
         self.assertTrue(os.path.exists(os.path.join(inst, rone)))
         cmd.outfiles = []
@@ -66,7 +66,7 @@
         cmd.run()
 
         # let's check the result
-        self.assertEquals(len(cmd.get_outputs()), 4)
+        self.assertEqual(len(cmd.get_outputs()), 4)
         self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
         self.assertTrue(os.path.exists(os.path.join(inst, rone)))
 

Modified: python/branches/pep-3151/Lib/distutils/tests/test_install_headers.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_install_headers.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_install_headers.py	Sat Feb 26 08:16:32 2011
@@ -24,7 +24,7 @@
 
         pkg_dir, dist = self.create_dist(headers=headers)
         cmd = install_headers(dist)
-        self.assertEquals(cmd.get_inputs(), headers)
+        self.assertEqual(cmd.get_inputs(), headers)
 
         # let's run the command
         cmd.install_dir = os.path.join(pkg_dir, 'inst')
@@ -32,7 +32,7 @@
         cmd.run()
 
         # let's check the results
-        self.assertEquals(len(cmd.get_outputs()), 2)
+        self.assertEqual(len(cmd.get_outputs()), 2)
 
 def test_suite():
     return unittest.makeSuite(InstallHeadersTestCase)

Modified: python/branches/pep-3151/Lib/distutils/tests/test_install_lib.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_install_lib.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_install_lib.py	Sat Feb 26 08:16:32 2011
@@ -19,8 +19,8 @@
         cmd = install_lib(dist)
 
         cmd.finalize_options()
-        self.assertEquals(cmd.compile, 1)
-        self.assertEquals(cmd.optimize, 0)
+        self.assertEqual(cmd.compile, 1)
+        self.assertEqual(cmd.optimize, 0)
 
         # optimize must be 0, 1, or 2
         cmd.optimize = 'foo'
@@ -30,7 +30,7 @@
 
         cmd.optimize = '2'
         cmd.finalize_options()
-        self.assertEquals(cmd.optimize, 2)
+        self.assertEqual(cmd.optimize, 2)
 
     @unittest.skipUnless(not sys.dont_write_bytecode,
                          'byte-compile not supported')
@@ -77,7 +77,7 @@
         cmd.distribution.script_name = 'setup.py'
 
         # get_input should return 2 elements
-        self.assertEquals(len(cmd.get_inputs()), 2)
+        self.assertEqual(len(cmd.get_inputs()), 2)
 
     def test_dont_write_bytecode(self):
         # makes sure byte_compile is not used

Modified: python/branches/pep-3151/Lib/distutils/tests/test_log.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_log.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_log.py	Sat Feb 26 08:16:32 2011
@@ -23,9 +23,9 @@
                 log.debug("debug:\xe9")
                 log.fatal("fatal:\xe9")
                 stdout.seek(0)
-                self.assertEquals(stdout.read().rstrip(), "debug:\\xe9")
+                self.assertEqual(stdout.read().rstrip(), "debug:\\xe9")
                 stderr.seek(0)
-                self.assertEquals(stderr.read().rstrip(), "fatal:\\xe9")
+                self.assertEqual(stderr.read().rstrip(), "fatal:\\xe9")
         finally:
             sys.stdout = old_stdout
             sys.stderr = old_stderr

Modified: python/branches/pep-3151/Lib/distutils/tests/test_msvc9compiler.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_msvc9compiler.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_msvc9compiler.py	Sat Feb 26 08:16:32 2011
@@ -104,7 +104,7 @@
         import winreg
         HKCU = winreg.HKEY_CURRENT_USER
         keys = Reg.read_keys(HKCU, 'xxxx')
-        self.assertEquals(keys, None)
+        self.assertEqual(keys, None)
 
         keys = Reg.read_keys(HKCU, r'Control Panel')
         self.assertTrue('Desktop' in keys)
@@ -131,7 +131,7 @@
             f.close()
 
         # makes sure the manifest was properly cleaned
-        self.assertEquals(content, _CLEANED_MANIFEST)
+        self.assertEqual(content, _CLEANED_MANIFEST)
 
 
 def test_suite():

Modified: python/branches/pep-3151/Lib/distutils/tests/test_register.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_register.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_register.py	Sat Feb 26 08:16:32 2011
@@ -121,7 +121,7 @@
         f = open(self.rc)
         try:
             content = f.read()
-            self.assertEquals(content, WANTED_PYPIRC)
+            self.assertEqual(content, WANTED_PYPIRC)
         finally:
             f.close()
 
@@ -141,8 +141,8 @@
         req1 = dict(self.conn.reqs[0].headers)
         req2 = dict(self.conn.reqs[1].headers)
 
-        self.assertEquals(req1['Content-length'], '1374')
-        self.assertEquals(req2['Content-length'], '1374')
+        self.assertEqual(req1['Content-length'], '1374')
+        self.assertEqual(req2['Content-length'], '1374')
         self.assertTrue((b'xxx') in self.conn.reqs[1].data)
 
     def test_password_not_in_file(self):
@@ -155,7 +155,7 @@
 
         # dist.password should be set
         # therefore used afterwards by other commands
-        self.assertEquals(cmd.distribution.password, 'password')
+        self.assertEqual(cmd.distribution.password, 'password')
 
     def test_registering(self):
         # this test runs choice 2
@@ -172,7 +172,7 @@
         self.assertTrue(self.conn.reqs, 1)
         req = self.conn.reqs[0]
         headers = dict(req.headers)
-        self.assertEquals(headers['Content-length'], '608')
+        self.assertEqual(headers['Content-length'], '608')
         self.assertTrue((b'tarek') in req.data)
 
     def test_password_reset(self):
@@ -190,7 +190,7 @@
         self.assertTrue(self.conn.reqs, 1)
         req = self.conn.reqs[0]
         headers = dict(req.headers)
-        self.assertEquals(headers['Content-length'], '290')
+        self.assertEqual(headers['Content-length'], '290')
         self.assertTrue((b'tarek') in req.data)
 
     def test_strict(self):
@@ -253,7 +253,7 @@
         with check_warnings() as w:
             warnings.simplefilter("always")
             cmd.check_metadata()
-            self.assertEquals(len(w.warnings), 1)
+            self.assertEqual(len(w.warnings), 1)
 
 def test_suite():
     return unittest.makeSuite(RegisterTestCase)

Modified: python/branches/pep-3151/Lib/distutils/tests/test_sdist.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_sdist.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_sdist.py	Sat Feb 26 08:16:32 2011
@@ -108,7 +108,7 @@
         # now let's check what we have
         dist_folder = join(self.tmp_dir, 'dist')
         files = os.listdir(dist_folder)
-        self.assertEquals(files, ['fake-1.0.zip'])
+        self.assertEqual(files, ['fake-1.0.zip'])
 
         zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
         try:
@@ -117,7 +117,7 @@
             zip_file.close()
 
         # making sure everything has been pruned correctly
-        self.assertEquals(len(content), 4)
+        self.assertEqual(len(content), 4)
 
     def test_make_distribution(self):
 
@@ -138,8 +138,7 @@
         dist_folder = join(self.tmp_dir, 'dist')
         result = os.listdir(dist_folder)
         result.sort()
-        self.assertEquals(result,
-                          ['fake-1.0.tar', 'fake-1.0.tar.gz'] )
+        self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'] )
 
         os.remove(join(dist_folder, 'fake-1.0.tar'))
         os.remove(join(dist_folder, 'fake-1.0.tar.gz'))
@@ -152,8 +151,7 @@
 
         result = os.listdir(dist_folder)
         result.sort()
-        self.assertEquals(result,
-                ['fake-1.0.tar', 'fake-1.0.tar.gz'])
+        self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])
 
     def test_add_defaults(self):
 
@@ -201,7 +199,7 @@
         # now let's check what we have
         dist_folder = join(self.tmp_dir, 'dist')
         files = os.listdir(dist_folder)
-        self.assertEquals(files, ['fake-1.0.zip'])
+        self.assertEqual(files, ['fake-1.0.zip'])
 
         zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
         try:
@@ -210,13 +208,13 @@
             zip_file.close()
 
         # making sure everything was added
-        self.assertEquals(len(content), 11)
+        self.assertEqual(len(content), 11)
 
         # checking the MANIFEST
         f = open(join(self.tmp_dir, 'MANIFEST'))
         try:
             manifest = f.read()
-            self.assertEquals(manifest, MANIFEST % {'sep': os.sep})
+            self.assertEqual(manifest, MANIFEST % {'sep': os.sep})
         finally:
             f.close()
 
@@ -229,7 +227,7 @@
         cmd.ensure_finalized()
         cmd.run()
         warnings = self.get_logs(WARN)
-        self.assertEquals(len(warnings), 2)
+        self.assertEqual(len(warnings), 2)
 
         # trying with a complete set of metadata
         self.clear_logs()
@@ -238,7 +236,7 @@
         cmd.metadata_check = 0
         cmd.run()
         warnings = self.get_logs(WARN)
-        self.assertEquals(len(warnings), 0)
+        self.assertEqual(len(warnings), 0)
 
     def test_check_metadata_deprecated(self):
         # makes sure make_metadata is deprecated
@@ -246,7 +244,7 @@
         with check_warnings() as w:
             warnings.simplefilter("always")
             cmd.check_metadata()
-            self.assertEquals(len(w.warnings), 1)
+            self.assertEqual(len(w.warnings), 1)
 
     def test_show_formats(self):
         with captured_stdout() as stdout:
@@ -256,7 +254,7 @@
         num_formats = len(ARCHIVE_FORMATS.keys())
         output = [line for line in stdout.getvalue().split('\n')
                   if line.strip().startswith('--formats=')]
-        self.assertEquals(len(output), num_formats)
+        self.assertEqual(len(output), num_formats)
 
     def test_finalize_options(self):
 
@@ -264,9 +262,9 @@
         cmd.finalize_options()
 
         # default options set by finalize
-        self.assertEquals(cmd.manifest, 'MANIFEST')
-        self.assertEquals(cmd.template, 'MANIFEST.in')
-        self.assertEquals(cmd.dist_dir, 'dist')
+        self.assertEqual(cmd.manifest, 'MANIFEST')
+        self.assertEqual(cmd.template, 'MANIFEST.in')
+        self.assertEqual(cmd.dist_dir, 'dist')
 
         # formats has to be a string splitable on (' ', ',') or
         # a stringlist
@@ -297,7 +295,7 @@
         finally:
             f.close()
 
-        self.assertEquals(len(manifest), 5)
+        self.assertEqual(len(manifest), 5)
 
         # adding a file
         self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#')
@@ -317,7 +315,7 @@
             f.close()
 
         # do we have the new file in MANIFEST ?
-        self.assertEquals(len(manifest2), 6)
+        self.assertEqual(len(manifest2), 6)
         self.assertIn('doc2.txt', manifest2[-1])
 
     def test_manifest_marker(self):

Modified: python/branches/pep-3151/Lib/distutils/tests/test_spawn.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_spawn.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_spawn.py	Sat Feb 26 08:16:32 2011
@@ -20,7 +20,7 @@
                                (['nochange', 'nospace'],
                                 ['nochange', 'nospace'])):
             res = _nt_quote_args(args)
-            self.assertEquals(res, wanted)
+            self.assertEqual(res, wanted)
 
 
     @unittest.skipUnless(os.name in ('nt', 'posix'),

Modified: python/branches/pep-3151/Lib/distutils/tests/test_sysconfig.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_sysconfig.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_sysconfig.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,6 @@
 """Tests for distutils.sysconfig."""
 import os
+import shutil
 import test
 import unittest
 
@@ -70,7 +71,7 @@
 
         comp = compiler()
         sysconfig.customize_compiler(comp)
-        self.assertEquals(comp.exes['archiver'], 'my_ar -arflags')
+        self.assertEqual(comp.exes['archiver'], 'my_ar -arflags')
 
     def test_parse_makefile_base(self):
         self.makefile = TESTFN
@@ -81,8 +82,8 @@
         finally:
             fd.close()
         d = sysconfig.parse_makefile(self.makefile)
-        self.assertEquals(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'",
-                              'OTHER': 'foo'})
+        self.assertEqual(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'",
+                             'OTHER': 'foo'})
 
     def test_parse_makefile_literal_dollar(self):
         self.makefile = TESTFN
@@ -93,16 +94,16 @@
         finally:
             fd.close()
         d = sysconfig.parse_makefile(self.makefile)
-        self.assertEquals(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'",
-                              'OTHER': 'foo'})
+        self.assertEqual(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'",
+                             'OTHER': 'foo'})
 
 
     def test_sysconfig_module(self):
         import sysconfig as global_sysconfig
-        self.assertEquals(global_sysconfig.get_config_var('CFLAGS'), sysconfig.get_config_var('CFLAGS'))
-        self.assertEquals(global_sysconfig.get_config_var('LDFLAGS'), sysconfig.get_config_var('LDFLAGS'))
-        self.assertEquals(global_sysconfig.get_config_var('LDSHARED'),sysconfig.get_config_var('LDSHARED'))
-        self.assertEquals(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC'))
+        self.assertEqual(global_sysconfig.get_config_var('CFLAGS'), sysconfig.get_config_var('CFLAGS'))
+        self.assertEqual(global_sysconfig.get_config_var('LDFLAGS'), sysconfig.get_config_var('LDFLAGS'))
+        self.assertEqual(global_sysconfig.get_config_var('LDSHARED'),sysconfig.get_config_var('LDSHARED'))
+        self.assertEqual(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC'))
 
 
 

Modified: python/branches/pep-3151/Lib/distutils/tests/test_text_file.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_text_file.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_text_file.py	Sat Feb 26 08:16:32 2011
@@ -49,7 +49,7 @@
 
         def test_input(count, description, file, expected_result):
             result = file.readlines()
-            self.assertEquals(result, expected_result)
+            self.assertEqual(result, expected_result)
 
         tmpdir = self.mkdtemp()
         filename = os.path.join(tmpdir, "test.txt")

Modified: python/branches/pep-3151/Lib/distutils/tests/test_upload.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_upload.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_upload.py	Sat Feb 26 08:16:32 2011
@@ -89,7 +89,7 @@
         for attr, waited in (('username', 'me'), ('password', 'secret'),
                              ('realm', 'pypi'),
                              ('repository', 'http://pypi.python.org/pypi')):
-            self.assertEquals(getattr(cmd, attr), waited)
+            self.assertEqual(getattr(cmd, attr), waited)
 
     def test_saved_password(self):
         # file with no password
@@ -99,14 +99,14 @@
         dist = Distribution()
         cmd = upload(dist)
         cmd.finalize_options()
-        self.assertEquals(cmd.password, None)
+        self.assertEqual(cmd.password, None)
 
         # make sure we get it as well, if another command
         # initialized it at the dist level
         dist.password = 'xxx'
         cmd = upload(dist)
         cmd.finalize_options()
-        self.assertEquals(cmd.password, 'xxx')
+        self.assertEqual(cmd.password, 'xxx')
 
     def test_upload(self):
         tmp = self.mkdtemp()
@@ -124,12 +124,12 @@
 
         # what did we send ?
         headers = dict(self.conn.headers)
-        self.assertEquals(headers['Content-length'], '2087')
+        self.assertEqual(headers['Content-length'], '2087')
         self.assertTrue(headers['Content-type'].startswith('multipart/form-data'))
         self.assertFalse('\n' in headers['Authorization'])
 
-        self.assertEquals(self.conn.requests, [('POST', '/pypi')])
-        self.assert_((b'xxx') in self.conn.body)
+        self.assertEqual(self.conn.requests, [('POST', '/pypi')])
+        self.assertTrue((b'xxx') in self.conn.body)
 
 def test_suite():
     return unittest.makeSuite(uploadTestCase)

Modified: python/branches/pep-3151/Lib/distutils/tests/test_util.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_util.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_util.py	Sat Feb 26 08:16:32 2011
@@ -67,21 +67,21 @@
         sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
                        '[MSC v.1310 32 bit (Intel)]')
         sys.platform = 'win32'
-        self.assertEquals(get_platform(), 'win32')
+        self.assertEqual(get_platform(), 'win32')
 
         # windows XP, amd64
         os.name = 'nt'
         sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
                        '[MSC v.1310 32 bit (Amd64)]')
         sys.platform = 'win32'
-        self.assertEquals(get_platform(), 'win-amd64')
+        self.assertEqual(get_platform(), 'win-amd64')
 
         # windows XP, itanium
         os.name = 'nt'
         sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
                        '[MSC v.1310 32 bit (Itanium)]')
         sys.platform = 'win32'
-        self.assertEquals(get_platform(), 'win-ia64')
+        self.assertEqual(get_platform(), 'win-ia64')
 
         # macbook
         os.name = 'posix'
@@ -100,7 +100,7 @@
         cursize = sys.maxsize
         sys.maxsize = (2 ** 31)-1
         try:
-            self.assertEquals(get_platform(), 'macosx-10.3-i386')
+            self.assertEqual(get_platform(), 'macosx-10.3-i386')
         finally:
             sys.maxsize = cursize
 
@@ -111,33 +111,33 @@
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
 
-        self.assertEquals(get_platform(), 'macosx-10.4-fat')
+        self.assertEqual(get_platform(), 'macosx-10.4-fat')
 
         get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
                                        '/Developer/SDKs/MacOSX10.4u.sdk  '
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
 
-        self.assertEquals(get_platform(), 'macosx-10.4-intel')
+        self.assertEqual(get_platform(), 'macosx-10.4-intel')
 
         get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
                                        '/Developer/SDKs/MacOSX10.4u.sdk  '
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
-        self.assertEquals(get_platform(), 'macosx-10.4-fat3')
+        self.assertEqual(get_platform(), 'macosx-10.4-fat3')
 
         get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
                                        '/Developer/SDKs/MacOSX10.4u.sdk  '
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
-        self.assertEquals(get_platform(), 'macosx-10.4-universal')
+        self.assertEqual(get_platform(), 'macosx-10.4-universal')
 
         get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
                                        '/Developer/SDKs/MacOSX10.4u.sdk  '
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
 
-        self.assertEquals(get_platform(), 'macosx-10.4-fat64')
+        self.assertEqual(get_platform(), 'macosx-10.4-fat64')
 
         for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
             get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
@@ -145,7 +145,7 @@
                                            '-fno-strict-aliasing -fno-common '
                                            '-dynamic -DNDEBUG -g -O3'%(arch,))
 
-            self.assertEquals(get_platform(), 'macosx-10.4-%s'%(arch,))
+            self.assertEqual(get_platform(), 'macosx-10.4-%s'%(arch,))
 
         # linux debian sarge
         os.name = 'posix'
@@ -155,7 +155,7 @@
         self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
                     '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
 
-        self.assertEquals(get_platform(), 'linux-i686')
+        self.assertEqual(get_platform(), 'linux-i686')
 
         # XXX more platforms to tests here
 
@@ -166,8 +166,8 @@
             return '/'.join(path)
         os.path.join = _join
 
-        self.assertEquals(convert_path('/home/to/my/stuff'),
-                          '/home/to/my/stuff')
+        self.assertEqual(convert_path('/home/to/my/stuff'),
+                         '/home/to/my/stuff')
 
         # win
         os.sep = '\\'
@@ -178,10 +178,10 @@
         self.assertRaises(ValueError, convert_path, '/home/to/my/stuff')
         self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/')
 
-        self.assertEquals(convert_path('home/to/my/stuff'),
-                          'home\\to\\my\\stuff')
-        self.assertEquals(convert_path('.'),
-                          os.curdir)
+        self.assertEqual(convert_path('home/to/my/stuff'),
+                         'home\\to\\my\\stuff')
+        self.assertEqual(convert_path('.'),
+                         os.curdir)
 
     def test_change_root(self):
         # linux/mac
@@ -193,10 +193,10 @@
             return '/'.join(path)
         os.path.join = _join
 
-        self.assertEquals(change_root('/root', '/old/its/here'),
-                          '/root/old/its/here')
-        self.assertEquals(change_root('/root', 'its/here'),
-                          '/root/its/here')
+        self.assertEqual(change_root('/root', '/old/its/here'),
+                         '/root/old/its/here')
+        self.assertEqual(change_root('/root', 'its/here'),
+                         '/root/its/here')
 
         # windows
         os.name = 'nt'
@@ -212,10 +212,10 @@
             return '\\'.join(path)
         os.path.join = _join
 
-        self.assertEquals(change_root('c:\\root', 'c:\\old\\its\\here'),
-                          'c:\\root\\old\\its\\here')
-        self.assertEquals(change_root('c:\\root', 'its\\here'),
-                          'c:\\root\\its\\here')
+        self.assertEqual(change_root('c:\\root', 'c:\\old\\its\\here'),
+                         'c:\\root\\old\\its\\here')
+        self.assertEqual(change_root('c:\\root', 'its\\here'),
+                         'c:\\root\\its\\here')
 
         # BugsBunny os (it's a great os)
         os.name = 'BugsBunny'
@@ -233,16 +233,16 @@
         if os.name == 'posix':  # this test won't run on windows
             check_environ()
             import pwd
-            self.assertEquals(os.environ['HOME'], pwd.getpwuid(os.getuid())[5])
+            self.assertEqual(os.environ['HOME'], pwd.getpwuid(os.getuid())[5])
         else:
             check_environ()
 
-        self.assertEquals(os.environ['PLAT'], get_platform())
-        self.assertEquals(util._environ_checked, 1)
+        self.assertEqual(os.environ['PLAT'], get_platform())
+        self.assertEqual(util._environ_checked, 1)
 
     def test_split_quoted(self):
-        self.assertEquals(split_quoted('""one"" "two" \'three\' \\four'),
-                          ['one', 'two', 'three', 'four'])
+        self.assertEqual(split_quoted('""one"" "two" \'three\' \\four'),
+                         ['one', 'two', 'three', 'four'])
 
     def test_strtobool(self):
         yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1')
@@ -259,7 +259,7 @@
         res = rfc822_escape(header)
         wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s'
                   'header%(8s)s') % {'8s': '\n'+8*' '}
-        self.assertEquals(res, wanted)
+        self.assertEqual(res, wanted)
 
     def test_dont_write_bytecode(self):
         # makes sure byte_compile raise a DistutilsError

Modified: python/branches/pep-3151/Lib/distutils/tests/test_version.py
==============================================================================
--- python/branches/pep-3151/Lib/distutils/tests/test_version.py	(original)
+++ python/branches/pep-3151/Lib/distutils/tests/test_version.py	Sat Feb 26 08:16:32 2011
@@ -8,12 +8,12 @@
 
     def test_prerelease(self):
         version = StrictVersion('1.2.3a1')
-        self.assertEquals(version.version, (1, 2, 3))
-        self.assertEquals(version.prerelease, ('a', 1))
-        self.assertEquals(str(version), '1.2.3a1')
+        self.assertEqual(version.version, (1, 2, 3))
+        self.assertEqual(version.prerelease, ('a', 1))
+        self.assertEqual(str(version), '1.2.3a1')
 
         version = StrictVersion('1.2.0')
-        self.assertEquals(str(version), '1.2')
+        self.assertEqual(str(version), '1.2')
 
     def test_cmp_strict(self):
         versions = (('1.5.1', '1.5.2b2', -1),
@@ -42,9 +42,9 @@
                     raise AssertionError(("cmp(%s, %s) "
                                           "shouldn't raise ValueError")
                                             % (v1, v2))
-            self.assertEquals(res, wanted,
-                              'cmp(%s, %s) should be %s, got %s' %
-                              (v1, v2, wanted, res))
+            self.assertEqual(res, wanted,
+                             'cmp(%s, %s) should be %s, got %s' %
+                             (v1, v2, wanted, res))
 
 
     def test_cmp(self):
@@ -60,9 +60,9 @@
 
         for v1, v2, wanted in versions:
             res = LooseVersion(v1)._cmp(LooseVersion(v2))
-            self.assertEquals(res, wanted,
-                              'cmp(%s, %s) should be %s, got %s' %
-                              (v1, v2, wanted, res))
+            self.assertEqual(res, wanted,
+                             'cmp(%s, %s) should be %s, got %s' %
+                             (v1, v2, wanted, res))
 
 def test_suite():
     return unittest.makeSuite(VersionTestCase)

Modified: python/branches/pep-3151/Lib/doctest.py
==============================================================================
--- python/branches/pep-3151/Lib/doctest.py	(original)
+++ python/branches/pep-3151/Lib/doctest.py	Sat Feb 26 08:16:32 2011
@@ -318,7 +318,8 @@
     def __init__(self, out):
         self.__out = out
         self.__debugger_used = False
-        pdb.Pdb.__init__(self, stdout=out)
+        # do not play signal games in the pdb
+        pdb.Pdb.__init__(self, stdout=out, nosigint=True)
         # still use input() to get user input
         self.use_rawinput = 1
 
@@ -1372,6 +1373,7 @@
         # Note that the interactive output will go to *our*
         # save_stdout, even if that's not the real sys.stdout; this
         # allows us to write test cases for the set_trace behavior.
+        save_trace = sys.gettrace()
         save_set_trace = pdb.set_trace
         self.debugger = _OutputRedirectingPdb(save_stdout)
         self.debugger.reset()
@@ -1391,6 +1393,7 @@
         finally:
             sys.stdout = save_stdout
             pdb.set_trace = save_set_trace
+            sys.settrace(save_trace)
             linecache.getlines = self.save_linecache_getlines
             sys.displayhook = save_displayhook
             if clear_globs:
@@ -2528,14 +2531,16 @@
                     exec(f.read(), globs, globs)
             except:
                 print(sys.exc_info()[1])
-                pdb.post_mortem(sys.exc_info()[2])
+                p = pdb.Pdb(nosigint=True)
+                p.reset()
+                p.interaction(None, sys.exc_info()[2])
         else:
             fp = open(srcfilename)
             try:
                 script = fp.read()
             finally:
                 fp.close()
-            pdb.run("exec(%r)" % script, globs, globs)
+            pdb.Pdb(nosigint=True).run("exec(%r)" % script, globs, globs)
 
     finally:
         os.remove(srcfilename)

Modified: python/branches/pep-3151/Lib/email/__init__.py
==============================================================================
--- python/branches/pep-3151/Lib/email/__init__.py	(original)
+++ python/branches/pep-3151/Lib/email/__init__.py	Sat Feb 26 08:16:32 2011
@@ -59,5 +59,5 @@
 
     Optional _class and strict are passed to the Parser constructor.
     """
-    from email.parser import Parser
+    from email.parser import BytesParser
     return BytesParser(*args, **kws).parse(fp)

Modified: python/branches/pep-3151/Lib/email/_parseaddr.py
==============================================================================
--- python/branches/pep-3151/Lib/email/_parseaddr.py	(original)
+++ python/branches/pep-3151/Lib/email/_parseaddr.py	Sat Feb 26 08:16:32 2011
@@ -64,8 +64,10 @@
     if len(data) == 4:
         s = data[3]
         i = s.find('+')
+        if i == -1:
+            i = s.find('-')
         if i > 0:
-            data[3:] = [s[:i], s[i+1:]]
+            data[3:] = [s[:i], s[i:]]
         else:
             data.append('') # Dummy tz
     if len(data) < 5:
@@ -199,14 +201,18 @@
         self.commentlist = []
 
     def gotonext(self):
-        """Parse up to the start of the next address."""
+        """Skip white space and extract comments."""
+        wslist = []
         while self.pos < len(self.field):
             if self.field[self.pos] in self.LWS + '\n\r':
+                if self.field[self.pos] not in '\n\r':
+                    wslist.append(self.field[self.pos])
                 self.pos += 1
             elif self.field[self.pos] == '(':
                 self.commentlist.append(self.getcomment())
             else:
                 break
+        return EMPTYSTRING.join(wslist)
 
     def getaddrlist(self):
         """Parse all addresses.
@@ -319,16 +325,24 @@
 
         self.gotonext()
         while self.pos < len(self.field):
+            preserve_ws = True
             if self.field[self.pos] == '.':
+                if aslist and not aslist[-1].strip():
+                    aslist.pop()
                 aslist.append('.')
                 self.pos += 1
+                preserve_ws = False
             elif self.field[self.pos] == '"':
                 aslist.append('"%s"' % quote(self.getquote()))
             elif self.field[self.pos] in self.atomends:
+                if aslist and not aslist[-1].strip():
+                    aslist.pop()
                 break
             else:
                 aslist.append(self.getatom())
-            self.gotonext()
+            ws = self.gotonext()
+            if preserve_ws and ws:
+                aslist.append(ws)
 
         if self.pos >= len(self.field) or self.field[self.pos] != '@':
             return EMPTYSTRING.join(aslist)

Modified: python/branches/pep-3151/Lib/email/charset.py
==============================================================================
--- python/branches/pep-3151/Lib/email/charset.py	(original)
+++ python/branches/pep-3151/Lib/email/charset.py	Sat Feb 26 08:16:32 2011
@@ -28,6 +28,7 @@
 RFC2047_CHROME_LEN = 7
 
 DEFAULT_CHARSET = 'us-ascii'
+UNKNOWN8BIT = 'unknown-8bit'
 EMPTYSTRING = ''
 
 
@@ -153,6 +154,16 @@
 
 
 
+# Convenience function for encoding strings, taking into account
+# that they might be unknown-8bit (ie: have surrogate-escaped bytes)
+def _encode(string, codec):
+    if codec == UNKNOWN8BIT:
+        return string.encode('ascii', 'surrogateescape')
+    else:
+        return string.encode(codec)
+
+
+
 class Charset:
     """Map character sets to their email properties.
 
@@ -282,8 +293,7 @@
         :return: The encoded string, with RFC 2047 chrome.
         """
         codec = self.output_codec or 'us-ascii'
-        charset = self.get_output_charset()
-        header_bytes = string.encode(codec)
+        header_bytes = _encode(string, codec)
         # 7bit/8bit encodings return the string unchanged (modulo conversions)
         encoder_module = self._get_encoder(header_bytes)
         if encoder_module is None:
@@ -294,7 +304,7 @@
         """Header-encode a string by converting it first to bytes.
 
         This is similar to `header_encode()` except that the string is fit
-        into maximum line lengths as given by the arguments.
+        into maximum line lengths as given by the argument.
 
         :param string: A unicode string for the header.  It must be possible
             to encode this string to bytes using the character set's
@@ -305,13 +315,11 @@
             and should never be exhausted.  The maximum line lengths should
             not count the RFC 2047 chrome.  These line lengths are only a
             hint; the splitter does the best it can.
-        :param firstmaxlen: The maximum line length of the first line.  If
-            None (the default), then `maxlen` is used for the first line.
         :return: Lines of encoded strings, each with RFC 2047 chrome.
         """
         # See which encoding we should use.
         codec = self.output_codec or 'us-ascii'
-        header_bytes = string.encode(codec)
+        header_bytes = _encode(string, codec)
         encoder_module = self._get_encoder(header_bytes)
         encoder = partial(encoder_module.header_encode, charset=str(self))
         # Calculate the number of characters that the RFC 2047 chrome will
@@ -335,7 +343,7 @@
         for character in string:
             current_line.append(character)
             this_line = EMPTYSTRING.join(current_line)
-            length = encoder_module.header_length(this_line.encode(charset))
+            length = encoder_module.header_length(_encode(this_line, charset))
             if length > maxlen:
                 # This last character doesn't fit so pop it off.
                 current_line.pop()
@@ -345,12 +353,12 @@
                 else:
                     separator = (' ' if lines else '')
                     joined_line = EMPTYSTRING.join(current_line)
-                    header_bytes = joined_line.encode(codec)
+                    header_bytes = _encode(joined_line, codec)
                     lines.append(encoder(header_bytes))
                 current_line = [character]
                 maxlen = next(maxlengths) - extra
         joined_line = EMPTYSTRING.join(current_line)
-        header_bytes = joined_line.encode(codec)
+        header_bytes = _encode(joined_line, codec)
         lines.append(encoder(header_bytes))
         return lines
 

Modified: python/branches/pep-3151/Lib/email/generator.py
==============================================================================
--- python/branches/pep-3151/Lib/email/generator.py	(original)
+++ python/branches/pep-3151/Lib/email/generator.py	Sat Feb 26 08:16:32 2011
@@ -220,18 +220,13 @@
             g = self.clone(s)
             g.flatten(part, unixfrom=False, linesep=self._NL)
             msgtexts.append(s.getvalue())
-        # Now make sure the boundary we've selected doesn't appear in any of
-        # the message texts.
-        alltext = self._encoded_NL.join(msgtexts)
         # BAW: What about boundaries that are wrapped in double-quotes?
-        boundary = msg.get_boundary(failobj=self._make_boundary(alltext))
-        # If we had to calculate a new boundary because the body text
-        # contained that string, set the new boundary.  We don't do it
-        # unconditionally because, while set_boundary() preserves order, it
-        # doesn't preserve newlines/continuations in headers.  This is no big
-        # deal in practice, but turns out to be inconvenient for the unittest
-        # suite.
-        if msg.get_boundary() != boundary:
+        boundary = msg.get_boundary()
+        if not boundary:
+            # Create a boundary that doesn't appear in any of the
+            # message texts.
+            alltext = self._encoded_NL.join(msgtexts)
+            boundary = self._make_boundary(alltext)
             msg.set_boundary(boundary)
         # If there's a preamble, write it out, with a trailing CRLF
         if msg.preamble is not None:
@@ -274,7 +269,7 @@
         for part in msg.get_payload():
             s = self._new_buffer()
             g = self.clone(s)
-            g.flatten(part, unixfrom=False)
+            g.flatten(part, unixfrom=False, linesep=self._NL)
             text = s.getvalue()
             lines = text.split(self._encoded_NL)
             # Strip off the unnecessary trailing empty line
@@ -301,7 +296,7 @@
         # in that case we just emit the string body.
         payload = msg.get_payload()
         if isinstance(payload, list):
-            g.flatten(msg.get_payload(0), unixfrom=False)
+            g.flatten(msg.get_payload(0), unixfrom=False, linesep=self._NL)
             payload = s.getvalue()
         self._fp.write(payload)
 
@@ -382,6 +377,8 @@
     def _handle_text(self, msg):
         # If the string has surrogates the original source was bytes, so
         # just write it back out.
+        if msg._payload is None:
+            return
         if _has_surrogates(msg._payload):
             self.write(msg._payload)
         else:

Modified: python/branches/pep-3151/Lib/email/header.py
==============================================================================
--- python/branches/pep-3151/Lib/email/header.py	(original)
+++ python/branches/pep-3151/Lib/email/header.py	Sat Feb 26 08:16:32 2011
@@ -17,7 +17,8 @@
 import email.base64mime
 
 from email.errors import HeaderParseError
-from email.charset import Charset
+from email import charset as _charset
+Charset = _charset.Charset
 
 NL = '\n'
 SPACE = ' '
@@ -46,6 +47,10 @@
 # For use with .match()
 fcre = re.compile(r'[\041-\176]+:$')
 
+# Find a header embeded in a putative header value.  Used to check for
+# header injection attack.
+_embeded_header = re.compile(r'\n[^ \t]+:')
+
 
 
 # Helpers
@@ -169,7 +174,7 @@
         charset is used both as s's initial charset and as the default for
         subsequent .append() calls.
 
-        The maximum line length can be specified explicit via maxlinelen.  For
+        The maximum line length can be specified explicitly via maxlinelen. For
         splitting the first line to a shorter value (to account for the field
         header which isn't included in s, e.g. `Subject') pass in the name of
         the field in header_name.  The default maxlinelen is 78 as recommended
@@ -210,6 +215,9 @@
             # from a charset to None/us-ascii, or from None/us-ascii to a
             # charset.  Only do this for the second and subsequent chunks.
             nextcs = charset
+            if nextcs == _charset.UNKNOWN8BIT:
+                original_bytes = string.encode('ascii', 'surrogateescape')
+                string = original_bytes.decode('ascii', 'replace')
             if uchunks:
                 if lastcs not in (None, 'us-ascii'):
                     if nextcs in (None, 'us-ascii'):
@@ -241,36 +249,31 @@
         constructor is used.
 
         s may be a byte string or a Unicode string.  If it is a byte string
-        (i.e. isinstance(s, str) is true), then charset is the encoding of
+        (i.e. isinstance(s, str) is false), then charset is the encoding of
         that byte string, and a UnicodeError will be raised if the string
         cannot be decoded with that charset.  If s is a Unicode string, then
         charset is a hint specifying the character set of the characters in
-        the string.  In this case, when producing an RFC 2822 compliant header
-        using RFC 2047 rules, the Unicode string will be encoded using the
-        following charsets in order: us-ascii, the charset hint, utf-8.  The
-        first character set not to provoke a UnicodeError is used.
+        the string.  In either case, when producing an RFC 2822 compliant
+        header using RFC 2047 rules, the string will be encoded using the
+        output codec of the charset.  If the string cannot be encoded to the
+        output codec, a UnicodeError will be raised.
 
-        Optional `errors' is passed as the third argument to any unicode() or
-        ustr.encode() call.
+        Optional `errors' is passed as the errors argument to the decode
+        call if s is a byte string.
         """
         if charset is None:
             charset = self._charset
         elif not isinstance(charset, Charset):
             charset = Charset(charset)
-        if isinstance(s, str):
-            # Convert the string from the input character set to the output
-            # character set and store the resulting bytes and the charset for
-            # composition later.
+        if not isinstance(s, str):
             input_charset = charset.input_codec or 'us-ascii'
-            input_bytes = s.encode(input_charset, errors)
-        else:
-            # We already have the bytes we will store internally.
-            input_bytes = s
+            s = s.decode(input_charset, errors)
         # Ensure that the bytes we're storing can be decoded to the output
         # character set, otherwise an early error is thrown.
         output_charset = charset.output_codec or 'us-ascii'
-        output_string = input_bytes.decode(output_charset, errors)
-        self._chunks.append((output_string, charset))
+        if output_charset != _charset.UNKNOWN8BIT:
+            s.encode(output_charset, errors)
+        self._chunks.append((s, charset))
 
     def encode(self, splitchars=';, \t', maxlinelen=None, linesep='\n'):
         """Encode a message header into an RFC-compliant format.
@@ -311,12 +314,21 @@
                                     self._continuation_ws, splitchars)
         for string, charset in self._chunks:
             lines = string.splitlines()
-            for line in lines:
+            formatter.feed(lines[0], charset)
+            for line in lines[1:]:
+                formatter.newline()
+                if charset.header_encoding is not None:
+                    formatter.feed(self._continuation_ws, USASCII)
+                    line = ' ' + line.lstrip()
                 formatter.feed(line, charset)
-                if len(lines) > 1:
-                    formatter.newline()
+            if len(lines) > 1:
+                formatter.newline()
             formatter.add_transition()
-        return formatter._str(linesep)
+        value = formatter._str(linesep)
+        if _embeded_header.search(value):
+            raise HeaderParseError("header value appears to contain "
+                "an embedded header: {!r}".format(value))
+        return value
 
     def _normalize(self):
         # Step 1: Normalize the chunks so that all runs of identical charsets

Modified: python/branches/pep-3151/Lib/email/message.py
==============================================================================
--- python/branches/pep-3151/Lib/email/message.py	(original)
+++ python/branches/pep-3151/Lib/email/message.py	Sat Feb 26 08:16:32 2011
@@ -16,7 +16,9 @@
 # Intrapackage imports
 from email import utils
 from email import errors
-from email.charset import Charset
+from email import header
+from email import charset as _charset
+Charset = _charset.Charset
 
 SEMISPACE = '; '
 
@@ -31,16 +33,15 @@
 
 
 # Helper functions
-def _sanitize_surrogates(value):
-    # If the value contains surrogates, re-decode and replace the original
-    # non-ascii bytes with '?'s.  Used to sanitize header values before letting
-    # them escape as strings.
+def _sanitize_header(name, value):
+    # If the header value contains surrogates, return a Header using
+    # the unknown-8bit charset to encode the bytes as encoded words.
     if not isinstance(value, str):
-        # Header object
+        # Assume it is already a header object
         return value
     if _has_surrogates(value):
-        original_bytes = value.encode('ascii', 'surrogateescape')
-        return original_bytes.decode('ascii', 'replace').replace('\ufffd', '?')
+        return header.Header(value, charset=_charset.UNKNOWN8BIT,
+                             header_name=name)
     else:
         return value
 
@@ -57,16 +58,28 @@
 def _formatparam(param, value=None, quote=True):
     """Convenience function to format and return a key=value pair.
 
-    This will quote the value if needed or if quote is true.
+    This will quote the value if needed or if quote is true.  If value is a
+    three tuple (charset, language, value), it will be encoded according
+    to RFC2231 rules.  If it contains non-ascii characters it will likewise
+    be encoded according to RFC2231 rules, using the utf-8 charset and
+    a null language.
     """
     if value is not None and len(value) > 0:
         # A tuple is used for RFC 2231 encoded parameter values where items
         # are (charset, language, value).  charset is a string, not a Charset
-        # instance.
+        # instance.  RFC 2231 encoded values are never quoted, per RFC.
         if isinstance(value, tuple):
             # Encode as per RFC 2231
             param += '*'
             value = utils.encode_rfc2231(value[2], value[0], value[1])
+            return '%s=%s' % (param, value)
+        else:
+            try:
+                value.encode('ascii')
+            except UnicodeEncodeError:
+                param += '*'
+                value = utils.encode_rfc2231(value, 'utf-8', '')
+                return '%s=%s' % (param, value)
         # BAW: Please check this.  I think that if quote is set it should
         # force quoting even if not necessary.
         if quote or tspecials.search(value):
@@ -386,7 +399,7 @@
         Any fields deleted and re-inserted are always appended to the header
         list.
         """
-        return [_sanitize_surrogates(v) for k, v in self._headers]
+        return [_sanitize_header(k, v) for k, v in self._headers]
 
     def items(self):
         """Get all the message's header fields and values.
@@ -396,7 +409,7 @@
         Any fields deleted and re-inserted are always appended to the header
         list.
         """
-        return [(k, _sanitize_surrogates(v)) for k, v in self._headers]
+        return [(k, _sanitize_header(k, v)) for k, v in self._headers]
 
     def get(self, name, failobj=None):
         """Get a header value.
@@ -407,7 +420,7 @@
         name = name.lower()
         for k, v in self._headers:
             if k.lower() == name:
-                return _sanitize_surrogates(v)
+                return _sanitize_header(k, v)
         return failobj
 
     #
@@ -427,7 +440,7 @@
         name = name.lower()
         for k, v in self._headers:
             if k.lower() == name:
-                values.append(_sanitize_surrogates(v))
+                values.append(_sanitize_header(k, v))
         if not values:
             return failobj
         return values
@@ -438,11 +451,19 @@
         name is the header field to add.  keyword arguments can be used to set
         additional parameters for the header field, with underscores converted
         to dashes.  Normally the parameter will be added as key="value" unless
-        value is None, in which case only the key will be added.
+        value is None, in which case only the key will be added.  If a
+        parameter value contains non-ASCII characters it can be specified as a
+        three-tuple of (charset, language, value), in which case it will be
+        encoded according to RFC2231 rules.  Otherwise it will be encoded using
+        the utf-8 charset and a language of ''.
 
-        Example:
+        Examples:
 
         msg.add_header('content-disposition', 'attachment', filename='bud.gif')
+        msg.add_header('content-disposition', 'attachment',
+                       filename=('utf-8', '', Fußballer.ppt'))
+        msg.add_header('content-disposition', 'attachment',
+                       filename='Fußballer.ppt'))
         """
         parts = []
         for k, v in _params.items():

Modified: python/branches/pep-3151/Lib/email/test/test_email.py
==============================================================================
--- python/branches/pep-3151/Lib/email/test/test_email.py	(original)
+++ python/branches/pep-3151/Lib/email/test/test_email.py	Sat Feb 26 08:16:32 2011
@@ -3,6 +3,7 @@
 # email package unit tests
 
 import os
+import re
 import sys
 import time
 import base64
@@ -44,13 +45,13 @@
 SPACE = ' '
 
 
-
+
 def openfile(filename, *args, **kws):
     path = os.path.join(os.path.dirname(landmark), 'data', filename)
     return open(path, *args, **kws)
 
 
-
+
 # Base test class
 class TestEmailBase(unittest.TestCase):
     def ndiffAssertEqual(self, first, second):
@@ -68,7 +69,7 @@
             return email.message_from_file(fp)
 
 
-
+
 # Test various aspects of the Message class's API
 class TestMessageAPI(TestEmailBase):
     def test_get_all(self):
@@ -77,7 +78,7 @@
         eq(msg.get_all('cc'), ['ccc at zzz.org', 'ddd at zzz.org', 'eee at zzz.org'])
         eq(msg.get_all('xx', 'n/a'), 'n/a')
 
-    def TEst_getset_charset(self):
+    def test_getset_charset(self):
         eq = self.assertEqual
         msg = Message()
         eq(msg.get_charset(), None)
@@ -179,6 +180,17 @@
         self.assertRaises(errors.HeaderParseError,
                           msg.set_boundary, 'BOUNDARY')
 
+    def test_make_boundary(self):
+        msg = MIMEMultipart('form-data')
+        # Note that when the boundary gets created is an implementation
+        # detail and might change.
+        self.assertEqual(msg.items()[0][1], 'multipart/form-data')
+        # Trigger creation of boundary
+        msg.as_string()
+        self.assertEqual(msg.items()[0][1][:33],
+                        'multipart/form-data; boundary="==')
+        # XXX: there ought to be tests of the uniqueness of the boundary, too.
+
     def test_message_rfc822_only(self):
         # Issue 7970: message/rfc822 not in multipart parsed by
         # HeaderParser caused an exception when flattened.
@@ -509,8 +521,59 @@
         self.assertEqual(msg.get_payload(decode=True),
                          bytes(x, 'raw-unicode-escape'))
 
+    # Issue 1078919
+    def test_ascii_add_header(self):
+        msg = Message()
+        msg.add_header('Content-Disposition', 'attachment',
+                       filename='bud.gif')
+        self.assertEqual('attachment; filename="bud.gif"',
+            msg['Content-Disposition'])
+
+    def test_noascii_add_header(self):
+        msg = Message()
+        msg.add_header('Content-Disposition', 'attachment',
+            filename="Fußballer.ppt")
+        self.assertEqual(
+            'attachment; filename*=utf-8\'\'Fu%C3%9Fballer.ppt',
+            msg['Content-Disposition'])
+
+    def test_nonascii_add_header_via_triple(self):
+        msg = Message()
+        msg.add_header('Content-Disposition', 'attachment',
+            filename=('iso-8859-1', '', 'Fußballer.ppt'))
+        self.assertEqual(
+            'attachment; filename*=iso-8859-1\'\'Fu%DFballer.ppt',
+            msg['Content-Disposition'])
+
+    def test_ascii_add_header_with_tspecial(self):
+        msg = Message()
+        msg.add_header('Content-Disposition', 'attachment',
+            filename="windows [filename].ppt")
+        self.assertEqual(
+            'attachment; filename="windows [filename].ppt"',
+            msg['Content-Disposition'])
+
+    def test_nonascii_add_header_with_tspecial(self):
+        msg = Message()
+        msg.add_header('Content-Disposition', 'attachment',
+            filename="Fußballer [filename].ppt")
+        self.assertEqual(
+            "attachment; filename*=utf-8''Fu%C3%9Fballer%20%5Bfilename%5D.ppt",
+            msg['Content-Disposition'])
+
+    # Issue 5871: reject an attempt to embed a header inside a header value
+    # (header injection attack).
+    def test_embeded_header_via_Header_rejected(self):
+        msg = Message()
+        msg['Dummy'] = Header('dummy\nX-Injected-Header: test')
+        self.assertRaises(errors.HeaderParseError, msg.as_string)
+
+    def test_embeded_header_via_string_rejected(self):
+        msg = Message()
+        msg['Dummy'] = 'dummy\nX-Injected-Header: test'
+        self.assertRaises(errors.HeaderParseError, msg.as_string)
+
 
-
 # Test the email.encoders module
 class TestEncoders(unittest.TestCase):
     def test_encode_empty_payload(self):
@@ -539,7 +602,7 @@
         msg = MIMEText('æ–‡', _charset='euc-jp')
         eq(msg['content-transfer-encoding'], '7bit')
 
-
+
 # Test long header wrapping
 class TestLongHeaders(TestEmailBase):
     def test_split_long_continuation(self):
@@ -917,8 +980,21 @@
 
 """)
 
+    def test_long_rfc2047_header_with_embedded_fws(self):
+        h = Header(textwrap.dedent("""\
+            We're going to pretend this header is in a non-ascii character set
+            \tto see if line wrapping with encoded words and embedded
+               folding white space works"""),
+                   charset='utf-8',
+                   header_name='Test')
+        self.assertEqual(h.encode()+'\n', textwrap.dedent("""\
+            =?utf-8?q?We=27re_going_to_pretend_this_header_is_in_a_non-ascii_chara?=
+             =?utf-8?q?cter_set?=
+             =?utf-8?q?_to_see_if_line_wrapping_with_encoded_words_and_embedded?=
+             =?utf-8?q?_folding_white_space_works?=""")+'\n')
+
+
 
-
 # Test mangling of "From " lines in the body of a message
 class TestFromMangling(unittest.TestCase):
     def setUp(self):
@@ -952,7 +1028,7 @@
 """)
 
 
-
+
 # Test the basic MIMEAudio class
 class TestMIMEAudio(unittest.TestCase):
     def setUp(self):
@@ -999,7 +1075,7 @@
                                   header='foobar') is missing)
 
 
-
+
 # Test the basic MIMEImage class
 class TestMIMEImage(unittest.TestCase):
     def setUp(self):
@@ -1040,7 +1116,7 @@
                                   header='foobar') is missing)
 
 
-
+
 # Test the basic MIMEApplication class
 class TestMIMEApplication(unittest.TestCase):
     def test_headers(self):
@@ -1057,7 +1133,7 @@
         eq(msg.get_payload(decode=True), bytes)
 
 
-
+
 # Test the basic MIMEText class
 class TestMIMEText(unittest.TestCase):
     def setUp(self):
@@ -1111,7 +1187,7 @@
         self.assertRaises(UnicodeEncodeError, MIMEText, teststr)
 
 
-
+
 # Test complicated multipart/* messages
 class TestMultipart(TestEmailBase):
     def setUp(self):
@@ -1483,10 +1559,10 @@
 
 YXNkZg==
 --===============0012394164==--""")
-        self.assertEquals(m.get_payload(0).get_payload(), 'YXNkZg==')
+        self.assertEqual(m.get_payload(0).get_payload(), 'YXNkZg==')
+
 
 
-
 # Test some badly formatted messages
 class TestNonConformant(TestEmailBase):
     def test_parse_missing_minor_type(self):
@@ -1600,7 +1676,7 @@
         eq(msg.defects[0].line, ' Line 1\n')
 
 
-
+
 # Test RFC 2047 header encoding and decoding
 class TestRFC2047(TestEmailBase):
     def test_rfc2047_multiline(self):
@@ -1666,7 +1742,7 @@
         self.assertEqual(decode_header(s),
                         [(b'andr\xe9=zz', 'iso-8659-1')])
 
-
+
 # Test the MIMEMessage class
 class TestMIMEMessage(TestEmailBase):
     def setUp(self):
@@ -1967,28 +2043,31 @@
         msg = MIMEMultipart()
         self.assertTrue(msg.is_multipart())
 
-
+
 # A general test of parser->model->generator idempotency.  IOW, read a message
 # in, parse it into a message object tree, then without touching the tree,
 # regenerate the plain text.  The original text and the transformed text
 # should be identical.  Note: that we ignore the Unix-From since that may
 # contain a changed date.
 class TestIdempotent(TestEmailBase):
+
+    linesep = '\n'
+
     def _msgobj(self, filename):
         with openfile(filename) as fp:
             data = fp.read()
         msg = email.message_from_string(data)
         return msg, data
 
-    def _idempotent(self, msg, text):
+    def _idempotent(self, msg, text, unixfrom=False):
         eq = self.ndiffAssertEqual
         s = StringIO()
         g = Generator(s, maxheaderlen=0)
-        g.flatten(msg)
+        g.flatten(msg, unixfrom=unixfrom)
         eq(text, s.getvalue())
 
     def test_parse_text_message(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         msg, text = self._msgobj('msg_01.txt')
         eq(msg.get_content_type(), 'text/plain')
         eq(msg.get_content_maintype(), 'text')
@@ -2000,7 +2079,7 @@
         self._idempotent(msg, text)
 
     def test_parse_untyped_message(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         msg, text = self._msgobj('msg_03.txt')
         eq(msg.get_content_type(), 'text/plain')
         eq(msg.get_params(), None)
@@ -2071,12 +2150,16 @@
         msg, text = self._msgobj('msg_36.txt')
         self._idempotent(msg, text)
 
+    def test_message_delivery_status(self):
+        msg, text = self._msgobj('msg_43.txt')
+        self._idempotent(msg, text, unixfrom=True)
+
     def test_message_signed_idempotent(self):
         msg, text = self._msgobj('msg_45.txt')
         self._idempotent(msg, text)
 
     def test_content_type(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         unless = self.assertTrue
         # Get a message object and reset the seek pointer for other tests
         msg, text = self._msgobj('msg_05.txt')
@@ -2087,16 +2170,16 @@
             params[pk] = pv
         eq(params['report-type'], 'delivery-status')
         eq(params['boundary'], 'D1690A7AC1.996856090/mail.example.com')
-        eq(msg.preamble, 'This is a MIME-encapsulated message.\n')
-        eq(msg.epilogue, '\n')
+        eq(msg.preamble, 'This is a MIME-encapsulated message.' + self.linesep)
+        eq(msg.epilogue, self.linesep)
         eq(len(msg.get_payload()), 3)
         # Make sure the subparts are what we expect
         msg1 = msg.get_payload(0)
         eq(msg1.get_content_type(), 'text/plain')
-        eq(msg1.get_payload(), 'Yadda yadda yadda\n')
+        eq(msg1.get_payload(), 'Yadda yadda yadda' + self.linesep)
         msg2 = msg.get_payload(1)
         eq(msg2.get_content_type(), 'text/plain')
-        eq(msg2.get_payload(), 'Yadda yadda yadda\n')
+        eq(msg2.get_payload(), 'Yadda yadda yadda' + self.linesep)
         msg3 = msg.get_payload(2)
         eq(msg3.get_content_type(), 'message/rfc822')
         self.assertTrue(isinstance(msg3, Message))
@@ -2105,10 +2188,10 @@
         eq(len(payload), 1)
         msg4 = payload[0]
         unless(isinstance(msg4, Message))
-        eq(msg4.get_payload(), 'Yadda yadda yadda\n')
+        eq(msg4.get_payload(), 'Yadda yadda yadda' + self.linesep)
 
     def test_parser(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         unless = self.assertTrue
         msg, text = self._msgobj('msg_06.txt')
         # Check some of the outer headers
@@ -2122,10 +2205,10 @@
         self.assertTrue(isinstance(msg1, Message))
         eq(msg1.get_content_type(), 'text/plain')
         self.assertTrue(isinstance(msg1.get_payload(), str))
-        eq(msg1.get_payload(), '\n')
+        eq(msg1.get_payload(), self.linesep)
+
 
 
-
 # Test various other bits of the package's functionality
 class TestMiscellaneous(TestEmailBase):
     def test_message_from_string(self):
@@ -2235,6 +2318,16 @@
         eq(utils.parsedate_tz('5 Feb 2003 13:47:26 -0800'),
            (2003, 2, 5, 13, 47, 26, 0, 1, -1, -28800))
 
+    def test_parsedate_no_space_before_positive_offset(self):
+        self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14:58:26+0800'),
+           (2002, 4, 3, 14, 58, 26, 0, 1, -1, 28800))
+
+    def test_parsedate_no_space_before_negative_offset(self):
+        # Issue 1155362: we already handled '+' for this case.
+        self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14:58:26-0800'),
+           (2002, 4, 3, 14, 58, 26, 0, 1, -1, -28800))
+
+
     def test_parsedate_acceptable_to_time_functions(self):
         eq = self.assertEqual
         timetup = utils.parsedate('5 Feb 2003 13:47:26 -0800')
@@ -2311,6 +2404,24 @@
         eq(utils.parseaddr('"\\\\"example\\\\" example"@example.com'),
           ('', '"\\\\"example\\\\" example"@example.com'))
 
+    def test_parseaddr_preserves_spaces_in_local_part(self):
+        # issue 9286.  A normal RFC5322 local part should not contain any
+        # folding white space, but legacy local parts can (they are a sequence
+        # of atoms, not dotatoms).  On the other hand we strip whitespace from
+        # before the @ and around dots, on the assumption that the whitespace
+        # around the punctuation is a mistake in what would otherwise be
+        # an RFC5322 local part.  Leading whitespace is, usual, stripped as well.
+        self.assertEqual(('', "merwok wok at xample.com"),
+            utils.parseaddr("merwok wok at xample.com"))
+        self.assertEqual(('', "merwok  wok at xample.com"),
+            utils.parseaddr("merwok  wok at xample.com"))
+        self.assertEqual(('', "merwok  wok at xample.com"),
+            utils.parseaddr(" merwok  wok  @xample.com"))
+        self.assertEqual(('', 'merwok"wok"  wok at xample.com'),
+            utils.parseaddr('merwok"wok"  wok at xample.com'))
+        self.assertEqual(('', 'merwok.wok.wok at xample.com'),
+            utils.parseaddr('merwok. wok .  wok at xample.com'))
+
     def test_multiline_from_comment(self):
         x = """\
 Foo
@@ -2449,8 +2560,12 @@
     text/rfc822-headers
 """)
 
+    def test_make_msgid_domain(self):
+        self.assertEqual(
+            email.utils.make_msgid(domain='testdomain-string')[-19:],
+            '@testdomain-string>')
+
 
-
 # Test the iterator/generators
 class TestIterators(TestEmailBase):
     def test_body_line_iterator(self):
@@ -2540,7 +2655,7 @@
         self.assertTrue(''.join([il for il, n in imt]) == ''.join(om))
 
 
-
+
 class TestParsers(TestEmailBase):
     def test_header_parser(self):
         eq = self.assertEqual
@@ -2704,7 +2819,7 @@
         msg = email.message_from_string(m)
         self.assertTrue(msg.get_payload(0).get_payload().endswith('\r\n'))
 
-
+
 class Test8BitBytesHandling(unittest.TestCase):
     # In Python3 all input is string, but that doesn't work if the actual input
     # uses an 8bit transfer encoding.  To hack around that, in email 5.1 we
@@ -2738,7 +2853,7 @@
                                      cte='8bit',
                                      bodyline='pöstal').encode('utf-8')
         msg = email.message_from_bytes(m)
-        self.assertEqual(msg.get_payload(), "p��stal\n")
+        self.assertEqual(msg.get_payload(), "p\uFFFD\uFFFDstal\n")
         self.assertEqual(msg.get_payload(decode=True),
                          "pöstal\n".encode('utf-8'))
 
@@ -2771,7 +2886,7 @@
                                      cte='quoted-printable',
                                      bodyline='p=C3=B6stál').encode('utf-8')
         msg = email.message_from_bytes(m)
-        self.assertEqual(msg.get_payload(), 'p=C3=B6st��l\n')
+        self.assertEqual(msg.get_payload(), 'p=C3=B6st\uFFFD\uFFFDl\n')
         self.assertEqual(msg.get_payload(decode=True),
                         'pöstál\n'.encode('utf-8'))
 
@@ -2796,52 +2911,65 @@
                          '<,.V<W1A; á \n'.encode('utf-8'))
 
 
-    headertest_msg = textwrap.dedent("""\
-        From: foo at bar.com
-        To: báz
-        Subject: Maintenant je vous présente mon collègue, le pouf célèbre
-        \tJean de Baddie
-        From: göst
-
-        Yes, they are flying.
-        """).encode('utf-8')
+    headertest_headers = (
+        ('From: foo at bar.com', ('From', 'foo at bar.com')),
+        ('To: báz', ('To', '=?unknown-8bit?q?b=C3=A1z?=')),
+        ('Subject: Maintenant je vous présente mon collègue, le pouf célèbre\n'
+            '\tJean de Baddie',
+            ('Subject', '=?unknown-8bit?q?Maintenant_je_vous_pr=C3=A9sente_mon_'
+                'coll=C3=A8gue=2C_le_pouf_c=C3=A9l=C3=A8bre?=\n'
+                ' =?unknown-8bit?q?_Jean_de_Baddie?=')),
+        ('From: göst', ('From', '=?unknown-8bit?b?Z8O2c3Q=?=')),
+        )
+    headertest_msg = ('\n'.join([src for (src, _) in headertest_headers]) +
+        '\nYes, they are flying.\n').encode('utf-8')
 
     def test_get_8bit_header(self):
         msg = email.message_from_bytes(self.headertest_msg)
-        self.assertEqual(msg.get('to'), 'b??z')
-        self.assertEqual(msg['to'], 'b??z')
+        self.assertEqual(str(msg.get('to')), 'b\uFFFD\uFFFDz')
+        self.assertEqual(str(msg['to']), 'b\uFFFD\uFFFDz')
 
     def test_print_8bit_headers(self):
         msg = email.message_from_bytes(self.headertest_msg)
         self.assertEqual(str(msg),
-                         self.headertest_msg.decode(
-                            'ascii', 'replace').replace('�', '?'))
+                         textwrap.dedent("""\
+                            From: {}
+                            To: {}
+                            Subject: {}
+                            From: {}
+
+                            Yes, they are flying.
+                            """).format(*[expected[1] for (_, expected) in
+                                        self.headertest_headers]))
 
     def test_values_with_8bit_headers(self):
         msg = email.message_from_bytes(self.headertest_msg)
-        self.assertListEqual(msg.values(),
+        self.assertListEqual([str(x) for x in msg.values()],
                               ['foo at bar.com',
-                               'b??z',
-                               'Maintenant je vous pr??sente mon '
-                                   'coll??gue, le pouf c??l??bre\n'
+                               'b\uFFFD\uFFFDz',
+                               'Maintenant je vous pr\uFFFD\uFFFDsente mon '
+                                   'coll\uFFFD\uFFFDgue, le pouf '
+                                   'c\uFFFD\uFFFDl\uFFFD\uFFFDbre\n'
                                    '\tJean de Baddie',
-                               "g??st"])
+                               "g\uFFFD\uFFFDst"])
 
     def test_items_with_8bit_headers(self):
         msg = email.message_from_bytes(self.headertest_msg)
-        self.assertListEqual(msg.items(),
+        self.assertListEqual([(str(x), str(y)) for (x, y) in msg.items()],
                               [('From', 'foo at bar.com'),
-                               ('To', 'b??z'),
-                               ('Subject', 'Maintenant je vous pr??sente mon '
-                                              'coll??gue, le pouf c??l??bre\n'
-                                              '\tJean de Baddie'),
-                               ('From', 'g??st')])
+                               ('To', 'b\uFFFD\uFFFDz'),
+                               ('Subject', 'Maintenant je vous '
+                                  'pr\uFFFD\uFFFDsente '
+                                  'mon coll\uFFFD\uFFFDgue, le pouf '
+                                  'c\uFFFD\uFFFDl\uFFFD\uFFFDbre\n'
+                                  '\tJean de Baddie'),
+                               ('From', 'g\uFFFD\uFFFDst')])
 
     def test_get_all_with_8bit_headers(self):
         msg = email.message_from_bytes(self.headertest_msg)
-        self.assertListEqual(msg.get_all('from'),
+        self.assertListEqual([str(x) for x in msg.get_all('from')],
                               ['foo at bar.com',
-                               'g??st'])
+                               'g\uFFFD\uFFFDst'])
 
     non_latin_bin_msg = textwrap.dedent("""\
         From: foo at bar.com
@@ -2861,13 +2989,19 @@
         email.generator.BytesGenerator(out).flatten(msg)
         self.assertEqual(out.getvalue(), self.non_latin_bin_msg)
 
-    # XXX: ultimately the '?' should turn into CTE encoded bytes
-    # using 'unknown-8bit' charset.
-    non_latin_bin_msg_as7bit = textwrap.dedent("""\
+    def test_bytes_generator_handles_None_body(self):
+        #Issue 11019
+        msg = email.message.Message()
+        out = BytesIO()
+        email.generator.BytesGenerator(out).flatten(msg)
+        self.assertEqual(out.getvalue(), b"\n")
+
+    non_latin_bin_msg_as7bit_wrapped = textwrap.dedent("""\
         From: foo at bar.com
-        To: b??z
-        Subject: Maintenant je vous pr??sente mon coll??gue, le pouf c??l??bre
-        \tJean de Baddie
+        To: =?unknown-8bit?q?b=C3=A1z?=
+        Subject: =?unknown-8bit?q?Maintenant_je_vous_pr=C3=A9sente_mon_coll=C3=A8gue?=
+         =?unknown-8bit?q?=2C_le_pouf_c=C3=A9l=C3=A8bre?=
+         =?unknown-8bit?q?_Jean_de_Baddie?=
         Mime-Version: 1.0
         Content-Type: text/plain; charset="utf-8"
         Content-Transfer-Encoding: base64
@@ -2879,7 +3013,7 @@
         msg = email.message_from_bytes(self.non_latin_bin_msg)
         out = StringIO()
         email.generator.Generator(out).flatten(msg)
-        self.assertEqual(out.getvalue(), self.non_latin_bin_msg_as7bit)
+        self.assertEqual(out.getvalue(), self.non_latin_bin_msg_as7bit_wrapped)
 
     def test_bytes_generator_with_unix_from(self):
         # The unixfrom contains a current date, so we can't check it
@@ -2892,6 +3026,12 @@
         self.assertEqual(lines[0].split()[0], b'From')
         self.assertEqual(b'\n'.join(lines[1:]), self.non_latin_bin_msg)
 
+    non_latin_bin_msg_as7bit = non_latin_bin_msg_as7bit_wrapped.split('\n')
+    non_latin_bin_msg_as7bit[2:4] = [
+        'Subject: =?unknown-8bit?q?Maintenant_je_vous_pr=C3=A9sente_mon_'
+         'coll=C3=A8gue=2C_le_pouf_c=C3=A9l=C3=A8bre?=']
+    non_latin_bin_msg_as7bit = '\n'.join(non_latin_bin_msg_as7bit)
+
     def test_message_from_binary_file(self):
         fn = 'test.msg'
         self.addCleanup(unlink, fn)
@@ -2954,28 +3094,44 @@
         self.assertEqual(s.getvalue(), text)
     maxDiff = None
 
-
-class TestBytesGeneratorIdempotent(TestIdempotent):
+
+class BaseTestBytesGeneratorIdempotent:
+
+    maxDiff = None
 
     def _msgobj(self, filename):
         with openfile(filename, 'rb') as fp:
             data = fp.read()
+        data = self.normalize_linesep_regex.sub(self.blinesep, data)
         msg = email.message_from_bytes(data)
         return msg, data
 
-    def _idempotent(self, msg, data):
+    def _idempotent(self, msg, data, unixfrom=False):
         b = BytesIO()
         g = email.generator.BytesGenerator(b, maxheaderlen=0)
-        g.flatten(msg)
-        self.assertEqual(data, b.getvalue())
-
-    maxDiff = None
+        g.flatten(msg, unixfrom=unixfrom, linesep=self.linesep)
+        self.assertByteStringsEqual(data, b.getvalue())
 
-    def assertEqual(self, str1, str2):
+    def assertByteStringsEqual(self, str1, str2):
+        # Not using self.blinesep here is intentional.  This way the output
+        # is more useful when the failure results in mixed line endings.
         self.assertListEqual(str1.split(b'\n'), str2.split(b'\n'))
 
 
-
+class TestBytesGeneratorIdempotentNL(BaseTestBytesGeneratorIdempotent,
+                                    TestIdempotent):
+    linesep = '\n'
+    blinesep = b'\n'
+    normalize_linesep_regex = re.compile(br'\r\n')
+
+
+class TestBytesGeneratorIdempotentCRLF(BaseTestBytesGeneratorIdempotent,
+                                       TestIdempotent):
+    linesep = '\r\n'
+    blinesep = b'\r\n'
+    normalize_linesep_regex = re.compile(br'(?<!\r)\n')
+
+
 class TestBase64(unittest.TestCase):
     def test_len(self):
         eq = self.assertEqual
@@ -3028,7 +3184,7 @@
         eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=')
 
 
-
+
 class TestQuopri(unittest.TestCase):
     def setUp(self):
         # Set of characters (as byte integers) that don't need to be encoded
@@ -3147,7 +3303,7 @@
 two line""")
 
 
-
+
 # Test the Charset class
 class TestCharset(unittest.TestCase):
     def tearDown(self):
@@ -3205,7 +3361,7 @@
         self.assertRaises(errors.CharsetError, Charset, 'asc\xffii')
 
 
-
+
 # Test multilingual MIME headers.
 class TestHeader(TestEmailBase):
     def test_simple(self):
@@ -3514,8 +3670,12 @@
         s = 'Subject: =?EUC-KR?B?CSixpLDtKSC/7Liuvsax4iC6uLmwMcijIKHaILzSwd/H0SC8+LCjwLsgv7W/+Mj3I ?='
         raises(errors.HeaderParseError, decode_header, s)
 
+    def test_shift_jis_charset(self):
+        h = Header('æ–‡', charset='shift_jis')
+        self.assertEqual(h.encode(), '=?iso-2022-jp?b?GyRCSjgbKEI=?=')
+
+
 
-
 # Test RFC 2231 header parameters (en/de)coding
 class TestRFC2231(TestEmailBase):
     def test_get_param(self):
@@ -3553,7 +3713,7 @@
 Subject: This is a test message
 Date: Fri, 4 May 2001 14:05:44 -0400
 Content-Type: text/plain; charset=us-ascii;
- title*="us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21"
+ title*=us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21
 
 
 Hi,
@@ -3583,7 +3743,7 @@
 Subject: This is a test message
 Date: Fri, 4 May 2001 14:05:44 -0400
 Content-Type: text/plain; charset="us-ascii";
- title*="us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21"
+ title*=us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21
 
 
 Hi,
@@ -3598,6 +3758,32 @@
         msg = self._msgobj('msg_32.txt')
         eq(msg.get_content_charset(), 'us-ascii')
 
+    def test_rfc2231_parse_rfc_quoting(self):
+        m = textwrap.dedent('''\
+            Content-Disposition: inline;
+            \tfilename*0*=''This%20is%20even%20more%20;
+            \tfilename*1*=%2A%2A%2Afun%2A%2A%2A%20;
+            \tfilename*2="is it not.pdf"
+
+            ''')
+        msg = email.message_from_string(m)
+        self.assertEqual(msg.get_filename(),
+                         'This is even more ***fun*** is it not.pdf')
+        self.assertEqual(m, msg.as_string())
+
+    def test_rfc2231_parse_extra_quoting(self):
+        m = textwrap.dedent('''\
+            Content-Disposition: inline;
+            \tfilename*0*="''This%20is%20even%20more%20";
+            \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20";
+            \tfilename*2="is it not.pdf"
+
+            ''')
+        msg = email.message_from_string(m)
+        self.assertEqual(msg.get_filename(),
+                         'This is even more ***fun*** is it not.pdf')
+        self.assertEqual(m, msg.as_string())
+
     def test_rfc2231_no_language_or_charset(self):
         m = '''\
 Content-Transfer-Encoding: 8bit
@@ -3827,7 +4013,7 @@
         eq(s, 'My Document For You')
 
 
-
+
 # Tests to ensure that signed parts of an email are completely preserved, as
 # required by RFC1847 section 2.1.  Note that these are incomplete, because the
 # email package does not currently always preserve the body.  See issue 1670765.
@@ -3865,7 +4051,7 @@
         self._signed_parts_eq(original, result)
 
 
-
+
 def _testclasses():
     mod = sys.modules[__name__]
     return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
@@ -3883,6 +4069,6 @@
         run_unittest(testclass)
 
 
-
+
 if __name__ == '__main__':
     unittest.main(defaultTest='suite')

Modified: python/branches/pep-3151/Lib/email/utils.py
==============================================================================
--- python/branches/pep-3151/Lib/email/utils.py	(original)
+++ python/branches/pep-3151/Lib/email/utils.py	Sat Feb 26 08:16:32 2011
@@ -148,13 +148,15 @@
 
 
 
-def make_msgid(idstring=None):
+def make_msgid(idstring=None, domain=None):
     """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:
 
     <20020201195627.33539.96671 at nightshade.la.mastaler.com>
 
     Optional idstring if given is a string used to strengthen the
-    uniqueness of the message id.
+    uniqueness of the message id.  Optional domain if given provides the
+    portion of the message id after the '@'.  It defaults to the locally
+    defined hostname.
     """
     timeval = time.time()
     utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
@@ -164,8 +166,9 @@
         idstring = ''
     else:
         idstring = '.' + idstring
-    idhost = socket.getfqdn()
-    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost)
+    if domain is None:
+        domain = socket.getfqdn()
+    msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain)
     return msgid
 
 

Modified: python/branches/pep-3151/Lib/fractions.py
==============================================================================
--- python/branches/pep-3151/Lib/fractions.py	(original)
+++ python/branches/pep-3151/Lib/fractions.py	Sat Feb 26 08:16:32 2011
@@ -528,12 +528,8 @@
             return Fraction(round(self / shift) * shift)
 
     def __hash__(self):
-        """hash(self)
+        """hash(self)"""
 
-        Tricky because values that are exactly representable as a
-        float must have the same hash as that float.
-
-        """
         # XXX since this method is expensive, consider caching the result
 
         # In order to make sure that the hash of a Fraction agrees
@@ -550,7 +546,8 @@
             hash_ = _PyHASH_INF
         else:
             hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS
-        return hash_ if self >= 0 else -hash_
+        result = hash_ if self >= 0 else -hash_
+        return -2 if result == -1 else result
 
     def __eq__(a, b):
         """a == b"""

Modified: python/branches/pep-3151/Lib/ftplib.py
==============================================================================
--- python/branches/pep-3151/Lib/ftplib.py	(original)
+++ python/branches/pep-3151/Lib/ftplib.py	Sat Feb 26 08:16:32 2011
@@ -100,7 +100,7 @@
     file = None
     welcome = None
     passiveserver = 1
-    encoding = "latin1"
+    encoding = "latin-1"
 
     # Initialization method (called by class instantiation).
     # Initialize host to localhost, port to standard ftp port
@@ -589,11 +589,11 @@
 
     def close(self):
         '''Close the connection without assuming anything about it.'''
-        if self.file:
+        if self.file is not None:
             self.file.close()
+        if self.sock is not None:
             self.sock.close()
-            self.file = self.sock = None
-
+        self.file = self.sock = None
 
 try:
     import ssl

Modified: python/branches/pep-3151/Lib/functools.py
==============================================================================
--- python/branches/pep-3151/Lib/functools.py	(original)
+++ python/branches/pep-3151/Lib/functools.py	Sat Feb 26 08:16:32 2011
@@ -12,7 +12,7 @@
            'total_ordering', 'cmp_to_key', 'lru_cache', 'reduce', 'partial']
 
 from _functools import partial, reduce
-from collections import OrderedDict
+from collections import OrderedDict, namedtuple
 try:
     from _thread import allocate_lock as Lock
 except:
@@ -68,17 +68,17 @@
 def total_ordering(cls):
     """Class decorator that fills in missing ordering methods"""
     convert = {
-        '__lt__': [('__gt__', lambda self, other: other < self),
-                   ('__le__', lambda self, other: not other < self),
+        '__lt__': [('__gt__', lambda self, other: not (self < other or self == other)),
+                   ('__le__', lambda self, other: self < other or self == other),
                    ('__ge__', lambda self, other: not self < other)],
-        '__le__': [('__ge__', lambda self, other: other <= self),
-                   ('__lt__', lambda self, other: not other <= self),
+        '__le__': [('__ge__', lambda self, other: not self <= other or self == other),
+                   ('__lt__', lambda self, other: self <= other and not self == other),
                    ('__gt__', lambda self, other: not self <= other)],
-        '__gt__': [('__lt__', lambda self, other: other > self),
-                   ('__ge__', lambda self, other: not other > self),
+        '__gt__': [('__lt__', lambda self, other: not (self > other or self == other)),
+                   ('__ge__', lambda self, other: self > other or self == other),
                    ('__le__', lambda self, other: not self > other)],
-        '__ge__': [('__le__', lambda self, other: other >= self),
-                   ('__gt__', lambda self, other: not other >= self),
+        '__ge__': [('__le__', lambda self, other: (not self >= other) or self == other),
+                   ('__gt__', lambda self, other: self >= other and not self == other),
                    ('__lt__', lambda self, other: not self >= other)]
     }
     # Find user-defined comparisons (not those inherited from object).
@@ -114,49 +114,91 @@
             raise TypeError('hash not implemented')
     return K
 
+_CacheInfo = namedtuple("CacheInfo", "hits misses maxsize currsize")
+
 def lru_cache(maxsize=100):
     """Least-recently-used cache decorator.
 
+    If *maxsize* is set to None, the LRU features are disabled and the cache
+    can grow without bound.
+
     Arguments to the cached function must be hashable.
-    Cache performance statistics stored in f.hits and f.misses.
-    Clear the cache using f.clear().
-    http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
+
+    View the cache statistics named tuple (hits, misses, maxsize, currsize) with
+    f.cache_info().  Clear the cache and statistics with f.cache_clear().
+    Access the underlying function with f.__wrapped__.
+
+    See:  http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used
 
     """
-    def decorating_function(user_function, tuple=tuple, sorted=sorted,
-                            len=len, KeyError=KeyError):
-        cache = OrderedDict()           # ordered least recent to most recent
-        cache_popitem = cache.popitem
-        cache_renew = cache.move_to_end
-        kwd_mark = object()             # separate positional and keyword args
-        lock = Lock()
-
-        @wraps(user_function)
-        def wrapper(*args, **kwds):
-            key = args
-            if kwds:
-                key += (kwd_mark,) + tuple(sorted(kwds.items()))
-            try:
-                with lock:
+    # Users should only access the lru_cache through its public API:
+    #       cache_info, cache_clear, and f.__wrapped__
+    # The internals of the lru_cache are encapsulated for thread safety and
+    # to allow the implementation to change (including a possible C version).
+
+    def decorating_function(user_function,
+                tuple=tuple, sorted=sorted, len=len, KeyError=KeyError):
+
+        hits = misses = 0
+        kwd_mark = object()             # separates positional and keyword args
+        lock = Lock()                   # needed because ordereddicts aren't threadsafe
+
+        if maxsize is None:
+            cache = dict()              # simple cache without ordering or size limit
+
+            @wraps(user_function)
+            def wrapper(*args, **kwds):
+                nonlocal hits, misses
+                key = args
+                if kwds:
+                    key += (kwd_mark,) + tuple(sorted(kwds.items()))
+                try:
                     result = cache[key]
-                    cache_renew(key)            # record recent use of this key
-                    wrapper.cache_hits += 1
-            except KeyError:
-                result = user_function(*args, **kwds)
-                with lock:
-                    cache[key] = result         # record recent use of this key
-                    wrapper.cache_misses += 1
-                    if len(cache) > maxsize:
-                        cache_popitem(0)        # purge least recently used cache entry
-            return result
+                    hits += 1
+                except KeyError:
+                    result = user_function(*args, **kwds)
+                    cache[key] = result
+                    misses += 1
+                return result
+        else:
+            cache = OrderedDict()       # ordered least recent to most recent
+            cache_popitem = cache.popitem
+            cache_renew = cache.move_to_end
+
+            @wraps(user_function)
+            def wrapper(*args, **kwds):
+                nonlocal hits, misses
+                key = args
+                if kwds:
+                    key += (kwd_mark,) + tuple(sorted(kwds.items()))
+                try:
+                    with lock:
+                        result = cache[key]
+                        cache_renew(key)        # record recent use of this key
+                        hits += 1
+                except KeyError:
+                    result = user_function(*args, **kwds)
+                    with lock:
+                        cache[key] = result     # record recent use of this key
+                        misses += 1
+                        if len(cache) > maxsize:
+                            cache_popitem(0)    # purge least recently used cache entry
+                return result
+
+        def cache_info():
+            """Report cache statistics"""
+            with lock:
+                return _CacheInfo(hits, misses, maxsize, len(cache))
 
         def cache_clear():
             """Clear the cache and cache statistics"""
+            nonlocal hits, misses
             with lock:
                 cache.clear()
-                wrapper.cache_hits = wrapper.cache_misses = 0
+                hits = misses = 0
 
-        wrapper.cache_hits = wrapper.cache_misses = 0
+        wrapper.cache_info = cache_info
         wrapper.cache_clear = cache_clear
         return wrapper
+
     return decorating_function

Modified: python/branches/pep-3151/Lib/getpass.py
==============================================================================
--- python/branches/pep-3151/Lib/getpass.py	(original)
+++ python/branches/pep-3151/Lib/getpass.py	Sat Feb 26 08:16:32 2011
@@ -166,12 +166,7 @@
     try:
         import msvcrt
     except ImportError:
-        try:
-            from EasyDialogs import AskPassword
-        except ImportError:
-            getpass = fallback_getpass
-        else:
-            getpass = AskPassword
+        getpass = fallback_getpass
     else:
         getpass = win_getpass
 else:

Modified: python/branches/pep-3151/Lib/gettext.py
==============================================================================
--- python/branches/pep-3151/Lib/gettext.py	(original)
+++ python/branches/pep-3151/Lib/gettext.py	Sat Feb 26 08:16:32 2011
@@ -46,7 +46,7 @@
 #   find this format documented anywhere.
 
 
-import locale, copy, os, re, struct, sys
+import locale, copy, io, os, re, struct, sys
 from errno import ENOENT
 
 
@@ -58,28 +58,13 @@
 _default_localedir = os.path.join(sys.prefix, 'share', 'locale')
 
 
-def test(condition, true, false):
-    """
-    Implements the C expression:
-
-      condition ? true : false
-
-    Required to correctly interpret plural forms.
-    """
-    if condition:
-        return true
-    else:
-        return false
-
-
 def c2py(plural):
     """Gets a C expression as used in PO files for plural forms and returns a
     Python lambda function that implements an equivalent expression.
     """
     # Security check, allow only the "n" identifier
-    from io import StringIO
     import token, tokenize
-    tokens = tokenize.generate_tokens(StringIO(plural).readline)
+    tokens = tokenize.generate_tokens(io.StringIO(plural).readline)
     try:
         danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
     except tokenize.TokenError:
@@ -96,11 +81,11 @@
     plural = expr.sub(' not \\1', plural)
 
     # Regular expression and replacement function used to transform
-    # "a?b:c" to "test(a,b,c)".
+    # "a?b:c" to "b if a else c".
     expr = re.compile(r'(.*?)\?(.*?):(.*)')
     def repl(x):
-        return "test(%s, %s, %s)" % (x.group(1), x.group(2),
-                                     expr.sub(repl, x.group(3)))
+        return "(%s if %s else %s)" % (x.group(2), x.group(1),
+                                       expr.sub(repl, x.group(3)))
 
     # Code to transform the plural expression, taking care of parentheses
     stack = ['']
@@ -123,36 +108,35 @@
 
 
 
-def _expand_lang(locale):
-    from locale import normalize
-    locale = normalize(locale)
+def _expand_lang(loc):
+    loc = locale.normalize(loc)
     COMPONENT_CODESET   = 1 << 0
     COMPONENT_TERRITORY = 1 << 1
     COMPONENT_MODIFIER  = 1 << 2
     # split up the locale into its base components
     mask = 0
-    pos = locale.find('@')
+    pos = loc.find('@')
     if pos >= 0:
-        modifier = locale[pos:]
-        locale = locale[:pos]
+        modifier = loc[pos:]
+        loc = loc[:pos]
         mask |= COMPONENT_MODIFIER
     else:
         modifier = ''
-    pos = locale.find('.')
+    pos = loc.find('.')
     if pos >= 0:
-        codeset = locale[pos:]
-        locale = locale[:pos]
+        codeset = loc[pos:]
+        loc = loc[:pos]
         mask |= COMPONENT_CODESET
     else:
         codeset = ''
-    pos = locale.find('_')
+    pos = loc.find('_')
     if pos >= 0:
-        territory = locale[pos:]
-        locale = locale[:pos]
+        territory = loc[pos:]
+        loc = loc[:pos]
         mask |= COMPONENT_TERRITORY
     else:
         territory = ''
-    language = locale
+    language = loc
     ret = []
     for i in range(mask+1):
         if not (i & ~mask):  # if all components for this combo exist ...

Modified: python/branches/pep-3151/Lib/gzip.py
==============================================================================
--- python/branches/pep-3151/Lib/gzip.py	(original)
+++ python/branches/pep-3151/Lib/gzip.py	Sat Feb 26 08:16:32 2011
@@ -98,7 +98,7 @@
         return self.file.seek(offset, whence)
 
     def __getattr__(self, name):
-        return getattr(name, self.file)
+        return getattr(self.file, name)
 
 
 class GzipFile(io.BufferedIOBase):

Modified: python/branches/pep-3151/Lib/hashlib.py
==============================================================================
--- python/branches/pep-3151/Lib/hashlib.py	(original)
+++ python/branches/pep-3151/Lib/hashlib.py	Sat Feb 26 08:16:32 2011
@@ -56,8 +56,8 @@
 # always available algorithm is added.
 __always_supported = ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512')
 
-algorithms_guaranteed = __always_supported
-algorithms_available = frozenset(__always_supported)
+algorithms_guaranteed = set(__always_supported)
+algorithms_available = set(__always_supported)
 
 __all__ = __always_supported + ('new', 'algorithms_guaranteed',
                                 'algorithms_available')

Modified: python/branches/pep-3151/Lib/html/parser.py
==============================================================================
--- python/branches/pep-3151/Lib/html/parser.py	(original)
+++ python/branches/pep-3151/Lib/html/parser.py	Sat Feb 26 08:16:32 2011
@@ -24,10 +24,14 @@
 piclose = re.compile('>')
 commentclose = re.compile(r'--\s*>')
 tagfind = re.compile('[a-zA-Z][-.a-zA-Z0-9:_]*')
+# Note, the strict one of this pair isn't really strict, but we can't
+# make it correctly strict without breaking backward compatibility.
 attrfind = re.compile(
     r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*'
     r'(\'[^\']*\'|"[^"]*"|[-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~@]*))?')
-
+attrfind_tolerant = re.compile(
+    r'\s*([a-zA-Z_][-.:a-zA-Z_0-9]*)(\s*=\s*'
+    r'(\'[^\']*\'|"[^"]*"|[^>\s]*))?')
 locatestarttagend = re.compile(r"""
   <[a-zA-Z][-.a-zA-Z0-9:_]*          # tag name
   (?:\s+                             # whitespace before attribute name
@@ -42,6 +46,21 @@
    )*
   \s*                                # trailing whitespace
 """, re.VERBOSE)
+locatestarttagend_tolerant = re.compile(r"""
+  <[a-zA-Z][-.a-zA-Z0-9:_]*          # tag name
+  (?:\s*                             # optional whitespace before attribute name
+    (?:[a-zA-Z_][-.:a-zA-Z0-9_]*     # attribute name
+      (?:\s*=\s*                     # value indicator
+        (?:'[^']*'                   # LITA-enclosed value
+          |\"[^\"]*\"                # LIT-enclosed value
+          |[^'\">\s]+                # bare value
+         )
+         (?:\s*,)*                   # possibly followed by a comma
+       )?
+     )
+   )*
+  \s*                                # trailing whitespace
+""", re.VERBOSE)
 endendtag = re.compile('>')
 endtagfind = re.compile('</\s*([a-zA-Z][-.a-zA-Z0-9:_]*)\s*>')
 
@@ -86,9 +105,15 @@
 
     CDATA_CONTENT_ELEMENTS = ("script", "style")
 
+    def __init__(self, strict=True):
+        """Initialize and reset this instance.
 
-    def __init__(self):
-        """Initialize and reset this instance."""
+        If strict is set to True (the default), errors are raised when invalid
+        HTML is encountered.  If set to False, an attempt is instead made to
+        continue parsing, making "best guesses" about the intended meaning, in
+        a fashion similar to what browsers typically do.
+        """
+        self.strict = strict
         self.reset()
 
     def reset(self):
@@ -160,9 +185,18 @@
                 else:
                     break
                 if k < 0:
-                    if end:
+                    if not end:
+                        break
+                    if self.strict:
                         self.error("EOF in middle of construct")
-                    break
+                    k = rawdata.find('>', i + 1)
+                    if k < 0:
+                        k = rawdata.find('<', i + 1)
+                        if k < 0:
+                            k = i + 1
+                    else:
+                        k += 1
+                    self.handle_data(rawdata[i:k])
                 i = self.updatepos(i, k)
             elif startswith("&#", i):
                 match = charref.match(rawdata, i)
@@ -193,7 +227,12 @@
                 if match:
                     # match.group() will contain at least 2 chars
                     if end and match.group() == rawdata[i:]:
-                        self.error("EOF in middle of entity or char ref")
+                        if self.strict:
+                            self.error("EOF in middle of entity or char ref")
+                        else:
+                            if k <= i:
+                                k = n
+                            i = self.updatepos(i, i + 1)
                     # incomplete
                     break
                 elif (i + 1) < n:
@@ -240,7 +279,10 @@
         self.lasttag = tag = rawdata[i+1:k].lower()
 
         while k < endpos:
-            m = attrfind.match(rawdata, k)
+            if self.strict:
+                m = attrfind.match(rawdata, k)
+            else:
+                m = attrfind_tolerant.search(rawdata, k)
             if not m:
                 break
             attrname, rest, attrvalue = m.group(1, 2, 3)
@@ -262,8 +304,11 @@
                          - self.__starttag_text.rfind("\n")
             else:
                 offset = offset + len(self.__starttag_text)
-            self.error("junk characters in start tag: %r"
-                       % (rawdata[k:endpos][:20],))
+            if self.strict:
+                self.error("junk characters in start tag: %r"
+                           % (rawdata[k:endpos][:20],))
+            self.handle_data(rawdata[i:endpos])
+            return endpos
         if end.endswith('/>'):
             # XHTML-style empty tag: <span attr="value" />
             self.handle_startendtag(tag, attrs)
@@ -277,7 +322,10 @@
     # or -1 if incomplete.
     def check_for_whole_start_tag(self, i):
         rawdata = self.rawdata
-        m = locatestarttagend.match(rawdata, i)
+        if self.strict:
+            m = locatestarttagend.match(rawdata, i)
+        else:
+            m = locatestarttagend_tolerant.match(rawdata, i)
         if m:
             j = m.end()
             next = rawdata[j:j+1]
@@ -290,8 +338,13 @@
                     # buffer boundary
                     return -1
                 # else bogus input
-                self.updatepos(i, j + 1)
-                self.error("malformed empty start tag")
+                if self.strict:
+                    self.updatepos(i, j + 1)
+                    self.error("malformed empty start tag")
+                if j > i:
+                    return j
+                else:
+                    return i + 1
             if next == "":
                 # end of input
                 return -1
@@ -300,8 +353,13 @@
                 # end of input in or before attribute value, or we have the
                 # '/' from a '/>' ending
                 return -1
-            self.updatepos(i, j)
-            self.error("malformed start tag")
+            if self.strict:
+                self.updatepos(i, j)
+                self.error("malformed start tag")
+            if j > i:
+                return j
+            else:
+                return i + 1
         raise AssertionError("we should not get here!")
 
     # Internal -- parse endtag, return end or -1 if incomplete
@@ -314,7 +372,15 @@
         j = match.end()
         match = endtagfind.match(rawdata, i) # </ + tag + >
         if not match:
-            self.error("bad end tag: %r" % (rawdata[i:j],))
+            if self.strict:
+                self.error("bad end tag: %r" % (rawdata[i:j],))
+            k = rawdata.find('<', i + 1, j)
+            if k > i:
+                j = k
+            if j <= i:
+                j = i + 1
+            self.handle_data(rawdata[i:j])
+            return j
         tag = match.group(1)
         self.handle_endtag(tag.lower())
         self.clear_cdata_mode()
@@ -358,7 +424,8 @@
         pass
 
     def unknown_decl(self, data):
-        self.error("unknown declaration: %r" % (data,))
+        if self.strict:
+            self.error("unknown declaration: %r" % (data,))
 
     # Internal -- helper to remove special character quoting
     entitydefs = None
@@ -367,13 +434,16 @@
             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 chr(c)
+            try:
+                if s[0] == "#":
+                    s = s[1:]
+                    if s[0] in ['x','X']:
+                        c = int(s[1:], 16)
+                    else:
+                        c = int(s)
+                    return chr(c)
+            except ValueError:
+                return '&#'+ s +';'
             else:
                 # Cannot use name2codepoint directly, because HTMLParser
                 # supports apos, which is not part of HTML 4

Modified: python/branches/pep-3151/Lib/http/client.py
==============================================================================
--- python/branches/pep-3151/Lib/http/client.py	(original)
+++ python/branches/pep-3151/Lib/http/client.py	Sat Feb 26 08:16:32 2011
@@ -71,6 +71,7 @@
 import io
 import os
 import socket
+import collections
 from urllib.parse import urlsplit
 import warnings
 
@@ -203,6 +204,9 @@
 # maximal amount of data to read at one time in _safe_read
 MAXAMOUNT = 1048576
 
+# maximal line length when calling readline().
+_MAXLINE = 65536
+
 class HTTPMessage(email.message.Message):
     # XXX The only usage of this method is in
     # http.server.CGIHTTPRequestHandler.  Maybe move the code there so
@@ -245,20 +249,19 @@
     """
     headers = []
     while True:
-        line = fp.readline()
+        line = fp.readline(_MAXLINE + 1)
+        if len(line) > _MAXLINE:
+            raise LineTooLong("header line")
         headers.append(line)
         if line in (b'\r\n', b'\n', b''):
             break
     hstring = b''.join(headers).decode('iso-8859-1')
     return email.parser.Parser(_class=_class).parsestr(hstring)
 
-class HTTPResponse(io.RawIOBase):
 
-    # strict: If true, raise BadStatusLine if the status line can't be
-    # parsed as a valid HTTP/1.0 or 1.1 status line.  By default it is
-    # false because it prevents clients from talking to HTTP/0.9
-    # servers.  Note that a response with a sufficiently corrupted
-    # status line will look like an HTTP/0.9 response.
+_strict_sentinel = object()
+
+class HTTPResponse(io.RawIOBase):
 
     # See RFC 2616 sec 19.6 and RFC 1945 sec 6 for details.
 
@@ -267,7 +270,7 @@
     # text following RFC 2047.  The basic status line parsing only
     # accepts iso-8859-1.
 
-    def __init__(self, sock, debuglevel=0, strict=0, method=None, url=None):
+    def __init__(self, sock, debuglevel=0, strict=_strict_sentinel, method=None, url=None):
         # If the response includes a content-length header, we need to
         # make sure that the client doesn't read more than the
         # specified number of bytes.  If it does, it will block until
@@ -277,7 +280,10 @@
         # clients unless they know what they are doing.
         self.fp = sock.makefile("rb")
         self.debuglevel = debuglevel
-        self.strict = strict
+        if strict is not _strict_sentinel:
+            warnings.warn("the 'strict' argument isn't supported anymore; "
+                "http.client now always assumes HTTP/1.x compliant servers.",
+                DeprecationWarning, 2)
         self._method = method
 
         # The HTTPResponse object is returned via urllib.  The clients
@@ -299,8 +305,9 @@
         self.will_close = _UNKNOWN      # conn will close at end of response
 
     def _read_status(self):
-        # Initialize with Simple-Response defaults.
-        line = str(self.fp.readline(), "iso-8859-1")
+        line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
+        if len(line) > _MAXLINE:
+            raise LineTooLong("status line")
         if self.debuglevel > 0:
             print("reply:", repr(line))
         if not line:
@@ -308,25 +315,17 @@
             # sending a valid response.
             raise BadStatusLine(line)
         try:
-            [version, status, reason] = line.split(None, 2)
+            version, status, reason = line.split(None, 2)
         except ValueError:
             try:
-                [version, status] = line.split(None, 1)
+                version, status = line.split(None, 1)
                 reason = ""
             except ValueError:
-                # empty version will cause next test to fail and status
-                # will be treated as 0.9 response.
+                # empty version will cause next test to fail.
                 version = ""
         if not version.startswith("HTTP/"):
-            if self.strict:
-                self.close()
-                raise BadStatusLine(line)
-            else:
-                # Assume it's a Simple-Response from an 0.9 server.
-                # We have to convert the first line back to raw bytes
-                # because self.fp.readline() needs to return bytes.
-                self.fp = LineAndFileWrapper(bytes(line, "ascii"), self.fp)
-                return "HTTP/0.9", 200, ""
+            self.close()
+            raise BadStatusLine(line)
 
         # The status code is a three-digit number
         try:
@@ -349,7 +348,10 @@
                 break
             # skip the header from the 100 response
             while True:
-                skip = self.fp.readline().strip()
+                skip = self.fp.readline(_MAXLINE + 1)
+                if len(skip) > _MAXLINE:
+                    raise LineTooLong("header line")
+                skip = skip.strip()
                 if not skip:
                     break
                 if self.debuglevel > 0:
@@ -357,22 +359,14 @@
 
         self.code = self.status = status
         self.reason = reason.strip()
-        if version == "HTTP/1.0":
+        if version in ("HTTP/1.0", "HTTP/0.9"):
+            # Some servers might still return "0.9", treat it as 1.0 anyway
             self.version = 10
         elif version.startswith("HTTP/1."):
             self.version = 11   # use HTTP/1.1 code for HTTP/1.x where x>=1
-        elif version == "HTTP/0.9":
-            self.version = 9
         else:
             raise UnknownProtocol(version)
 
-        if self.version == 9:
-            self.length = None
-            self.chunked = False
-            self.will_close = True
-            self.headers = self.msg = email.message_from_string('')
-            return
-
         self.headers = self.msg = parse_headers(self.fp)
 
         if self.debuglevel > 0:
@@ -525,7 +519,9 @@
         value = []
         while True:
             if chunk_left is None:
-                line = self.fp.readline()
+                line = self.fp.readline(_MAXLINE + 1)
+                if len(line) > _MAXLINE:
+                    raise LineTooLong("chunk size")
                 i = line.find(b";")
                 if i >= 0:
                     line = line[:i] # strip chunk-extensions
@@ -560,7 +556,9 @@
         # read and discard trailer up to the CRLF terminator
         ### note: we shouldn't have any trailers!
         while True:
-            line = self.fp.readline()
+            line = self.fp.readline(_MAXLINE + 1)
+            if len(line) > _MAXLINE:
+                raise LineTooLong("trailer line")
             if not line:
                 # a vanishingly small number of sites EOF without
                 # sending the trailer
@@ -639,10 +637,13 @@
     default_port = HTTP_PORT
     auto_open = 1
     debuglevel = 0
-    strict = 0
 
-    def __init__(self, host, port=None, strict=None,
+    def __init__(self, host, port=None, strict=_strict_sentinel,
                  timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None):
+        if strict is not _strict_sentinel:
+            warnings.warn("the 'strict' argument isn't supported anymore; "
+                "http.client now always assumes HTTP/1.x compliant servers.",
+                DeprecationWarning, 2)
         self.timeout = timeout
         self.source_address = source_address
         self.sock = None
@@ -652,10 +653,9 @@
         self._method = None
         self._tunnel_host = None
         self._tunnel_port = None
+        self._tunnel_headers = {}
 
         self._set_hostport(host, port)
-        if strict is not None:
-            self.strict = strict
 
     def set_tunnel(self, host, port=None, headers=None):
         """ Sets up the host and the port for the HTTP CONNECT Tunnelling.
@@ -692,16 +692,16 @@
 
     def _tunnel(self):
         self._set_hostport(self._tunnel_host, self._tunnel_port)
-        connect_str = "CONNECT %s:%d HTTP/1.0\r\n" %(self.host, self.port)
+        connect_str = "CONNECT %s:%d HTTP/1.0\r\n" % (self.host, self.port)
         connect_bytes = connect_str.encode("ascii")
         self.send(connect_bytes)
-        for header, value in self._tunnel_headers.iteritems():
+        for header, value in self._tunnel_headers.items():
             header_str = "%s: %s\r\n" % (header, value)
-            header_bytes = header_str.encode("ascii")
+            header_bytes = header_str.encode("latin-1")
             self.send(header_bytes)
+        self.send(b'\r\n')
 
-        response = self.response_class(self.sock, strict = self.strict,
-                                       method = self._method)
+        response = self.response_class(self.sock, method=self._method)
         (version, code, message) = response._read_status()
 
         if code != 200:
@@ -709,7 +709,9 @@
             raise socket.error("Tunnel connection failed: %d %s" % (code,
                                                                     message.strip()))
         while True:
-            line = response.fp.readline()
+            line = response.fp.readline(_MAXLINE + 1)
+            if len(line) > _MAXLINE:
+                raise LineTooLong("header line")
             if line == b'\r\n':
                 break
 
@@ -731,7 +733,11 @@
         self.__state = _CS_IDLE
 
     def send(self, data):
-        """Send `data' to the server."""
+        """Send `data' to the server.
+        ``data`` can be a string object, a bytes object, an array object, a
+        file-like object that supports a .read() method, or an iterable object.
+        """
+
         if self.sock is None:
             if self.auto_open:
                 self.connect()
@@ -763,8 +769,16 @@
                 if encode:
                     datablock = datablock.encode("iso-8859-1")
                 self.sock.sendall(datablock)
-        else:
+
+        try:
             self.sock.sendall(data)
+        except TypeError:
+            if isinstance(data, collections.Iterable):
+                for d in data:
+                    self.sock.sendall(d)
+            else:
+                raise TypeError("data should be a bytes-like object\
+                        or an iterable, got %r " % type(it))
 
     def _output(self, s):
         """Add a line of output to the current request buffer.
@@ -874,6 +888,13 @@
                         host_enc = self.host.encode("ascii")
                     except UnicodeEncodeError:
                         host_enc = self.host.encode("idna")
+
+                    # As per RFC 273, IPv6 address should be wrapped with []
+                    # when used as Host header
+
+                    if self.host.find(':') >= 0:
+                        host_enc = b'[' + host_enc + b']'
+
                     if self.port == self.default_port:
                         self.putheader('Host', host_enc)
                     else:
@@ -916,7 +937,7 @@
         values = list(values)
         for i, one_value in enumerate(values):
             if hasattr(one_value, 'encode'):
-                values[i] = one_value.encode('ascii')
+                values[i] = one_value.encode('latin-1')
             elif isinstance(one_value, int):
                 values[i] = str(one_value).encode('ascii')
         value = b'\r\n\t'.join(values)
@@ -1018,11 +1039,9 @@
 
         if self.debuglevel > 0:
             response = self.response_class(self.sock, self.debuglevel,
-                                           strict=self.strict,
                                            method=self._method)
         else:
-            response = self.response_class(self.sock, strict=self.strict,
-                                           method=self._method)
+            response = self.response_class(self.sock, method=self._method)
 
         response.begin()
         assert response.will_close != _UNKNOWN
@@ -1050,7 +1069,7 @@
         # XXX Should key_file and cert_file be deprecated in favour of context?
 
         def __init__(self, host, port=None, key_file=None, cert_file=None,
-                     strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
+                     strict=_strict_sentinel, timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
                      source_address=None, *, context=None, check_hostname=None):
             super(HTTPSConnection, self).__init__(host, port, strict, timeout,
                                                   source_address)
@@ -1149,73 +1168,10 @@
         self.args = line,
         self.line = line
 
+class LineTooLong(HTTPException):
+    def __init__(self, line_type):
+        HTTPException.__init__(self, "got more than %d bytes when reading %s"
+                                     % (_MAXLINE, line_type))
+
 # for backwards compatibility
 error = HTTPException
-
-class LineAndFileWrapper:
-    """A limited file-like object for HTTP/0.9 responses."""
-
-    # The status-line parsing code calls readline(), which normally
-    # get the HTTP status line.  For a 0.9 response, however, this is
-    # actually the first line of the body!  Clients need to get a
-    # readable file object that contains that line.
-
-    def __init__(self, line, file):
-        self._line = line
-        self._file = file
-        self._line_consumed = 0
-        self._line_offset = 0
-        self._line_left = len(line)
-
-    def __getattr__(self, attr):
-        return getattr(self._file, attr)
-
-    def _done(self):
-        # called when the last byte is read from the line.  After the
-        # call, all read methods are delegated to the underlying file
-        # object.
-        self._line_consumed = 1
-        self.read = self._file.read
-        self.readline = self._file.readline
-        self.readlines = self._file.readlines
-
-    def read(self, amt=None):
-        if self._line_consumed:
-            return self._file.read(amt)
-        assert self._line_left
-        if amt is None or amt > self._line_left:
-            s = self._line[self._line_offset:]
-            self._done()
-            if amt is None:
-                return s + self._file.read()
-            else:
-                return s + self._file.read(amt - len(s))
-        else:
-            assert amt <= self._line_left
-            i = self._line_offset
-            j = i + amt
-            s = self._line[i:j]
-            self._line_offset = j
-            self._line_left -= amt
-            if self._line_left == 0:
-                self._done()
-            return s
-
-    def readline(self):
-        if self._line_consumed:
-            return self._file.readline()
-        assert self._line_left
-        s = self._line[self._line_offset:]
-        self._done()
-        return s
-
-    def readlines(self, size=None):
-        if self._line_consumed:
-            return self._file.readlines(size)
-        assert self._line_left
-        L = [self._line[self._line_offset:]]
-        self._done()
-        if size is None:
-            return L + self._file.readlines()
-        else:
-            return L + self._file.readlines(size)

Modified: python/branches/pep-3151/Lib/http/cookies.py
==============================================================================
--- python/branches/pep-3151/Lib/http/cookies.py	(original)
+++ python/branches/pep-3151/Lib/http/cookies.py	Sat Feb 26 08:16:32 2011
@@ -173,6 +173,11 @@
     '\033' : '\\033',  '\034' : '\\034',  '\035' : '\\035',
     '\036' : '\\036',  '\037' : '\\037',
 
+    # Because of the way browsers really handle cookies (as opposed
+    # to what the RFC says) we also encode , and ;
+
+    ',' : '\\054', ';' : '\\073',
+
     '"' : '\\"',       '\\' : '\\\\',
 
     '\177' : '\\177',  '\200' : '\\200',  '\201' : '\\201',
@@ -230,7 +235,7 @@
     if all(c in LegalChars for c in str):
         return str
     else:
-        return '"' + _nulljoin(map(_Translator.get, str, str)) + '"'
+        return '"' + _nulljoin(_Translator.get(s, s) for s in str) + '"'
 
 
 _OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")

Modified: python/branches/pep-3151/Lib/http/server.py
==============================================================================
--- python/branches/pep-3151/Lib/http/server.py	(original)
+++ python/branches/pep-3151/Lib/http/server.py	Sat Feb 26 08:16:32 2011
@@ -314,8 +314,12 @@
         self.command, self.path, self.request_version = command, path, version
 
         # Examine the headers and look for a Connection directive.
-        self.headers = http.client.parse_headers(self.rfile,
-                                                 _class=self.MessageClass)
+        try:
+            self.headers = http.client.parse_headers(self.rfile,
+                                                     _class=self.MessageClass)
+        except http.client.LineTooLong:
+            self.send_error(400, "Line too long")
+            return False
 
         conntype = self.headers.get('Connection', "")
         if conntype.lower() == 'close':
@@ -358,7 +362,13 @@
 
         """
         try:
-            self.raw_requestline = self.rfile.readline()
+            self.raw_requestline = self.rfile.readline(65537)
+            if len(self.raw_requestline) > 65536:
+                self.requestline = ''
+                self.request_version = ''
+                self.command = ''
+                self.send_error(414)
+                return
             if not self.raw_requestline:
                 self.close_connection = 1
                 return
@@ -438,12 +448,15 @@
                 message = ''
         if self.request_version != 'HTTP/0.9':
             self.wfile.write(("%s %d %s\r\n" %
-                              (self.protocol_version, code, message)).encode('ASCII', 'strict'))
+                              (self.protocol_version, code, message)).encode('latin-1', 'strict'))
 
     def send_header(self, keyword, value):
         """Send a MIME header."""
         if self.request_version != 'HTTP/0.9':
-            self.wfile.write(("%s: %s\r\n" % (keyword, value)).encode('ASCII', 'strict'))
+            if not hasattr(self, '_headers_buffer'):
+                self._headers_buffer = []
+            self._headers_buffer.append(
+                ("%s: %s\r\n" % (keyword, value)).encode('latin-1', 'strict'))
 
         if keyword.lower() == 'connection':
             if value.lower() == 'close':
@@ -454,7 +467,9 @@
     def end_headers(self):
         """Send the blank line ending the MIME headers."""
         if self.request_version != 'HTTP/0.9':
-            self.wfile.write(b"\r\n")
+            self._headers_buffer.append(b"\r\n")
+            self.wfile.write(b"".join(self._headers_buffer))
+            self._headers_buffer = []
 
     def log_request(self, code='-', size='-'):
         """Log an accepted request.
@@ -863,7 +878,7 @@
     try:
         nobody = pwd.getpwnam('nobody')[2]
     except KeyError:
-        nobody = 1 + max(map(lambda x: x[2], pwd.getpwall()))
+        nobody = 1 + max(x[2] for x in pwd.getpwall())
     return nobody
 
 

Modified: python/branches/pep-3151/Lib/idlelib/Bindings.py
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/Bindings.py	(original)
+++ python/branches/pep-3151/Lib/idlelib/Bindings.py	Sat Feb 26 08:16:32 2011
@@ -98,14 +98,6 @@
     # menu
     del menudefs[-1][1][0:2]
 
-    menudefs.insert(0,
-            ('application', [
-                ('About IDLE', '<<about-idle>>'),
-                None,
-                ('_Preferences....', '<<open-config-dialog>>'),
-            ]))
-
-
 default_keydefs = idleConf.GetCurrentKeySet()
 
 del sys

Modified: python/branches/pep-3151/Lib/idlelib/EditorWindow.py
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/EditorWindow.py	(original)
+++ python/branches/pep-3151/Lib/idlelib/EditorWindow.py	Sat Feb 26 08:16:32 2011
@@ -138,6 +138,14 @@
         if macosxSupport.runningAsOSXApp():
             # Command-W on editorwindows doesn't work without this.
             text.bind('<<close-window>>', self.close_event)
+            # Some OS X systems have only one mouse button,
+            # so use control-click for pulldown menus there.
+            #  (Note, AquaTk defines <2> as the right button if
+            #   present and the Tk Text widget already binds <2>.)
+            text.bind("<Control-Button-1>",self.right_menu_event)
+        else:
+            # Elsewhere, use right-click for pulldown menus.
+            text.bind("<3>",self.right_menu_event)
         text.bind("<<cut>>", self.cut)
         text.bind("<<copy>>", self.copy)
         text.bind("<<paste>>", self.paste)
@@ -156,7 +164,6 @@
         text.bind("<<find-selection>>", self.find_selection_event)
         text.bind("<<replace>>", self.replace_event)
         text.bind("<<goto-line>>", self.goto_line_event)
-        text.bind("<3>", self.right_menu_event)
         text.bind("<<smart-backspace>>",self.smart_backspace_event)
         text.bind("<<newline-and-indent>>",self.newline_and_indent_event)
         text.bind("<<smart-indent>>",self.smart_indent_event)
@@ -380,7 +387,7 @@
             underline, label = prepstr(label)
             menudict[name] = menu = Menu(mbar, name=name)
             mbar.add_cascade(label=label, menu=menu, underline=underline)
-        if macosxSupport.runningAsOSXApp():
+        if macosxSupport.isCarbonAquaTk(self.root):
             # Insert the application menu
             menudict['application'] = menu = Menu(mbar, name='apple')
             mbar.add_cascade(label='IDLE', menu=menu)
@@ -443,7 +450,11 @@
 
     def python_docs(self, event=None):
         if sys.platform[:3] == 'win':
-            os.startfile(self.help_url)
+            try:
+                os.startfile(self.help_url)
+            except WindowsError as why:
+                tkMessageBox.showerror(title='Document Start Failure',
+                    message=str(why), parent=self.text)
         else:
             webbrowser.open(self.help_url)
         return "break"
@@ -746,9 +757,13 @@
         "Create a callback with the helpfile value frozen at definition time"
         def display_extra_help(helpfile=helpfile):
             if not helpfile.startswith(('www', 'http')):
-                url = os.path.normpath(helpfile)
+                helpfile = os.path.normpath(helpfile)
             if sys.platform[:3] == 'win':
-                os.startfile(helpfile)
+                try:
+                    os.startfile(helpfile)
+                except WindowsError as why:
+                    tkMessageBox.showerror(title='Document Start Failure',
+                        message=str(why), parent=self.text)
             else:
                 webbrowser.open(helpfile)
         return display_extra_help
@@ -757,7 +772,8 @@
         "Load and update the recent files list and menus"
         rf_list = []
         if os.path.exists(self.recent_files_path):
-            rf_list_file = open(self.recent_files_path,'r')
+            rf_list_file = open(self.recent_files_path,'r',
+                                encoding='utf_8', errors='replace')
             try:
                 rf_list = rf_list_file.readlines()
             finally:
@@ -775,7 +791,8 @@
         rf_list = [path for path in rf_list if path not in bad_paths]
         ulchars = "1234567890ABCDEFGHIJK"
         rf_list = rf_list[0:len(ulchars)]
-        rf_file = open(self.recent_files_path, 'w')
+        rf_file = open(self.recent_files_path, 'w',
+                        encoding='utf_8', errors='replace')
         try:
             rf_file.writelines(rf_list)
         finally:
@@ -1529,7 +1546,12 @@
 
 def get_accelerator(keydefs, eventname):
     keylist = keydefs.get(eventname)
-    if not keylist:
+    # issue10940: temporary workaround to prevent hang with OS X Cocoa Tk 8.5
+    # if not keylist:
+    if (not keylist) or (macosxSupport.runningAsOSXApp() and eventname in {
+                            "<<open-module>>",
+                            "<<goto-line>>",
+                            "<<change-indentwidth>>"}):
         return ""
     s = keylist[0]
     s = re.sub(r"-[a-z]\b", lambda m: m.group().upper(), s)

Modified: python/branches/pep-3151/Lib/idlelib/FileList.py
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/FileList.py	(original)
+++ python/branches/pep-3151/Lib/idlelib/FileList.py	Sat Feb 26 08:16:32 2011
@@ -48,7 +48,7 @@
     def new(self, filename=None):
         return self.EditorWindow(self, filename)
 
-    def close_all_callback(self, event):
+    def close_all_callback(self, *args, **kwds):
         for edit in list(self.inversedict):
             reply = edit.close()
             if reply == "cancel":

Modified: python/branches/pep-3151/Lib/idlelib/IOBinding.py
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/IOBinding.py	(original)
+++ python/branches/pep-3151/Lib/idlelib/IOBinding.py	Sat Feb 26 08:16:32 2011
@@ -476,8 +476,8 @@
     savedialog = None
 
     filetypes = [
-        ("Python and text files", "*.py *.pyw *.txt", "TEXT"),
-        ("All text files", "*", "TEXT"),
+        ("Python files", "*.py *.pyw", "TEXT"),
+        ("Text files", "*.txt", "TEXT"),
         ("All files", "*"),
         ]
 

Modified: python/branches/pep-3151/Lib/idlelib/PyShell.py
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/PyShell.py	(original)
+++ python/branches/pep-3151/Lib/idlelib/PyShell.py	Sat Feb 26 08:16:32 2011
@@ -1417,6 +1417,13 @@
             shell.interp.prepend_syspath(script)
             shell.interp.execfile(script)
 
+    # Check for problematic OS X Tk versions and print a warning message
+    # in the IDLE shell window; this is less intrusive than always opening
+    # a separate window.
+    tkversionwarning = macosxSupport.tkVersionWarning(root)
+    if tkversionwarning:
+        shell.interp.runcommand(''.join(("print('", tkversionwarning, "')")))
+
     root.mainloop()
     root.destroy()
 

Modified: python/branches/pep-3151/Lib/idlelib/RemoteObjectBrowser.py
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/RemoteObjectBrowser.py	(original)
+++ python/branches/pep-3151/Lib/idlelib/RemoteObjectBrowser.py	Sat Feb 26 08:16:32 2011
@@ -17,8 +17,8 @@
         return value
 
     def _GetSubList(self):
-        list = self.__item._GetSubList()
-        return list(map(remote_object_tree_item, list))
+        sub_list = self.__item._GetSubList()
+        return list(map(remote_object_tree_item, sub_list))
 
 class StubObjectTreeItem:
     # Lives in IDLE process
@@ -32,5 +32,5 @@
         return value
 
     def _GetSubList(self):
-        list = self.sockio.remotecall(self.oid, "_GetSubList", (), {})
-        return [StubObjectTreeItem(self.sockio, oid) for oid in list]
+        sub_list = self.sockio.remotecall(self.oid, "_GetSubList", (), {})
+        return [StubObjectTreeItem(self.sockio, oid) for oid in sub_list]

Modified: python/branches/pep-3151/Lib/idlelib/ScriptBinding.py
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/ScriptBinding.py	(original)
+++ python/branches/pep-3151/Lib/idlelib/ScriptBinding.py	Sat Feb 26 08:16:32 2011
@@ -190,10 +190,10 @@
                                   icon=tkMessageBox.QUESTION,
                                   type=tkMessageBox.OKCANCEL,
                                   default=tkMessageBox.OK,
-                                  parent=self.editwin.text)
+                                  master=self.editwin.text)
         return mb.show()
 
     def errorbox(self, title, message):
         # XXX This should really be a function of EditorWindow...
-        tkMessageBox.showerror(title, message, parent=self.editwin.text)
+        tkMessageBox.showerror(title, message, master=self.editwin.text)
         self.editwin.text.focus_set()

Modified: python/branches/pep-3151/Lib/idlelib/config-keys.def
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/config-keys.def	(original)
+++ python/branches/pep-3151/Lib/idlelib/config-keys.def	Sat Feb 26 08:16:32 2011
@@ -176,7 +176,7 @@
 redo = <Shift-Command-Key-Z>
 close-window = <Command-Key-w>
 restart-shell = <Control-Key-F6>
-save-window-as-file = <Command-Key-S>
+save-window-as-file = <Shift-Command-Key-S>
 close-all-windows = <Command-Key-q>
 view-restart = <Key-F6>
 tabify-region = <Control-Key-5>
@@ -208,7 +208,7 @@
 open-module = <Command-Key-m>
 find-selection = <Shift-Command-Key-F3>
 python-context-help = <Shift-Key-F1>
-save-copy-of-window-as-file = <Shift-Command-Key-s>
+save-copy-of-window-as-file = <Option-Command-Key-s>
 open-window-from-file = <Command-Key-o>
 python-docs = <Key-F1>
 

Modified: python/branches/pep-3151/Lib/idlelib/idle.bat
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/idle.bat	(original)
+++ python/branches/pep-3151/Lib/idlelib/idle.bat	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,4 @@
 @echo off
-rem Working IDLE bat for Windows - uses start instead of absolute pathname
-start idle.pyw %1 %2 %3 %4 %5 %6 %7 %8 %9
+rem Start IDLE using the appropriate Python interpreter
+set CURRDIR=%~dp0
+start "%CURRDIR%..\..\pythonw.exe" "%CURRDIR%idle.pyw" %1 %2 %3 %4 %5 %6 %7 %8 %9

Modified: python/branches/pep-3151/Lib/idlelib/idlever.py
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/idlever.py	(original)
+++ python/branches/pep-3151/Lib/idlelib/idlever.py	Sat Feb 26 08:16:32 2011
@@ -1 +1 @@
-IDLE_VERSION = "3.2a3"
+IDLE_VERSION = "3.3a0"

Modified: python/branches/pep-3151/Lib/idlelib/macosxSupport.py
==============================================================================
--- python/branches/pep-3151/Lib/idlelib/macosxSupport.py	(original)
+++ python/branches/pep-3151/Lib/idlelib/macosxSupport.py	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,7 @@
 """
 import sys
 import tkinter
+from os import path
 
 
 _appbundle = None
@@ -19,6 +20,37 @@
         _appbundle = (sys.platform == 'darwin' and '.app' in sys.executable)
     return _appbundle
 
+_carbonaquatk = None
+
+def isCarbonAquaTk(root):
+    """
+    Returns True if IDLE is using a Carbon Aqua Tk (instead of the
+    newer Cocoa Aqua Tk).
+    """
+    global _carbonaquatk
+    if _carbonaquatk is None:
+        _carbonaquatk = (runningAsOSXApp() and
+                         'aqua' in root.tk.call('tk', 'windowingsystem') and
+                         'AppKit' not in root.tk.call('winfo', 'server', '.'))
+    return _carbonaquatk
+
+def tkVersionWarning(root):
+    """
+    Returns a string warning message if the Tk version in use appears to
+    be one known to cause problems with IDLE.  The Apple Cocoa-based Tk 8.5
+    that was shipped with Mac OS X 10.6.
+    """
+
+    if (runningAsOSXApp() and
+            ('AppKit' in root.tk.call('winfo', 'server', '.')) and
+            (root.tk.call('info', 'patchlevel') == '8.5.7') ):
+        return (r"WARNING: The version of Tcl/Tk (8.5.7) in use may"
+                r" be unstable.\n"
+                r"Visit http://www.python.org/download/mac/tcltk/"
+                r" for current information.")
+    else:
+        return False
+
 def addOpenEventSupport(root, flist):
     """
     This ensures that the application will respont to open AppleEvents, which
@@ -79,9 +111,6 @@
         WindowList.add_windows_to_menu(menu)
     WindowList.register_callback(postwindowsmenu)
 
-    menudict['application'] = menu = Menu(menubar, name='apple')
-    menubar.add_cascade(label='IDLE', menu=menu)
-
     def about_dialog(event=None):
         from idlelib import aboutDialog
         aboutDialog.AboutDialog(root, 'About IDLE')
@@ -97,41 +126,45 @@
         root.instance_dict = flist.inversedict
         configDialog.ConfigDialog(root, 'Settings')
 
+    def help_dialog(event=None):
+        from idlelib import textView
+        fn = path.join(path.abspath(path.dirname(__file__)), 'help.txt')
+        textView.view_file(root, 'Help', fn)
 
     root.bind('<<about-idle>>', about_dialog)
     root.bind('<<open-config-dialog>>', config_dialog)
+    root.createcommand('::tk::mac::ShowPreferences', config_dialog)
     if flist:
         root.bind('<<close-all-windows>>', flist.close_all_callback)
 
-
-    ###check if Tk version >= 8.4.14; if so, use hard-coded showprefs binding
-    tkversion = root.tk.eval('info patchlevel')
-    # Note: we cannot check if the string tkversion >= '8.4.14', because
-    # the string '8.4.7' is greater than the string '8.4.14'.
-    if tuple(map(int, tkversion.split('.'))) >= (8, 4, 14):
-        Bindings.menudefs[0] =  ('application', [
+        # The binding above doesn't reliably work on all versions of Tk
+        # on MacOSX. Adding command definition below does seem to do the
+        # right thing for now.
+        root.createcommand('exit', flist.close_all_callback)
+
+    if isCarbonAquaTk(root):
+        # for Carbon AquaTk, replace the default Tk apple menu
+        menudict['application'] = menu = Menu(menubar, name='apple')
+        menubar.add_cascade(label='IDLE', menu=menu)
+        Bindings.menudefs.insert(0,
+            ('application', [
                 ('About IDLE', '<<about-idle>>'),
-                None,
-            ])
-        root.createcommand('::tk::mac::ShowPreferences', config_dialog)
+                    None,
+                ]))
+        tkversion = root.tk.eval('info patchlevel')
+        if tuple(map(int, tkversion.split('.'))) < (8, 4, 14):
+            # for earlier AquaTk versions, supply a Preferences menu item
+            Bindings.menudefs[0][1].append(
+                    ('_Preferences....', '<<open-config-dialog>>'),
+                )
     else:
-        for mname, entrylist in Bindings.menudefs:
-            menu = menudict.get(mname)
-            if not menu:
-                continue
-            else:
-                for entry in entrylist:
-                    if not entry:
-                        menu.add_separator()
-                    else:
-                        label, eventname = entry
-                        underline, label = prepstr(label)
-                        accelerator = get_accelerator(Bindings.default_keydefs,
-                        eventname)
-                        def command(text=root, eventname=eventname):
-                            text.event_generate(eventname)
-                        menu.add_command(label=label, underline=underline,
-                        command=command, accelerator=accelerator)
+        # assume Cocoa AquaTk
+        # replace default About dialog with About IDLE one
+        root.createcommand('tkAboutDialog', about_dialog)
+        # replace default "Help" item in Help menu
+        root.createcommand('::tk::mac::ShowHelp', help_dialog)
+        # remove redundant "IDLE Help" from menu
+        del Bindings.menudefs[-1][1][0]
 
 def setupApp(root, flist):
     """

Modified: python/branches/pep-3151/Lib/imaplib.py
==============================================================================
--- python/branches/pep-3151/Lib/imaplib.py	(original)
+++ python/branches/pep-3151/Lib/imaplib.py	Sat Feb 26 08:16:32 2011
@@ -24,6 +24,12 @@
 
 import binascii, errno, random, re, socket, subprocess, sys, time
 
+try:
+    import ssl
+    HAVE_SSL = True
+except ImportError:
+    HAVE_SSL = False
+
 __all__ = ["IMAP4", "IMAP4_stream", "Internaldate2tuple",
            "Int2AP", "ParseFlags", "Time2Internaldate"]
 
@@ -71,6 +77,7 @@
         'SETANNOTATION':('AUTH', 'SELECTED'),
         'SETQUOTA':     ('AUTH', 'SELECTED'),
         'SORT':         ('SELECTED',),
+        'STARTTLS':     ('NONAUTH',),
         'STATUS':       ('AUTH', 'SELECTED'),
         'STORE':        ('SELECTED',),
         'SUBSCRIBE':    ('AUTH', 'SELECTED'),
@@ -156,11 +163,23 @@
         self.continuation_response = '' # Last continuation response
         self.is_readonly = False        # READ-ONLY desired state
         self.tagnum = 0
+        self._tls_established = False
 
         # Open socket to server.
 
         self.open(host, port)
 
+        try:
+            self._connect()
+        except Exception:
+            try:
+                self.shutdown()
+            except socket.error:
+                pass
+            raise
+
+
+    def _connect(self):
         # Create unique tag for this session,
         # and compile tagged response matcher.
 
@@ -188,13 +207,7 @@
         else:
             raise self.error(self.welcome)
 
-        typ, dat = self.capability()
-        if dat == [None]:
-            raise self.error('no CAPABILITY response from server')
-        dat = str(dat[-1], "ASCII")
-        dat = dat.upper()
-        self.capabilities = tuple(dat.split())
-
+        self._get_capabilities()
         if __debug__:
             if self.debug >= 3:
                 self._mesg('CAPABILITIES: %r' % (self.capabilities,))
@@ -711,6 +724,30 @@
         return self._untagged_response(typ, dat, name)
 
 
+    def starttls(self, ssl_context=None):
+        name = 'STARTTLS'
+        if not HAVE_SSL:
+            raise self.error('SSL support missing')
+        if self._tls_established:
+            raise self.abort('TLS session already established')
+        if name not in self.capabilities:
+            raise self.abort('TLS not supported by server')
+        # Generate a default SSL context if none was passed.
+        if ssl_context is None:
+            ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
+            # SSLv2 considered harmful.
+            ssl_context.options |= ssl.OP_NO_SSLv2
+        typ, dat = self._simple_command(name)
+        if typ == 'OK':
+            self.sock = ssl_context.wrap_socket(self.sock)
+            self.file = self.sock.makefile('rb')
+            self._tls_established = True
+            self._get_capabilities()
+        else:
+            raise self.error("Couldn't establish TLS session")
+        return self._untagged_response(typ, dat, name)
+
+
     def status(self, mailbox, names):
         """Request named status conditions for mailbox.
 
@@ -921,6 +958,15 @@
         return typ, data
 
 
+    def _get_capabilities(self):
+        typ, dat = self.capability()
+        if dat == [None]:
+            raise self.error('no CAPABILITY response from server')
+        dat = str(dat[-1], "ASCII")
+        dat = dat.upper()
+        self.capabilities = tuple(dat.split())
+
+
     def _get_response(self):
 
         # Read response and store.
@@ -1125,12 +1171,8 @@
                 n -= 1
 
 
+if HAVE_SSL:
 
-try:
-    import ssl
-except ImportError:
-    pass
-else:
     class IMAP4_SSL(IMAP4):
 
         """IMAP4 client class over SSL connection
@@ -1266,13 +1308,14 @@
 
 
 
-Mon2num = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
-        'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
+Mon2num = {b'Jan': 1, b'Feb': 2, b'Mar': 3, b'Apr': 4, b'May': 5, b'Jun': 6,
+           b'Jul': 7, b'Aug': 8, b'Sep': 9, b'Oct': 10, b'Nov': 11, b'Dec': 12}
 
 def Internaldate2tuple(resp):
-    """Convert IMAP4 INTERNALDATE to UT.
+    """Parse an IMAP4 INTERNALDATE string.
 
-    Returns Python time module tuple.
+    Return corresponding local time.  The return value is a
+    time.struct_time tuple or None if the string has wrong format.
     """
 
     mo = InternalDate.match(resp)
@@ -1293,7 +1336,7 @@
     # INTERNALDATE timezone must be subtracted to get UT
 
     zone = (zoneh*60 + zonem)*60
-    if zonen == '-':
+    if zonen == b'-':
         zone = -zone
 
     tt = (year, mon, day, hour, min, sec, -1, -1, -1)
@@ -1339,9 +1382,14 @@
 
 def Time2Internaldate(date_time):
 
-    """Convert 'date_time' to IMAP4 INTERNALDATE representation.
+    """Convert date_time to IMAP4 INTERNALDATE representation.
 
-    Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'
+    Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'.  The
+    date_time argument can be a number (int or float) represening
+    seconds since epoch (as returned by time.time()), a 9-tuple
+    representing local time (as returned by time.localtime()), or a
+    double-quoted string.  In the last case, it is assumed to already
+    be in the correct format.
     """
 
     if isinstance(date_time, (int, float)):

Modified: python/branches/pep-3151/Lib/importlib/_bootstrap.py
==============================================================================
--- python/branches/pep-3151/Lib/importlib/_bootstrap.py	(original)
+++ python/branches/pep-3151/Lib/importlib/_bootstrap.py	Sat Feb 26 08:16:32 2011
@@ -345,17 +345,17 @@
 
 class SourceLoader(_LoaderBasics):
 
-    def path_mtime(self, path:str) -> int:
-        """Optional method that returns the modification time for the specified
-        path.
+    def path_mtime(self, path):
+        """Optional method that returns the modification time (an int) for the
+        specified path, where path is a str.
 
         Implementing this method allows the loader to read bytecode files.
 
         """
         raise NotImplementedError
 
-    def set_data(self, path:str, data:bytes) -> None:
-        """Optional method which writes data to a file path.
+    def set_data(self, path, data):
+        """Optional method which writes data (bytes) to a file path (a str).
 
         Implementing this method allows for the writing of bytecode files.
 
@@ -758,6 +758,8 @@
 
 _IMPLICIT_META_PATH = [BuiltinImporter, FrozenImporter, _DefaultPathFinder]
 
+_ERR_MSG = 'No module named {}'
+
 def _gcd_import(name, package=None, level=0):
     """Import and return the module based on its name, the package the call is
     being made from, and the level adjustment.
@@ -808,8 +810,8 @@
             try:
                 path = parent_module.__path__
             except AttributeError:
-                raise ImportError("no module named {}; "
-                                    "{} is not a package".format(name, parent))
+                msg = (_ERR_MSG + '; {} is not a package').format(name, parent)
+                raise ImportError(msg)
         meta_path = sys.meta_path + _IMPLICIT_META_PATH
         for finder in meta_path:
             loader = finder.find_module(name, path)
@@ -817,7 +819,7 @@
                 loader.load_module(name)
                 break
         else:
-            raise ImportError("No module named {0}".format(name))
+            raise ImportError(_ERR_MSG.format(name))
         # Backwards-compatibility; be nicer to skip the dict lookup.
         module = sys.modules[name]
         if parent:

Modified: python/branches/pep-3151/Lib/importlib/abc.py
==============================================================================
--- python/branches/pep-3151/Lib/importlib/abc.py	(original)
+++ python/branches/pep-3151/Lib/importlib/abc.py	Sat Feb 26 08:16:32 2011
@@ -18,8 +18,9 @@
     """Abstract base class for import loaders."""
 
     @abc.abstractmethod
-    def load_module(self, fullname:str) -> types.ModuleType:
-        """Abstract method which when implemented should load a module."""
+    def load_module(self, fullname):
+        """Abstract method which when implemented should load a module.
+        The fullname is a str."""
         raise NotImplementedError
 
 
@@ -28,8 +29,11 @@
     """Abstract base class for import finders."""
 
     @abc.abstractmethod
-    def find_module(self, fullname:str, path:[str]=None) -> Loader:
-        """Abstract method which when implemented should find a module."""
+    def find_module(self, fullname, path=None):
+        """Abstract method which when implemented should find a module.
+        The fullname is a str and the optional path is a str or None.
+        Returns a Loader object.
+        """
         raise NotImplementedError
 
 Finder.register(machinery.BuiltinImporter)
@@ -47,9 +51,9 @@
     """
 
     @abc.abstractmethod
-    def get_data(self, path:str) -> bytes:
+    def get_data(self, path):
         """Abstract method which when implemented should return the bytes for
-        the specified path."""
+        the specified path.  The path must be a str."""
         raise NotImplementedError
 
 
@@ -63,21 +67,21 @@
     """
 
     @abc.abstractmethod
-    def is_package(self, fullname:str) -> bool:
+    def is_package(self, fullname):
         """Abstract method which when implemented should return whether the
-        module is a package."""
+        module is a package.  The fullname is a str.  Returns a bool."""
         raise NotImplementedError
 
     @abc.abstractmethod
-    def get_code(self, fullname:str) -> types.CodeType:
+    def get_code(self, fullname):
         """Abstract method which when implemented should return the code object
-        for the module"""
+        for the module.  The fullname is a str.  Returns a types.CodeType."""
         raise NotImplementedError
 
     @abc.abstractmethod
-    def get_source(self, fullname:str) -> str:
+    def get_source(self, fullname):
         """Abstract method which should return the source code for the
-        module."""
+        module.  The fullname is a str.  Returns a str."""
         raise NotImplementedError
 
 InspectLoader.register(machinery.BuiltinImporter)
@@ -94,7 +98,7 @@
     """
 
     @abc.abstractmethod
-    def get_filename(self, fullname:str) -> str:
+    def get_filename(self, fullname):
         """Abstract method which should return the value that __file__ is to be
         set to."""
         raise NotImplementedError
@@ -117,13 +121,15 @@
 
     """
 
-    def path_mtime(self, path:str) -> int:
-        """Return the modification time for the path."""
+    def path_mtime(self, path):
+        """Return the (int) modification time for the path (str)."""
         raise NotImplementedError
 
-    def set_data(self, path:str, data:bytes) -> None:
+    def set_data(self, path, data):
         """Write the bytes to the path (if possible).
 
+        Accepts a str path and data as bytes.
+
         Any needed intermediary directories are to be created. If for some
         reason the file cannot be written because of permissions, fail
         silently.
@@ -170,9 +176,9 @@
         raise NotImplementedError
 
     @abc.abstractmethod
-    def source_path(self, fullname:str) -> object:
-        """Abstract method which when implemented should return the path to the
-        source code for the module."""
+    def source_path(self, fullname):
+        """Abstract method.  Accepts a str module name and returns the path to
+        the source code for the module."""
         raise NotImplementedError
 
     def get_filename(self, fullname):
@@ -279,20 +285,20 @@
         return code_object
 
     @abc.abstractmethod
-    def source_mtime(self, fullname:str) -> int:
-        """Abstract method which when implemented should return the
+    def source_mtime(self, fullname):
+        """Abstract method. Accepts a str filename and returns an int
         modification time for the source of the module."""
         raise NotImplementedError
 
     @abc.abstractmethod
-    def bytecode_path(self, fullname:str) -> object:
-        """Abstract method which when implemented should return the path to the
-        bytecode for the module."""
+    def bytecode_path(self, fullname):
+        """Abstract method. Accepts a str filename and returns the str pathname
+        to the bytecode for the module."""
         raise NotImplementedError
 
     @abc.abstractmethod
-    def write_bytecode(self, fullname:str, bytecode:bytes) -> bool:
-        """Abstract method which when implemented should attempt to write the
-        bytecode for the module, returning a boolean representing whether the
-        bytecode was written or not."""
+    def write_bytecode(self, fullname, bytecode):
+        """Abstract method.  Accepts a str filename and bytes object
+        representing the bytecode for the module.  Returns a boolean
+        representing whether the bytecode was written or not."""
         raise NotImplementedError

Modified: python/branches/pep-3151/Lib/importlib/test/import_/test___package__.py
==============================================================================
--- python/branches/pep-3151/Lib/importlib/test/import_/test___package__.py	(original)
+++ python/branches/pep-3151/Lib/importlib/test/import_/test___package__.py	Sat Feb 26 08:16:32 2011
@@ -42,7 +42,7 @@
                 module = import_util.import_('',
                                             globals={'__package__': 'pkg.fake'},
                                             fromlist=['attr'], level=2)
-        self.assertEquals(module.__name__, 'pkg')
+        self.assertEqual(module.__name__, 'pkg')
 
     def test_using___name__(self, package_as_None=False):
         # [__name__]
@@ -54,7 +54,7 @@
                 import_util.import_('pkg.fake')
                 module = import_util.import_('', globals= globals_,
                                                 fromlist=['attr'], level=2)
-            self.assertEquals(module.__name__, 'pkg')
+            self.assertEqual(module.__name__, 'pkg')
 
     def test_None_as___package__(self):
         # [None]

Modified: python/branches/pep-3151/Lib/importlib/test/import_/test_caching.py
==============================================================================
--- python/branches/pep-3151/Lib/importlib/test/import_/test_caching.py	(original)
+++ python/branches/pep-3151/Lib/importlib/test/import_/test_caching.py	Sat Feb 26 08:16:32 2011
@@ -54,7 +54,7 @@
         with self.create_mock('module') as mock:
             with util.import_state(meta_path=[mock]):
                 module = import_util.import_('module')
-                self.assertEquals(id(module), id(sys.modules['module']))
+                self.assertEqual(id(module), id(sys.modules['module']))
 
     # See test_using_cache_after_loader() for reasoning.
     @import_util.importlib_only
@@ -74,8 +74,8 @@
             with util.import_state(meta_path=[importer]):
                 module = import_util.import_('pkg', fromlist=['module'])
                 self.assertTrue(hasattr(module, 'module'))
-                self.assertEquals(id(module.module),
-                                  id(sys.modules['pkg.module']))
+                self.assertEqual(id(module.module),
+                                 id(sys.modules['pkg.module']))
 
 
 def test_main():

Modified: python/branches/pep-3151/Lib/importlib/test/import_/test_fromlist.py
==============================================================================
--- python/branches/pep-3151/Lib/importlib/test/import_/test_fromlist.py	(original)
+++ python/branches/pep-3151/Lib/importlib/test/import_/test_fromlist.py	Sat Feb 26 08:16:32 2011
@@ -19,14 +19,14 @@
         with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
             with util.import_state(meta_path=[importer]):
                 module = import_util.import_('pkg.module')
-                self.assertEquals(module.__name__, 'pkg')
+                self.assertEqual(module.__name__, 'pkg')
 
     def test_return_from_from_import(self):
         # [from return]
         with util.mock_modules('pkg.__init__', 'pkg.module')as importer:
             with util.import_state(meta_path=[importer]):
                 module = import_util.import_('pkg.module', fromlist=['attr'])
-                self.assertEquals(module.__name__, 'pkg.module')
+                self.assertEqual(module.__name__, 'pkg.module')
 
 
 class HandlingFromlist(unittest.TestCase):
@@ -51,14 +51,14 @@
         with util.mock_modules('module') as importer:
             with util.import_state(meta_path=[importer]):
                 module = import_util.import_('module', fromlist=['attr'])
-                self.assertEquals(module.__name__, 'module')
+                self.assertEqual(module.__name__, 'module')
 
     def test_unexistent_object(self):
         # [bad object]
         with util.mock_modules('module') as importer:
             with util.import_state(meta_path=[importer]):
                 module = import_util.import_('module', fromlist=['non_existent'])
-                self.assertEquals(module.__name__, 'module')
+                self.assertEqual(module.__name__, 'module')
                 self.assertTrue(not hasattr(module, 'non_existent'))
 
     def test_module_from_package(self):
@@ -66,23 +66,23 @@
         with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
             with util.import_state(meta_path=[importer]):
                 module = import_util.import_('pkg', fromlist=['module'])
-                self.assertEquals(module.__name__, 'pkg')
+                self.assertEqual(module.__name__, 'pkg')
                 self.assertTrue(hasattr(module, 'module'))
-                self.assertEquals(module.module.__name__, 'pkg.module')
+                self.assertEqual(module.module.__name__, 'pkg.module')
 
     def test_no_module_from_package(self):
         # [no module]
         with util.mock_modules('pkg.__init__') as importer:
             with util.import_state(meta_path=[importer]):
                 module = import_util.import_('pkg', fromlist='non_existent')
-                self.assertEquals(module.__name__, 'pkg')
+                self.assertEqual(module.__name__, 'pkg')
                 self.assertTrue(not hasattr(module, 'non_existent'))
 
     def test_empty_string(self):
         with util.mock_modules('pkg.__init__', 'pkg.mod') as importer:
             with util.import_state(meta_path=[importer]):
                 module = import_util.import_('pkg.mod', fromlist=[''])
-                self.assertEquals(module.__name__, 'pkg.mod')
+                self.assertEqual(module.__name__, 'pkg.mod')
 
     def basic_star_test(self, fromlist=['*']):
         # [using *]
@@ -90,7 +90,7 @@
             with util.import_state(meta_path=[mock]):
                 mock['pkg'].__all__ = ['module']
                 module = import_util.import_('pkg', fromlist=fromlist)
-                self.assertEquals(module.__name__, 'pkg')
+                self.assertEqual(module.__name__, 'pkg')
                 self.assertTrue(hasattr(module, 'module'))
                 self.assertEqual(module.module.__name__, 'pkg.module')
 
@@ -108,11 +108,11 @@
             with util.import_state(meta_path=[mock]):
                 mock['pkg'].__all__ = ['module1']
                 module = import_util.import_('pkg', fromlist=['module2', '*'])
-                self.assertEquals(module.__name__, 'pkg')
+                self.assertEqual(module.__name__, 'pkg')
                 self.assertTrue(hasattr(module, 'module1'))
                 self.assertTrue(hasattr(module, 'module2'))
-                self.assertEquals(module.module1.__name__, 'pkg.module1')
-                self.assertEquals(module.module2.__name__, 'pkg.module2')
+                self.assertEqual(module.module1.__name__, 'pkg.module1')
+                self.assertEqual(module.module2.__name__, 'pkg.module2')
 
 
 def test_main():

Modified: python/branches/pep-3151/Lib/importlib/test/import_/test_meta_path.py
==============================================================================
--- python/branches/pep-3151/Lib/importlib/test/import_/test_meta_path.py	(original)
+++ python/branches/pep-3151/Lib/importlib/test/import_/test_meta_path.py	Sat Feb 26 08:16:32 2011
@@ -21,7 +21,7 @@
             first.modules[mod] = 42
             second.modules[mod] = -13
             with util.import_state(meta_path=[first, second]):
-                self.assertEquals(import_util.import_(mod), 42)
+                self.assertEqual(import_util.import_(mod), 42)
 
     def test_continuing(self):
         # [continuing]
@@ -31,7 +31,7 @@
             first.find_module = lambda self, fullname, path=None: None
             second.modules[mod_name] = 42
             with util.import_state(meta_path=[first, second]):
-                self.assertEquals(import_util.import_(mod_name), 42)
+                self.assertEqual(import_util.import_(mod_name), 42)
 
 
 class CallSignature(unittest.TestCase):
@@ -61,9 +61,9 @@
                 args = log[0][0]
                 kwargs = log[0][1]
                 # Assuming all arguments are positional.
-                self.assertEquals(len(args), 2)
-                self.assertEquals(len(kwargs), 0)
-                self.assertEquals(args[0], mod_name)
+                self.assertEqual(len(args), 2)
+                self.assertEqual(len(kwargs), 0)
+                self.assertEqual(args[0], mod_name)
                 self.assertTrue(args[1] is None)
 
     def test_with_path(self):
@@ -83,7 +83,7 @@
                 kwargs = log[1][1]
                 # Assuming all arguments are positional.
                 self.assertTrue(not kwargs)
-                self.assertEquals(args[0], mod_name)
+                self.assertEqual(args[0], mod_name)
                 self.assertTrue(args[1] is path)
 
 

Modified: python/branches/pep-3151/Lib/inspect.py
==============================================================================
--- python/branches/pep-3151/Lib/inspect.py	(original)
+++ python/branches/pep-3151/Lib/inspect.py	Sat Feb 26 08:16:32 2011
@@ -1054,3 +1054,100 @@
 def trace(context=1):
     """Return a list of records for the stack below the current exception."""
     return getinnerframes(sys.exc_info()[2], context)
+
+
+# ------------------------------------------------ static version of getattr
+
+_sentinel = object()
+
+def _static_getmro(klass):
+    return type.__dict__['__mro__'].__get__(klass)
+
+def _check_instance(obj, attr):
+    instance_dict = {}
+    try:
+        instance_dict = object.__getattribute__(obj, "__dict__")
+    except AttributeError:
+        pass
+    return instance_dict.get(attr, _sentinel)
+
+
+def _check_class(klass, attr):
+    for entry in _static_getmro(klass):
+        try:
+            return entry.__dict__[attr]
+        except KeyError:
+            pass
+    return _sentinel
+
+def _is_type(obj):
+    try:
+        _static_getmro(obj)
+    except TypeError:
+        return False
+    return True
+
+
+def getattr_static(obj, attr, default=_sentinel):
+    """Retrieve attributes without triggering dynamic lookup via the
+       descriptor protocol,  __getattr__ or __getattribute__.
+
+       Note: this function may not be able to retrieve all attributes
+       that getattr can fetch (like dynamically created attributes)
+       and may find attributes that getattr can't (like descriptors
+       that raise AttributeError). It can also return descriptor objects
+       instead of instance members in some cases. See the
+       documentation for details.
+    """
+    instance_result = _sentinel
+    if not _is_type(obj):
+        instance_result = _check_instance(obj, attr)
+        klass = type(obj)
+    else:
+        klass = obj
+
+    klass_result = _check_class(klass, attr)
+
+    if instance_result is not _sentinel and klass_result is not _sentinel:
+        if (_check_class(type(klass_result), '__get__') is not _sentinel and
+            _check_class(type(klass_result), '__set__') is not _sentinel):
+            return klass_result
+
+    if instance_result is not _sentinel:
+        return instance_result
+    if klass_result is not _sentinel:
+        return klass_result
+
+    if obj is klass:
+        # for types we check the metaclass too
+        for entry in _static_getmro(type(klass)):
+            try:
+                return entry.__dict__[attr]
+            except KeyError:
+                pass
+    if default is not _sentinel:
+        return default
+    raise AttributeError(attr)
+
+
+GEN_CREATED = 'GEN_CREATED'
+GEN_RUNNING = 'GEN_RUNNING'
+GEN_SUSPENDED = 'GEN_SUSPENDED'
+GEN_CLOSED = 'GEN_CLOSED'
+
+def getgeneratorstate(generator):
+    """Get current state of a generator-iterator.
+
+    Possible states are:
+      GEN_CREATED: Waiting to start execution.
+      GEN_RUNNING: Currently being executed by the interpreter.
+      GEN_SUSPENDED: Currently suspended at a yield expression.
+      GEN_CLOSED: Execution has completed.
+    """
+    if generator.gi_running:
+        return GEN_RUNNING
+    if generator.gi_frame is None:
+        return GEN_CLOSED
+    if generator.gi_frame.f_lasti == -1:
+        return GEN_CREATED
+    return GEN_SUSPENDED

Modified: python/branches/pep-3151/Lib/json/__init__.py
==============================================================================
--- python/branches/pep-3151/Lib/json/__init__.py	(original)
+++ python/branches/pep-3151/Lib/json/__init__.py	Sat Feb 26 08:16:32 2011
@@ -298,6 +298,8 @@
     To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
     kwarg; otherwise ``JSONDecoder`` is used.
 
+    The ``encoding`` argument is ignored and deprecated.
+
     """
     if (cls is None and object_hook is None and
             parse_int is None and parse_float is None and

Modified: python/branches/pep-3151/Lib/lib2to3/fixes/fix_urllib.py
==============================================================================
--- python/branches/pep-3151/Lib/lib2to3/fixes/fix_urllib.py	(original)
+++ python/branches/pep-3151/Lib/lib2to3/fixes/fix_urllib.py	Sat Feb 26 08:16:32 2011
@@ -12,7 +12,7 @@
 
 MAPPING = {"urllib":  [
                 ("urllib.request",
-                    ["URLOpener", "FancyURLOpener", "urlretrieve",
+                    ["URLopener", "FancyURLopener", "urlretrieve",
                      "_urlopener", "urlopen", "urlcleanup",
                      "pathname2url", "url2pathname"]),
                 ("urllib.parse",

Modified: python/branches/pep-3151/Lib/lib2to3/main.py
==============================================================================
--- python/branches/pep-3151/Lib/lib2to3/main.py	(original)
+++ python/branches/pep-3151/Lib/lib2to3/main.py	Sat Feb 26 08:16:32 2011
@@ -100,7 +100,7 @@
     parser.add_option("-j", "--processes", action="store", default=1,
                       type="int", help="Run 2to3 concurrently")
     parser.add_option("-x", "--nofix", action="append", default=[],
-                      help="Prevent a fixer from being run.")
+                      help="Prevent a transformation from being run")
     parser.add_option("-l", "--list-fixes", action="store_true",
                       help="List available transformations")
     parser.add_option("-p", "--print-function", action="store_true",
@@ -112,7 +112,7 @@
     parser.add_option("-w", "--write", action="store_true",
                       help="Write back modified files")
     parser.add_option("-n", "--nobackups", action="store_true", default=False,
-                      help="Don't write backups for modified files.")
+                      help="Don't write backups for modified files")
 
     # Parse command line arguments
     refactor_stdin = False

Modified: python/branches/pep-3151/Lib/lib2to3/refactor.py
==============================================================================
--- python/branches/pep-3151/Lib/lib2to3/refactor.py	(original)
+++ python/branches/pep-3151/Lib/lib2to3/refactor.py	Sat Feb 26 08:16:32 2011
@@ -302,13 +302,14 @@
 
         Files and subdirectories starting with '.' are skipped.
         """
+        py_ext = os.extsep + "py"
         for dirpath, dirnames, filenames in os.walk(dir_name):
             self.log_debug("Descending into %s", dirpath)
             dirnames.sort()
             filenames.sort()
             for name in filenames:
-                if not name.startswith(".") and \
-                        os.path.splitext(name)[1].endswith("py"):
+                if (not name.startswith(".") and
+                    os.path.splitext(name)[1] == py_ext):
                     fullname = os.path.join(dirpath, name)
                     self.refactor_file(fullname, write, doctests_only)
             # Modify dirnames in-place to remove subdirs with leading dots

Modified: python/branches/pep-3151/Lib/lib2to3/tests/test_refactor.py
==============================================================================
--- python/branches/pep-3151/Lib/lib2to3/tests/test_refactor.py	(original)
+++ python/branches/pep-3151/Lib/lib2to3/tests/test_refactor.py	Sat Feb 26 08:16:32 2011
@@ -223,6 +223,7 @@
                 "hi.py",
                 ".dumb",
                 ".after.py",
+                "notpy.npy",
                 "sappy"]
         expected = ["hi.py"]
         check(tree, expected)

Modified: python/branches/pep-3151/Lib/lib2to3/tests/test_util.py
==============================================================================
--- python/branches/pep-3151/Lib/lib2to3/tests/test_util.py	(original)
+++ python/branches/pep-3151/Lib/lib2to3/tests/test_util.py	Sat Feb 26 08:16:32 2011
@@ -568,8 +568,8 @@
 
     def test_from_import(self):
         node = parse('bar()')
-        fixer_util.touch_import("cgi", "escape", node)
-        self.assertEqual(str(node), 'from cgi import escape\nbar()\n\n')
+        fixer_util.touch_import("html", "escape", node)
+        self.assertEqual(str(node), 'from html import escape\nbar()\n\n')
 
     def test_name_import(self):
         node = parse('bar()')

Modified: python/branches/pep-3151/Lib/logging/__init__.py
==============================================================================
--- python/branches/pep-3151/Lib/logging/__init__.py	(original)
+++ python/branches/pep-3151/Lib/logging/__init__.py	Sat Feb 26 08:16:32 2011
@@ -33,7 +33,7 @@
            'captureWarnings', 'critical', 'debug', 'disable', 'error',
            'exception', 'fatal', 'getLevelName', 'getLogger', 'getLoggerClass',
            'info', 'log', 'makeLogRecord', 'setLoggerClass', 'warn', 'warning',
-           'getLogRecordClass', 'setLogRecordClass']
+           'getLogRecordFactory', 'setLogRecordFactory', 'lastResort']
 
 try:
     import codecs
@@ -238,7 +238,7 @@
     information to be logged.
     """
     def __init__(self, name, level, pathname, lineno,
-                 msg, args, exc_info, func=None):
+                 msg, args, exc_info, func=None, sinfo=None, **kwargs):
         """
         Initialize a logging record with interesting information.
         """
@@ -272,6 +272,7 @@
             self.module = "Unknown module"
         self.exc_info = exc_info
         self.exc_text = None      # used to cache the traceback text
+        self.stack_info = sinfo
         self.lineno = lineno
         self.funcName = func
         self.created = ct
@@ -321,21 +322,24 @@
 #
 #   Determine which class to use when instantiating log records.
 #
-_logRecordClass = LogRecord
+_logRecordFactory = LogRecord
 
-def setLogRecordClass(cls):
+def setLogRecordFactory(factory):
     """
-    Set the class to be used when instantiating a log record.
+    Set the factory to be used when instantiating a log record.
+
+    :param factory: A callable which will be called to instantiate
+    a log record.
     """
-    global _logRecordClass
-    _logRecordClass = cls
+    global _logRecordFactory
+    _logRecordFactory = factory
 
-def getLogRecordClass():
+def getLogRecordFactory():
     """
-    Return the class to be used when instantiating a log record.
+    Return the factory to be used when instantiating a log record.
     """
 
-    return _logRecordClass
+    return _logRecordFactory
 
 def makeLogRecord(dict):
     """
@@ -344,7 +348,7 @@
     a socket connection (which is sent as a dictionary) into a LogRecord
     instance.
     """
-    rv = _logRecordClass(None, None, "", 0, "", (), None, None)
+    rv = _logRecordFactory(None, None, "", 0, "", (), None, None)
     rv.__dict__.update(dict)
     return rv
 
@@ -515,6 +519,19 @@
     def formatMessage(self, record):
         return self._style.format(record)
 
+    def formatStack(self, stack_info):
+        """
+        This method is provided as an extension point for specialized
+        formatting of stack information.
+
+        The input data is a string as returned from a call to
+        :func:`traceback.print_stack`, but with the last trailing newline
+        removed.
+
+        The base implementation just returns the value passed in.
+        """
+        return stack_info
+
     def format(self, record):
         """
         Format the specified record as text.
@@ -541,6 +558,10 @@
             if s[-1:] != "\n":
                 s = s + "\n"
             s = s + record.exc_text
+        if record.stack_info:
+            if s[-1:] != "\n":
+                s = s + "\n"
+            s = s + self.formatStack(record.stack_info)
         return s
 
 #
@@ -976,6 +997,26 @@
             self.stream = self._open()
         StreamHandler.emit(self, record)
 
+class _StderrHandler(StreamHandler):
+    """
+    This class is like a StreamHandler using sys.stderr, but always uses
+    whatever sys.stderr is currently set to rather than the value of
+    sys.stderr at handler construction time.
+    """
+    def __init__(self, level=NOTSET):
+        """
+        Initialize the handler.
+        """
+        Handler.__init__(self, level)
+
+    @property
+    def stream(self):
+        return sys.stderr
+
+
+_defaultLastResort = _StderrHandler(WARNING)
+lastResort = _defaultLastResort
+
 #---------------------------------------------------------------------------
 #   Manager classes and functions
 #---------------------------------------------------------------------------
@@ -1035,10 +1076,10 @@
         """
         self.root = rootnode
         self.disable = 0
-        self.emittedNoHandlerWarning = 0
+        self.emittedNoHandlerWarning = False
         self.loggerDict = {}
         self.loggerClass = None
-        self.logRecordClass = None
+        self.logRecordFactory = None
 
     def getLogger(self, name):
         """
@@ -1082,12 +1123,12 @@
                                 + klass.__name__)
         self.loggerClass = klass
 
-    def setLogRecordClass(self, cls):
+    def setLogRecordFactory(self, factory):
         """
-        Set the class to be used when instantiating a log record with this
+        Set the factory to be used when instantiating a log record with this
         Manager.
         """
-        self.logRecordClass = cls
+        self.logRecordFactory = factory
 
     def _fixupParents(self, alogger):
         """
@@ -1213,11 +1254,12 @@
         if self.isEnabledFor(ERROR):
             self._log(ERROR, msg, args, **kwargs)
 
-    def exception(self, msg, *args):
+    def exception(self, msg, *args, **kwargs):
         """
         Convenience method for logging an ERROR with exception information.
         """
-        self.error(msg, exc_info=1, *args)
+        kwargs['exc_info'] = True
+        self.error(msg, *args, **kwargs)
 
     def critical(self, msg, *args, **kwargs):
         """
@@ -1250,7 +1292,7 @@
         if self.isEnabledFor(level):
             self._log(level, msg, args, **kwargs)
 
-    def findCaller(self):
+    def findCaller(self, stack_info=False):
         """
         Find the stack frame of the caller so that we can note the source
         file name, line number and function name.
@@ -1260,23 +1302,34 @@
         #IronPython isn't run with -X:Frames.
         if f is not None:
             f = f.f_back
-        rv = "(unknown file)", 0, "(unknown function)"
+        rv = "(unknown file)", 0, "(unknown function)", None
         while hasattr(f, "f_code"):
             co = f.f_code
             filename = os.path.normcase(co.co_filename)
             if filename == _srcfile:
                 f = f.f_back
                 continue
-            rv = (co.co_filename, f.f_lineno, co.co_name)
+            sinfo = None
+            if stack_info:
+                sio = io.StringIO()
+                sio.write('Stack (most recent call last):\n')
+                traceback.print_stack(f, file=sio)
+                sinfo = sio.getvalue()
+                if sinfo[-1] == '\n':
+                    sinfo = sinfo[:-1]
+                sio.close()
+            rv = (co.co_filename, f.f_lineno, co.co_name, sinfo)
             break
         return rv
 
-    def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None):
+    def makeRecord(self, name, level, fn, lno, msg, args, exc_info,
+                   func=None, extra=None, sinfo=None):
         """
         A factory method which can be overridden in subclasses to create
         specialized LogRecords.
         """
-        rv = _logRecordClass(name, level, fn, lno, msg, args, exc_info, func)
+        rv = _logRecordFactory(name, level, fn, lno, msg, args, exc_info, func,
+                             sinfo)
         if extra is not None:
             for key in extra:
                 if (key in ["message", "asctime"]) or (key in rv.__dict__):
@@ -1284,17 +1337,18 @@
                 rv.__dict__[key] = extra[key]
         return rv
 
-    def _log(self, level, msg, args, exc_info=None, extra=None):
+    def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False):
         """
         Low-level logging routine which creates a LogRecord and then calls
         all the handlers of this logger to handle the record.
         """
+        sinfo = None
         if _srcfile:
             #IronPython doesn't track Python frames, so findCaller throws an
             #exception on some versions of IronPython. We trap it here so that
             #IronPython can use logging.
             try:
-                fn, lno, func = self.findCaller()
+                fn, lno, func, sinfo = self.findCaller(stack_info)
             except ValueError:
                 fn, lno, func = "(unknown file)", 0, "(unknown function)"
         else:
@@ -1302,7 +1356,8 @@
         if exc_info:
             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)
+        record = self.makeRecord(self.name, level, fn, lno, msg, args,
+                                 exc_info, func, extra, sinfo)
         self.handle(record)
 
     def handle(self, record):
@@ -1380,10 +1435,13 @@
                 c = None    #break out
             else:
                 c = c.parent
-        if (found == 0) and raiseExceptions and not self.manager.emittedNoHandlerWarning:
-            sys.stderr.write("No handlers could be found for logger"
-                             " \"%s\"\n" % self.name)
-            self.manager.emittedNoHandlerWarning = 1
+        if (found == 0):
+            if lastResort:
+                lastResort.handle(record)
+            elif raiseExceptions and not self.manager.emittedNoHandlerWarning:
+                sys.stderr.write("No handlers could be found for logger"
+                                 " \"%s\"\n" % self.name)
+                self.manager.emittedNoHandlerWarning = True
 
     def getEffectiveLevel(self):
         """
@@ -1641,7 +1699,9 @@
 
 def critical(msg, *args, **kwargs):
     """
-    Log a message with severity 'CRITICAL' on the root logger.
+    Log a message with severity 'CRITICAL' on the root logger. If the logger
+    has no handlers, call basicConfig() to add a console handler with a
+    pre-defined format.
     """
     if len(root.handlers) == 0:
         basicConfig()
@@ -1651,22 +1711,28 @@
 
 def error(msg, *args, **kwargs):
     """
-    Log a message with severity 'ERROR' on the root logger.
+    Log a message with severity 'ERROR' on the root logger. If the logger has
+    no handlers, call basicConfig() to add a console handler with a pre-defined
+    format.
     """
     if len(root.handlers) == 0:
         basicConfig()
     root.error(msg, *args, **kwargs)
 
-def exception(msg, *args):
+def exception(msg, *args, **kwargs):
     """
-    Log a message with severity 'ERROR' on the root logger,
-    with exception information.
+    Log a message with severity 'ERROR' on the root logger, with exception
+    information. If the logger has no handlers, basicConfig() is called to add
+    a console handler with a pre-defined format.
     """
-    error(msg, exc_info=1, *args)
+    kwargs['exc_info'] = True
+    error(msg, *args, **kwargs)
 
 def warning(msg, *args, **kwargs):
     """
-    Log a message with severity 'WARNING' on the root logger.
+    Log a message with severity 'WARNING' on the root logger. If the logger has
+    no handlers, call basicConfig() to add a console handler with a pre-defined
+    format.
     """
     if len(root.handlers) == 0:
         basicConfig()
@@ -1676,7 +1742,9 @@
 
 def info(msg, *args, **kwargs):
     """
-    Log a message with severity 'INFO' on the root logger.
+    Log a message with severity 'INFO' on the root logger. If the logger has
+    no handlers, call basicConfig() to add a console handler with a pre-defined
+    format.
     """
     if len(root.handlers) == 0:
         basicConfig()
@@ -1684,7 +1752,9 @@
 
 def debug(msg, *args, **kwargs):
     """
-    Log a message with severity 'DEBUG' on the root logger.
+    Log a message with severity 'DEBUG' on the root logger. If the logger has
+    no handlers, call basicConfig() to add a console handler with a pre-defined
+    format.
     """
     if len(root.handlers) == 0:
         basicConfig()
@@ -1692,7 +1762,9 @@
 
 def log(level, msg, *args, **kwargs):
     """
-    Log 'msg % args' with the integer severity 'level' on the root logger.
+    Log 'msg % args' with the integer severity 'level' on the root logger. If
+    the logger has no handlers, call basicConfig() to add a console handler
+    with a pre-defined format.
     """
     if len(root.handlers) == 0:
         basicConfig()

Modified: python/branches/pep-3151/Lib/logging/handlers.py
==============================================================================
--- python/branches/pep-3151/Lib/logging/handlers.py	(original)
+++ python/branches/pep-3151/Lib/logging/handlers.py	Sat Feb 26 08:16:32 2011
@@ -120,6 +120,7 @@
         """
         if self.stream:
             self.stream.close()
+            self.stream = None
         if self.backupCount > 0:
             for i in range(self.backupCount - 1, 0, -1):
                 sfn = "%s.%d" % (self.baseFilename, i)
@@ -316,6 +317,7 @@
         """
         if self.stream:
             self.stream.close()
+            self.stream = None
         # get the time that this sequence started at and make it a TimeTuple
         t = self.rolloverAt - self.interval
         if self.utc:
@@ -1305,6 +1307,16 @@
             except queue.Empty:
                 break
 
+    def enqueue_sentinel(self):
+        """
+        This is used to enqueue the sentinel record.
+
+        The base implementation uses put_nowait. You may want to override this
+        method if you want to use timeouts or work with custom queue
+        implementations.
+        """
+        self.queue.put_nowait(self._sentinel)
+
     def stop(self):
         """
         Stop the listener.
@@ -1314,6 +1326,6 @@
         may be some records still left on the queue, which won't be processed.
         """
         self._stop.set()
-        self.queue.put_nowait(self._sentinel)
+        self.enqueue_sentinel()
         self._thread.join()
         self._thread = None

Modified: python/branches/pep-3151/Lib/mailbox.py
==============================================================================
--- python/branches/pep-3151/Lib/mailbox.py	(original)
+++ python/branches/pep-3151/Lib/mailbox.py	Sat Feb 26 08:16:32 2011
@@ -15,6 +15,7 @@
 import socket
 import errno
 import copy
+import warnings
 import email
 import email.message
 import email.generator
@@ -31,6 +32,8 @@
             'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage',
             'BabylMessage', 'MMDFMessage']
 
+linesep = os.linesep.encode('ascii')
+
 class Mailbox:
     """A group of messages in a particular place."""
 
@@ -80,7 +83,14 @@
         raise NotImplementedError('Method must be implemented by subclass')
 
     def get_string(self, key):
-        """Return a string representation or raise a KeyError."""
+        """Return a string representation or raise a KeyError.
+
+        Uses email.message.Message to create a 7bit clean string
+        representation of the message."""
+        return email.message_from_bytes(self.get_bytes(key)).as_string()
+
+    def get_bytes(self, key):
+        """Return a byte string representation or raise a KeyError."""
         raise NotImplementedError('Method must be implemented by subclass')
 
     def get_file(self, key):
@@ -186,31 +196,55 @@
         """Flush and close the mailbox."""
         raise NotImplementedError('Method must be implemented by subclass')
 
+    def _string_to_bytes(self, message):
+        # If a message is not 7bit clean, we refuse to handle it since it
+        # likely came from reading invalid messages in text mode, and that way
+        # lies mojibake.
+        try:
+            return message.encode('ascii')
+        except UnicodeError:
+            raise ValueError("String input must be ASCII-only; "
+                "use bytes or a Message instead")
+
     def _dump_message(self, message, target, mangle_from_=False):
-        # This assumes the target file is open in *text* mode with the
-        # desired encoding and newline setting.
+        # This assumes the target file is open in binary mode.
         """Dump message contents to target file."""
         if isinstance(message, email.message.Message):
-            buffer = io.StringIO()
-            gen = email.generator.Generator(buffer, mangle_from_, 0)
+            buffer = io.BytesIO()
+            gen = email.generator.BytesGenerator(buffer, mangle_from_, 0)
             gen.flatten(message)
             buffer.seek(0)
             data = buffer.read()
-            ##data = data.replace('\n', os.linesep)
+            data = data.replace(b'\n', linesep)
             target.write(data)
-        elif isinstance(message, str):
+        elif isinstance(message, (str, bytes, io.StringIO)):
+            if isinstance(message, io.StringIO):
+                warnings.warn("Use of StringIO input is deprecated, "
+                    "use BytesIO instead", DeprecationWarning, 3)
+                message = message.getvalue()
+            if isinstance(message, str):
+                message = self._string_to_bytes(message)
             if mangle_from_:
-                message = message.replace('\nFrom ', '\n>From ')
-            ##message = message.replace('\n', os.linesep)
+                message = message.replace(b'\nFrom ', b'\n>From ')
+            message = message.replace(b'\n', linesep)
             target.write(message)
         elif hasattr(message, 'read'):
+            if hasattr(message, 'buffer'):
+                warnings.warn("Use of text mode files is deprecated, "
+                    "use a binary mode file instead", DeprecationWarning, 3)
+                message = message.buffer
             while True:
                 line = message.readline()
+                # Universal newline support.
+                if line.endswith(b'\r\n'):
+                    line = line[:-2] + b'\n'
+                elif line.endswith(b'\r'):
+                    line = line[:-1] + b'\n'
                 if not line:
                     break
-                if mangle_from_ and line.startswith('From '):
-                    line = '>From ' + line[5:]
-                ##line = line.replace('\n', os.linesep)
+                if mangle_from_ and line.startswith(b'From '):
+                    line = b'>From ' + line[5:]
+                line = line.replace(b'\n', linesep)
                 target.write(line)
         else:
             raise TypeError('Invalid message type: %s' % type(message))
@@ -243,8 +277,11 @@
         tmp_file = self._create_tmp()
         try:
             self._dump_message(message, tmp_file)
-        finally:
-            _sync_close(tmp_file)
+        except BaseException:
+            tmp_file.close()
+            os.remove(tmp_file.name)
+            raise
+        _sync_close(tmp_file)
         if isinstance(message, MaildirMessage):
             subdir = message.get_subdir()
             suffix = self.colon + message.get_info()
@@ -319,7 +356,7 @@
     def get_message(self, key):
         """Return a Message representation or raise a KeyError."""
         subpath = self._lookup(key)
-        f = open(os.path.join(self._path, subpath), 'r', newline='')
+        f = open(os.path.join(self._path, subpath), 'rb')
         try:
             if self._factory:
                 msg = self._factory(f)
@@ -334,17 +371,17 @@
         msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
         return msg
 
-    def get_string(self, key):
-        """Return a string representation or raise a KeyError."""
-        f = open(os.path.join(self._path, self._lookup(key)), 'r', newline='')
+    def get_bytes(self, key):
+        """Return a bytes representation or raise a KeyError."""
+        f = open(os.path.join(self._path, self._lookup(key)), 'rb')
         try:
-            return f.read()
+            return f.read().replace(linesep, b'\n')
         finally:
             f.close()
 
     def get_file(self, key):
         """Return a file-like representation or raise a KeyError."""
-        f = open(os.path.join(self._path, self._lookup(key)), 'r', newline='')
+        f = open(os.path.join(self._path, self._lookup(key)), 'rb')
         return _ProxyFile(f)
 
     def iterkeys(self):
@@ -534,15 +571,15 @@
         """Initialize a single-file mailbox."""
         Mailbox.__init__(self, path, factory, create)
         try:
-            f = open(self._path, 'r+', newline='')
+            f = open(self._path, 'rb+')
         except IOError as e:
             if e.errno == errno.ENOENT:
                 if create:
-                    f = open(self._path, 'w+', newline='')
+                    f = open(self._path, 'wb+')
                 else:
                     raise NoSuchMailboxError(self._path)
             elif e.errno == errno.EACCES:
-                f = open(self._path, 'r', newline='')
+                f = open(self._path, 'rb')
             else:
                 raise
         self._file = f
@@ -690,9 +727,14 @@
     def _append_message(self, message):
         """Append message to mailbox and return (start, stop) offsets."""
         self._file.seek(0, 2)
-        self._pre_message_hook(self._file)
-        offsets = self._install_message(message)
-        self._post_message_hook(self._file)
+        before = self._file.tell()
+        try:
+            self._pre_message_hook(self._file)
+            offsets = self._install_message(message)
+            self._post_message_hook(self._file)
+        except BaseException:
+            self._file.truncate(before)
+            raise
         self._file.flush()
         self._file_length = self._file.tell()  # Record current length of mailbox
         return offsets
@@ -708,20 +750,25 @@
         """Return a Message representation or raise a KeyError."""
         start, stop = self._lookup(key)
         self._file.seek(start)
-        from_line = self._file.readline().replace(os.linesep, '')
+        from_line = self._file.readline().replace(linesep, b'')
         string = self._file.read(stop - self._file.tell())
-        msg = self._message_factory(string.replace(os.linesep, '\n'))
-        msg.set_from(from_line[5:])
+        msg = self._message_factory(string.replace(linesep, b'\n'))
+        msg.set_from(from_line[5:].decode('ascii'))
         return msg
 
     def get_string(self, key, from_=False):
         """Return a string representation or raise a KeyError."""
+        return email.message_from_bytes(
+            self.get_bytes(key)).as_string(unixfrom=from_)
+
+    def get_bytes(self, key, from_=False):
+        """Return a string representation or raise a KeyError."""
         start, stop = self._lookup(key)
         self._file.seek(start)
         if not from_:
             self._file.readline()
         string = self._file.read(stop - self._file.tell())
-        return string.replace(os.linesep, '\n')
+        return string.replace(linesep, b'\n')
 
     def get_file(self, key, from_=False):
         """Return a file-like representation or raise a KeyError."""
@@ -734,22 +781,27 @@
     def _install_message(self, message):
         """Format a message and blindly write to self._file."""
         from_line = None
-        if isinstance(message, str) and message.startswith('From '):
-            newline = message.find('\n')
+        if isinstance(message, str):
+            message = self._string_to_bytes(message)
+        if isinstance(message, bytes) and message.startswith(b'From '):
+            newline = message.find(b'\n')
             if newline != -1:
                 from_line = message[:newline]
                 message = message[newline + 1:]
             else:
                 from_line = message
-                message = ''
+                message = b''
         elif isinstance(message, _mboxMMDFMessage):
-            from_line = 'From ' + message.get_from()
+            author = message.get_from().encode('ascii')
+            from_line = b'From ' + author
         elif isinstance(message, email.message.Message):
             from_line = message.get_unixfrom()  # May be None.
+            if from_line is not None:
+                from_line = from_line.encode('ascii')
         if from_line is None:
-            from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
+            from_line = b'From MAILER-DAEMON ' + time.asctime(time.gmtime()).encode()
         start = self._file.tell()
-        self._file.write(from_line + os.linesep)
+        self._file.write(from_line + linesep)
         self._dump_message(message, self._file, self._mangle_from_)
         stop = self._file.tell()
         return (start, stop)
@@ -768,7 +820,7 @@
     def _pre_message_hook(self, f):
         """Called before writing each message to file f."""
         if f.tell() != 0:
-            f.write(os.linesep)
+            f.write(linesep)
 
     def _generate_toc(self):
         """Generate key-to-(start, stop) table of contents."""
@@ -777,9 +829,9 @@
         while True:
             line_pos = self._file.tell()
             line = self._file.readline()
-            if line.startswith('From '):
+            if line.startswith(b'From '):
                 if len(stops) < len(starts):
-                    stops.append(line_pos - len(os.linesep))
+                    stops.append(line_pos - len(linesep))
                 starts.append(line_pos)
             elif not line:
                 stops.append(line_pos)
@@ -799,11 +851,11 @@
 
     def _pre_message_hook(self, f):
         """Called before writing each message to file f."""
-        f.write('\001\001\001\001' + os.linesep)
+        f.write(b'\001\001\001\001' + linesep)
 
     def _post_message_hook(self, f):
         """Called after writing each message to file f."""
-        f.write(os.linesep + '\001\001\001\001' + os.linesep)
+        f.write(linesep + b'\001\001\001\001' + linesep)
 
     def _generate_toc(self):
         """Generate key-to-(start, stop) table of contents."""
@@ -814,14 +866,14 @@
             line_pos = next_pos
             line = self._file.readline()
             next_pos = self._file.tell()
-            if line.startswith('\001\001\001\001' + os.linesep):
+            if line.startswith(b'\001\001\001\001' + linesep):
                 starts.append(next_pos)
                 while True:
                     line_pos = next_pos
                     line = self._file.readline()
                     next_pos = self._file.tell()
-                    if line == '\001\001\001\001' + os.linesep:
-                        stops.append(line_pos - len(os.linesep))
+                    if line == b'\001\001\001\001' + linesep:
+                        stops.append(line_pos - len(linesep))
                         break
                     elif not line:
                         stops.append(line_pos)
@@ -858,18 +910,29 @@
             new_key = max(keys) + 1
         new_path = os.path.join(self._path, str(new_key))
         f = _create_carefully(new_path)
+        closed = False
         try:
             if self._locked:
                 _lock_file(f)
             try:
-                self._dump_message(message, f)
+                try:
+                    self._dump_message(message, f)
+                except BaseException:
+                    # Unlock and close so it can be deleted on Windows
+                    if self._locked:
+                        _unlock_file(f)
+                    _sync_close(f)
+                    closed = True
+                    os.remove(new_path)
+                    raise
                 if isinstance(message, MHMessage):
                     self._dump_sequences(message, new_key)
             finally:
                 if self._locked:
                     _unlock_file(f)
         finally:
-            _sync_close(f)
+            if not closed:
+                _sync_close(f)
         return new_key
 
     def remove(self, key):
@@ -890,7 +953,7 @@
         """Replace the keyed message; raise KeyError if it doesn't exist."""
         path = os.path.join(self._path, str(key))
         try:
-            f = open(path, 'r+', newline='')
+            f = open(path, 'rb+')
         except IOError as e:
             if e.errno == errno.ENOENT:
                 raise KeyError('No message with key: %s' % key)
@@ -914,9 +977,9 @@
         """Return a Message representation or raise a KeyError."""
         try:
             if self._locked:
-                f = open(os.path.join(self._path, str(key)), 'r+', newline='')
+                f = open(os.path.join(self._path, str(key)), 'rb+')
             else:
-                f = open(os.path.join(self._path, str(key)), 'r', newline='')
+                f = open(os.path.join(self._path, str(key)), 'rb')
         except IOError as e:
             if e.errno == errno.ENOENT:
                 raise KeyError('No message with key: %s' % key)
@@ -937,13 +1000,13 @@
                 msg.add_sequence(name)
         return msg
 
-    def get_string(self, key):
-        """Return a string representation or raise a KeyError."""
+    def get_bytes(self, key):
+        """Return a bytes representation or raise a KeyError."""
         try:
             if self._locked:
-                f = open(os.path.join(self._path, str(key)), 'r+', newline='')
+                f = open(os.path.join(self._path, str(key)), 'rb+')
             else:
-                f = open(os.path.join(self._path, str(key)), 'r', newline='')
+                f = open(os.path.join(self._path, str(key)), 'rb')
         except IOError as e:
             if e.errno == errno.ENOENT:
                 raise KeyError('No message with key: %s' % key)
@@ -953,7 +1016,7 @@
             if self._locked:
                 _lock_file(f)
             try:
-                return f.read()
+                return f.read().replace(linesep, b'\n')
             finally:
                 if self._locked:
                     _unlock_file(f)
@@ -963,7 +1026,7 @@
     def get_file(self, key):
         """Return a file-like representation or raise a KeyError."""
         try:
-            f = open(os.path.join(self._path, str(key)), 'r', newline='')
+            f = open(os.path.join(self._path, str(key)), 'rb')
         except IOError as e:
             if e.errno == errno.ENOENT:
                 raise KeyError('No message with key: %s' % key)
@@ -1041,7 +1104,7 @@
     def get_sequences(self):
         """Return a name-to-key-list dictionary to define each sequence."""
         results = {}
-        f = open(os.path.join(self._path, '.mh_sequences'), 'r', newline='')
+        f = open(os.path.join(self._path, '.mh_sequences'), 'r')
         try:
             all_keys = set(self.keys())
             for line in f:
@@ -1067,13 +1130,13 @@
 
     def set_sequences(self, sequences):
         """Set sequences using the given name-to-key-list dictionary."""
-        f = open(os.path.join(self._path, '.mh_sequences'), 'r+', newline='')
+        f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
         try:
             os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
             for name, keys in sequences.items():
                 if len(keys) == 0:
                     continue
-                f.write('%s:' % name)
+                f.write(name + ':')
                 prev = None
                 completing = False
                 for key in sorted(set(keys)):
@@ -1168,50 +1231,55 @@
         """Return a Message representation or raise a KeyError."""
         start, stop = self._lookup(key)
         self._file.seek(start)
-        self._file.readline()   # Skip '1,' line specifying labels.
-        original_headers = io.StringIO()
+        self._file.readline()   # Skip b'1,' line specifying labels.
+        original_headers = io.BytesIO()
         while True:
             line = self._file.readline()
-            if line == '*** EOOH ***' + os.linesep or not line:
+            if line == b'*** EOOH ***' + linesep or not line:
                 break
-            original_headers.write(line.replace(os.linesep, '\n'))
-        visible_headers = io.StringIO()
+            original_headers.write(line.replace(linesep, b'\n'))
+        visible_headers = io.BytesIO()
         while True:
             line = self._file.readline()
-            if line == os.linesep or not line:
+            if line == linesep or not line:
                 break
-            visible_headers.write(line.replace(os.linesep, '\n'))
-        body = self._file.read(stop - self._file.tell()).replace(os.linesep,
-                                                                 '\n')
+            visible_headers.write(line.replace(linesep, b'\n'))
+        # Read up to the stop, or to the end
+        n = stop - self._file.tell()
+        assert n >= 0
+        body = self._file.read(n)
+        body = body.replace(linesep, b'\n')
         msg = BabylMessage(original_headers.getvalue() + body)
         msg.set_visible(visible_headers.getvalue())
         if key in self._labels:
             msg.set_labels(self._labels[key])
         return msg
 
-    def get_string(self, key):
+    def get_bytes(self, key):
         """Return a string representation or raise a KeyError."""
         start, stop = self._lookup(key)
         self._file.seek(start)
-        self._file.readline()   # Skip '1,' line specifying labels.
-        original_headers = io.StringIO()
+        self._file.readline()   # Skip b'1,' line specifying labels.
+        original_headers = io.BytesIO()
         while True:
             line = self._file.readline()
-            if line == '*** EOOH ***' + os.linesep or not line:
+            if line == b'*** EOOH ***' + linesep or not line:
                 break
-            original_headers.write(line.replace(os.linesep, '\n'))
+            original_headers.write(line.replace(linesep, b'\n'))
         while True:
             line = self._file.readline()
-            if line == os.linesep or not line:
+            if line == linesep or not line:
                 break
-        return original_headers.getvalue() + \
-               self._file.read(stop - self._file.tell()).replace(os.linesep,
-                                                                 '\n')
+        headers = original_headers.getvalue()
+        n = stop - self._file.tell()
+        assert n >= 0
+        data = self._file.read(n)
+        data = data.replace(linesep, b'\n')
+        return headers + data
 
     def get_file(self, key):
         """Return a file-like representation or raise a KeyError."""
-        return io.StringIO(self.get_string(key).replace('\n',
-                                                              os.linesep))
+        return io.BytesIO(self.get_bytes(key).replace(b'\n', linesep))
 
     def get_labels(self):
         """Return a list of user-defined labels in the mailbox."""
@@ -1232,19 +1300,19 @@
             line_pos = next_pos
             line = self._file.readline()
             next_pos = self._file.tell()
-            if line == '\037\014' + os.linesep:
+            if line == b'\037\014' + linesep:
                 if len(stops) < len(starts):
-                    stops.append(line_pos - len(os.linesep))
+                    stops.append(line_pos - len(linesep))
                 starts.append(next_pos)
                 labels = [label.strip() for label
-                                        in self._file.readline()[1:].split(',')
+                                        in self._file.readline()[1:].split(b',')
                                         if label.strip()]
                 label_lists.append(labels)
-            elif line == '\037' or line == '\037' + os.linesep:
+            elif line == b'\037' or line == b'\037' + linesep:
                 if len(stops) < len(starts):
-                    stops.append(line_pos - len(os.linesep))
+                    stops.append(line_pos - len(linesep))
             elif not line:
-                stops.append(line_pos - len(os.linesep))
+                stops.append(line_pos - len(linesep))
                 break
         self._toc = dict(enumerate(zip(starts, stops)))
         self._labels = dict(enumerate(label_lists))
@@ -1254,17 +1322,21 @@
 
     def _pre_mailbox_hook(self, f):
         """Called before writing the mailbox to file f."""
-        f.write('BABYL OPTIONS:%sVersion: 5%sLabels:%s%s\037' %
-                (os.linesep, os.linesep, ','.join(self.get_labels()),
-                 os.linesep))
+        babyl = b'BABYL OPTIONS:' + linesep
+        babyl += b'Version: 5' + linesep
+        labels = self.get_labels()
+        labels = (label.encode() for label in labels)
+        babyl += b'Labels:' + b','.join(labels) + linesep
+        babyl += b'\037'
+        f.write(babyl)
 
     def _pre_message_hook(self, f):
         """Called before writing each message to file f."""
-        f.write('\014' + os.linesep)
+        f.write(b'\014' + linesep)
 
     def _post_message_hook(self, f):
         """Called after writing each message to file f."""
-        f.write(os.linesep + '\037')
+        f.write(linesep + b'\037')
 
     def _install_message(self, message):
         """Write message contents and return (start, stop)."""
@@ -1277,68 +1349,80 @@
                     special_labels.append(label)
                 else:
                     labels.append(label)
-            self._file.write('1')
+            self._file.write(b'1')
             for label in special_labels:
-                self._file.write(', ' + label)
-            self._file.write(',,')
+                self._file.write(b', ' + label.encode())
+            self._file.write(b',,')
             for label in labels:
-                self._file.write(' ' + label + ',')
-            self._file.write(os.linesep)
+                self._file.write(b' ' + label.encode() + b',')
+            self._file.write(linesep)
         else:
-            self._file.write('1,,' + os.linesep)
+            self._file.write(b'1,,' + linesep)
         if isinstance(message, email.message.Message):
-            orig_buffer = io.StringIO()
-            orig_generator = email.generator.Generator(orig_buffer, False, 0)
+            orig_buffer = io.BytesIO()
+            orig_generator = email.generator.BytesGenerator(orig_buffer, False, 0)
             orig_generator.flatten(message)
             orig_buffer.seek(0)
             while True:
                 line = orig_buffer.readline()
-                self._file.write(line.replace('\n', os.linesep))
-                if line == '\n' or not line:
+                self._file.write(line.replace(b'\n', linesep))
+                if line == b'\n' or not line:
                     break
-            self._file.write('*** EOOH ***' + os.linesep)
+            self._file.write(b'*** EOOH ***' + linesep)
             if isinstance(message, BabylMessage):
-                vis_buffer = io.StringIO()
-                vis_generator = email.generator.Generator(vis_buffer, False, 0)
+                vis_buffer = io.BytesIO()
+                vis_generator = email.generator.BytesGenerator(vis_buffer, False, 0)
                 vis_generator.flatten(message.get_visible())
                 while True:
                     line = vis_buffer.readline()
-                    self._file.write(line.replace('\n', os.linesep))
-                    if line == '\n' or not line:
+                    self._file.write(line.replace(b'\n', linesep))
+                    if line == b'\n' or not line:
                         break
             else:
                 orig_buffer.seek(0)
                 while True:
                     line = orig_buffer.readline()
-                    self._file.write(line.replace('\n', os.linesep))
-                    if line == '\n' or not line:
+                    self._file.write(line.replace(b'\n', linesep))
+                    if line == b'\n' or not line:
                         break
             while True:
                 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
                 if not buffer:
                     break
-                self._file.write(buffer.replace('\n', os.linesep))
-        elif isinstance(message, str):
-            body_start = message.find('\n\n') + 2
+                self._file.write(buffer.replace(b'\n', linesep))
+        elif isinstance(message, (bytes, str, io.StringIO)):
+            if isinstance(message, io.StringIO):
+                warnings.warn("Use of StringIO input is deprecated, "
+                    "use BytesIO instead", DeprecationWarning, 3)
+                message = message.getvalue()
+            if isinstance(message, str):
+                message = self._string_to_bytes(message)
+            body_start = message.find(b'\n\n') + 2
             if body_start - 2 != -1:
-                self._file.write(message[:body_start].replace('\n',
-                                                              os.linesep))
-                self._file.write('*** EOOH ***' + os.linesep)
-                self._file.write(message[:body_start].replace('\n',
-                                                              os.linesep))
-                self._file.write(message[body_start:].replace('\n',
-                                                              os.linesep))
+                self._file.write(message[:body_start].replace(b'\n', linesep))
+                self._file.write(b'*** EOOH ***' + linesep)
+                self._file.write(message[:body_start].replace(b'\n', linesep))
+                self._file.write(message[body_start:].replace(b'\n', linesep))
             else:
-                self._file.write('*** EOOH ***' + os.linesep + os.linesep)
-                self._file.write(message.replace('\n', os.linesep))
+                self._file.write(b'*** EOOH ***' + linesep + linesep)
+                self._file.write(message.replace(b'\n', linesep))
         elif hasattr(message, 'readline'):
+            if hasattr(message, 'buffer'):
+                warnings.warn("Use of text mode files is deprecated, "
+                    "use a binary mode file instead", DeprecationWarning, 3)
+                message = message.buffer
             original_pos = message.tell()
             first_pass = True
             while True:
                 line = message.readline()
-                self._file.write(line.replace('\n', os.linesep))
-                if line == '\n' or not line:
-                    self._file.write('*** EOOH ***' + os.linesep)
+                # Universal newline support.
+                if line.endswith(b'\r\n'):
+                    line = line[:-2] + b'\n'
+                elif line.endswith(b'\r'):
+                    line = line[:-1] + b'\n'
+                self._file.write(line.replace(b'\n', linesep))
+                if line == b'\n' or not line:
+                    self._file.write(b'*** EOOH ***' + linesep)
                     if first_pass:
                         first_pass = False
                         message.seek(original_pos)
@@ -1348,7 +1432,7 @@
                 buffer = message.read(4096)     # Buffer size is arbitrary.
                 if not buffer:
                     break
-                self._file.write(buffer.replace('\n', os.linesep))
+                self._file.write(buffer.replace(b'\n', linesep))
         else:
             raise TypeError('Invalid message type: %s' % type(message))
         stop = self._file.tell()
@@ -1364,10 +1448,14 @@
             self._become_message(copy.deepcopy(message))
             if isinstance(message, Message):
                 message._explain_to(self)
+        elif isinstance(message, bytes):
+            self._become_message(email.message_from_bytes(message))
         elif isinstance(message, str):
             self._become_message(email.message_from_string(message))
-        elif hasattr(message, "read"):
+        elif isinstance(message, io.TextIOWrapper):
             self._become_message(email.message_from_file(message))
+        elif hasattr(message, "read"):
+            self._become_message(email.message_from_binary_file(message))
         elif message is None:
             email.message.Message.__init__(self)
         else:
@@ -1631,7 +1719,7 @@
             if not sequence in self._sequences:
                 self._sequences.append(sequence)
         else:
-            raise TypeError('sequence must be a string: %s' % type(sequence))
+            raise TypeError('sequence type must be str: %s' % type(sequence))
 
     def remove_sequence(self, sequence):
         """Remove sequence from the list of sequences including the message."""
@@ -1791,6 +1879,10 @@
         """Read bytes."""
         return self._read(size, self._file.read)
 
+    def read1(self, size=None):
+        """Read bytes."""
+        return self._read(size, self._file.read1)
+
     def readline(self, size=None):
         """Read a line."""
         return self._read(size, self._file.readline)
@@ -1847,6 +1939,22 @@
     def __exit__(self, *exc):
         self.close()
 
+    def readable(self):
+        return self._file.readable()
+
+    def writable(self):
+        return self._file.writable()
+
+    def seekable(self):
+        return self._file.seekable()
+
+    def flush(self):
+        return self._file.flush()
+
+    @property
+    def closed(self):
+        return self._file.closed
+
 
 class _PartialFile(_ProxyFile):
     """A read-only wrapper of part of a file."""
@@ -1875,7 +1983,7 @@
         """Read size bytes using read_method, honoring start and stop."""
         remaining = self._stop - self._pos
         if remaining <= 0:
-            return ''
+            return b''
         if size is None or size < 0 or size > remaining:
             size = remaining
         return _ProxyFile._read(self, size, read_method)
@@ -1942,7 +2050,7 @@
     """Create a file if it doesn't exist and open for reading and writing."""
     fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666)
     try:
-        return open(path, 'r+', newline='')
+        return open(path, 'rb+')
     finally:
         os.close(fd)
 

Modified: python/branches/pep-3151/Lib/mimetypes.py
==============================================================================
--- python/branches/pep-3151/Lib/mimetypes.py	(original)
+++ python/branches/pep-3151/Lib/mimetypes.py	Sat Feb 26 08:16:32 2011
@@ -374,6 +374,7 @@
     global common_types
 
     suffix_map = {
+        '.svgz': '.svg.gz',
         '.tgz': '.tar.gz',
         '.taz': '.tar.gz',
         '.tz': '.tar.gz',
@@ -387,7 +388,7 @@
         }
 
     # Before adding new types, make sure they are either registered with IANA,
-    # at http://www.isi.edu/in-notes/iana/assignments/media-types
+    # at http://www.iana.org/assignments/media-types
     # or extensions, i.e. using the x- prefix
 
     # If you add to these, please keep them sorted!
@@ -488,6 +489,7 @@
         '.src'    : 'application/x-wais-source',
         '.sv4cpio': 'application/x-sv4cpio',
         '.sv4crc' : 'application/x-sv4crc',
+        '.svg'    : 'image/svg+xml',
         '.swf'    : 'application/x-shockwave-flash',
         '.t'      : 'application/x-troff',
         '.tar'    : 'application/x-tar',

Modified: python/branches/pep-3151/Lib/multiprocessing/__init__.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/__init__.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/__init__.py	Sat Feb 26 08:16:32 2011
@@ -38,6 +38,7 @@
 # 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.
 #
 
 __version__ = '0.70a1'

Modified: python/branches/pep-3151/Lib/multiprocessing/connection.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/connection.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/connection.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/connection.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 __all__ = [ 'Client', 'Listener', 'Pipe' ]
@@ -255,25 +281,24 @@
     Return a connection object connected to the socket given by `address`
     '''
     family = address_type(address)
-    s = socket.socket( getattr(socket, family) )
-    t = _init_timeout()
+    with socket.socket( getattr(socket, family) ) as s:
+        t = _init_timeout()
 
-    while 1:
-        try:
-            s.connect(address)
-        except socket.error as e:
-            if e.args[0] != errno.ECONNREFUSED or _check_timeout(t):
-                debug('failed to connect to address %s', address)
-                raise
-            time.sleep(0.01)
+        while 1:
+            try:
+                s.connect(address)
+            except socket.error as e:
+                if e.args[0] != errno.ECONNREFUSED or _check_timeout(t):
+                    debug('failed to connect to address %s', address)
+                    raise
+                time.sleep(0.01)
+            else:
+                break
         else:
-            break
-    else:
-        raise
+            raise
 
-    fd = duplicate(s.fileno())
+        fd = duplicate(s.fileno())
     conn = _multiprocessing.Connection(fd)
-    s.close()
     return conn
 
 #
@@ -409,10 +434,10 @@
         return self._loads(s)
 
 def _xml_dumps(obj):
-    return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf8')
+    return xmlrpclib.dumps((obj,), None, None, None, 1).encode('utf-8')
 
 def _xml_loads(s):
-    (obj,), method = xmlrpclib.loads(s.decode('utf8'))
+    (obj,), method = xmlrpclib.loads(s.decode('utf-8'))
     return obj
 
 class XmlListener(Listener):

Modified: python/branches/pep-3151/Lib/multiprocessing/dummy/__init__.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/dummy/__init__.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/dummy/__init__.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/dummy/__init__.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 __all__ = [

Modified: python/branches/pep-3151/Lib/multiprocessing/dummy/connection.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/dummy/connection.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/dummy/connection.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/dummy/connection.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 __all__ = [ 'Client', 'Listener', 'Pipe' ]

Modified: python/branches/pep-3151/Lib/multiprocessing/forking.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/forking.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/forking.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/forking.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 import os
@@ -433,12 +459,20 @@
         process.ORIGINAL_DIR = data['orig_dir']
 
     if 'main_path' in data:
+        # XXX (ncoghlan): The following code makes several bogus
+        # assumptions regarding the relationship between __file__
+        # and a module's real name. See PEP 302 and issue #10845
         main_path = data['main_path']
         main_name = os.path.splitext(os.path.basename(main_path))[0]
         if main_name == '__init__':
             main_name = os.path.basename(os.path.dirname(main_path))
 
-        if main_name != 'ipython':
+        if main_name == '__main__':
+            main_module = sys.modules['__main__']
+            main_module.__file__ = main_path
+        elif main_name != 'ipython':
+            # Main modules not actually called __main__.py may
+            # contain additional code that should still be executed
             import imp
 
             if main_path is None:

Modified: python/branches/pep-3151/Lib/multiprocessing/heap.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/heap.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/heap.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/heap.py
 #
-# Copyright (c) 2007-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 import bisect

Modified: python/branches/pep-3151/Lib/multiprocessing/managers.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/managers.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/managers.py	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,33 @@
 #
 # multiprocessing/managers.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 __all__ = [ 'BaseManager', 'SyncManager', 'BaseProxy', 'Token' ]

Modified: python/branches/pep-3151/Lib/multiprocessing/pool.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/pool.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/pool.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/pool.py
 #
-# Copyright (c) 2007-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 __all__ = ['Pool']

Modified: python/branches/pep-3151/Lib/multiprocessing/process.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/process.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/process.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/process.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 __all__ = ['Process', 'current_process', 'active_children']
@@ -65,12 +91,16 @@
     '''
     _Popen = None
 
-    def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
+    def __init__(self, group=None, target=None, name=None, args=(), kwargs={},
+                 *, daemon=None):
         assert group is None, 'group argument must be None for now'
         count = next(_current_process._counter)
         self._identity = _current_process._identity + (count,)
         self._authkey = _current_process._authkey
-        self._daemonic = _current_process._daemonic
+        if daemon is not None:
+            self._daemonic = daemon
+        else:
+            self._daemonic = _current_process._daemonic
         self._tempdir = _current_process._tempdir
         self._parent_pid = os.getpid()
         self._popen = None

Modified: python/branches/pep-3151/Lib/multiprocessing/queues.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/queues.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/queues.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/queues.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 __all__ = ['Queue', 'SimpleQueue', 'JoinableQueue']

Modified: python/branches/pep-3151/Lib/multiprocessing/reduction.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/reduction.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/reduction.py	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,33 @@
 #
 # multiprocessing/reduction.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 __all__ = []

Modified: python/branches/pep-3151/Lib/multiprocessing/sharedctypes.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/sharedctypes.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/sharedctypes.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/sharedctypes.py
 #
-# Copyright (c) 2007-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 import sys

Modified: python/branches/pep-3151/Lib/multiprocessing/synchronize.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/synchronize.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/synchronize.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/synchronize.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 __all__ = [

Modified: python/branches/pep-3151/Lib/multiprocessing/util.py
==============================================================================
--- python/branches/pep-3151/Lib/multiprocessing/util.py	(original)
+++ python/branches/pep-3151/Lib/multiprocessing/util.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,33 @@
 #
 # multiprocessing/util.py
 #
-# Copyright (c) 2006-2008, R Oudkerk --- see COPYING.txt
+# Copyright (c) 2006-2008, R Oudkerk
+# 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. Neither the name of author nor the names of any contributors may be
+#    used to endorse or promote products derived from this software
+#    without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "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 OR CONTRIBUTORS 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.
 #
 
 import itertools

Modified: python/branches/pep-3151/Lib/netrc.py
==============================================================================
--- python/branches/pep-3151/Lib/netrc.py	(original)
+++ python/branches/pep-3151/Lib/netrc.py	Sat Feb 26 08:16:32 2011
@@ -34,11 +34,15 @@
     def _parse(self, file, fp):
         lexer = shlex.shlex(fp)
         lexer.wordchars += r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
+        lexer.commenters = lexer.commenters.replace('#', '')
         while 1:
             # Look for a machine, default, or macdef top-level keyword
             toplevel = tt = lexer.get_token()
             if not tt:
                 break
+            elif tt[0] == '#':
+                fp.readline();
+                continue;
             elif tt == 'machine':
                 entryname = lexer.get_token()
             elif tt == 'default':

Modified: python/branches/pep-3151/Lib/numbers.py
==============================================================================
--- python/branches/pep-3151/Lib/numbers.py	(original)
+++ python/branches/pep-3151/Lib/numbers.py	Sat Feb 26 08:16:32 2011
@@ -60,7 +60,7 @@
 
     @abstractproperty
     def imag(self):
-        """Retrieve the real component of this number.
+        """Retrieve the imaginary component of this number.
 
         This should subclass Real.
         """
@@ -189,7 +189,7 @@
         raise NotImplementedError
 
     @abstractmethod
-    def __round__(self, ndigits:"Integral"=None):
+    def __round__(self, ndigits=None):
         """Rounds self to ndigits decimal places, defaulting to 0.
 
         If ndigits is omitted or None, returns an Integral, otherwise
@@ -303,7 +303,7 @@
         raise NotImplementedError
 
     def __index__(self):
-        """index(self)"""
+        """someobject[self]"""
         return int(self)
 
     @abstractmethod

Modified: python/branches/pep-3151/Lib/os.py
==============================================================================
--- python/branches/pep-3151/Lib/os.py	(original)
+++ python/branches/pep-3151/Lib/os.py	Sat Feb 26 08:16:32 2011
@@ -114,18 +114,26 @@
 SEEK_CUR = 1
 SEEK_END = 2
 
+
+def _get_masked_mode(mode):
+    mask = umask(0)
+    umask(mask)
+    return mode & ~mask
+
 #'
 
 # Super directory utilities.
 # (Inspired by Eric Raymond; the doc strings are mostly his)
 
-def makedirs(name, mode=0o777):
-    """makedirs(path [, mode=0o777])
+def makedirs(name, mode=0o777, exist_ok=False):
+    """makedirs(path [, mode=0o777][, exist_ok=False])
 
     Super-mkdir; create a leaf directory and all intermediate ones.
     Works like mkdir, except that any intermediate path segment (not
-    just the rightmost) will be created if it does not exist.  This is
-    recursive.
+    just the rightmost) will be created if it does not exist. If the
+    target directory with the same mode as we specified already exists,
+    raises an OSError if exist_ok is False, otherwise no exception is
+    raised.  This is recursive.
 
     """
     head, tail = path.split(name)
@@ -133,14 +141,20 @@
         head, tail = path.split(head)
     if head and tail and not path.exists(head):
         try:
-            makedirs(head, mode)
+            makedirs(head, mode, exist_ok)
         except OSError as e:
             # be happy if someone already created the path
             if e.errno != errno.EEXIST:
                 raise
         if tail == curdir:           # xxx/newdir/. exists if xxx/newdir exists
             return
-    mkdir(name, mode)
+    try:
+        mkdir(name, mode)
+    except OSError as e:
+        import stat as st
+        if not (e.errno == errno.EEXIST and exist_ok and path.isdir(name) and
+                st.S_IMODE(lstat(name).st_mode) == _get_masked_mode(mode)):
+            raise
 
 def removedirs(name):
     """removedirs(path)
@@ -420,7 +434,7 @@
 
 
 # Change environ to automatically call putenv(), unsetenv if they exist.
-from _abcoll import MutableMapping  # Can't use collections (bootstrap)
+from collections.abc import MutableMapping
 
 class _Environ(MutableMapping):
     def __init__(self, data, encodekey, decodekey, encodevalue, decodevalue, putenv, unsetenv):

Modified: python/branches/pep-3151/Lib/pdb.py
==============================================================================
--- python/branches/pep-3151/Lib/pdb.py	(original)
+++ python/branches/pep-3151/Lib/pdb.py	Sat Feb 26 08:16:32 2011
@@ -66,16 +66,18 @@
 # NOTE: the actual command documentation is collected from docstrings of the
 # commands and is appended to __doc__ after the class has been defined.
 
+import os
+import re
 import sys
-import linecache
 import cmd
 import bdb
 import dis
-import os
-import re
+import code
 import pprint
-import traceback
+import signal
 import inspect
+import traceback
+import linecache
 
 
 class Restart(Exception):
@@ -94,14 +96,14 @@
     # consumer of this info expects the first line to be 1
     lineno = 1
     answer = None
-    while 1:
+    while True:
         line = fp.readline()
         if line == '':
             break
         if cre.match(line):
             answer = funcname, filename, lineno
             break
-        lineno = lineno + 1
+        lineno += 1
     fp.close()
     return answer
 
@@ -123,6 +125,12 @@
     return 0
 
 
+class _rstr(str):
+    """String that doesn't quote its repr."""
+    def __repr__(self):
+        return self
+
+
 # Interaction prompt line will separate file and call info from code
 # text using value of line_prefix string.  A newline and arrow may
 # be to your liking.  You can set it once pdb is imported using the
@@ -132,21 +140,25 @@
 
 class Pdb(bdb.Bdb, cmd.Cmd):
 
-    def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None):
+    def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None,
+                 nosigint=False):
         bdb.Bdb.__init__(self, skip=skip)
         cmd.Cmd.__init__(self, completekey, stdin, stdout)
         if stdout:
             self.use_rawinput = 0
         self.prompt = '(Pdb) '
         self.aliases = {}
+        self.displaying = {}
         self.mainpyfile = ''
-        self._wait_for_mainpyfile = 0
+        self._wait_for_mainpyfile = False
         self.tb_lineno = {}
         # Try to load readline if it exists
         try:
             import readline
         except ImportError:
             pass
+        self.allow_kbdint = False
+        self.nosigint = nosigint
 
         # Read $HOME/.pdbrc and ./.pdbrc
         self.rcLines = []
@@ -173,6 +185,15 @@
         self.commands_bnum = None # The breakpoint number for which we are
                                   # defining a list
 
+    def sigint_handler(self, signum, frame):
+        if self.allow_kbdint:
+            raise KeyboardInterrupt
+        self.message("\nProgram interrupted. (Use 'cont' to resume).")
+        self.set_step()
+        self.set_trace(frame)
+        # restore previous signal handler
+        signal.signal(signal.SIGINT, self._previous_sigint_handler)
+
     def reset(self):
         bdb.Bdb.reset(self)
         self.forget()
@@ -235,9 +256,9 @@
         """This function is called when we stop or break at this line."""
         if self._wait_for_mainpyfile:
             if (self.mainpyfile != self.canonic(frame.f_code.co_filename)
-                or frame.f_lineno<= 0):
+                or frame.f_lineno <= 0):
                 return
-            self._wait_for_mainpyfile = 0
+            self._wait_for_mainpyfile = False
         if self.bp_commands(frame):
             self.interaction(frame, None)
 
@@ -260,7 +281,7 @@
             if not self.commands_silent[currentbp]:
                 self.print_stack_entry(self.stack[self.curindex])
             if self.commands_doprompt[currentbp]:
-                self.cmdloop()
+                self._cmdloop()
             self.forget()
             return
         return 1
@@ -285,6 +306,31 @@
         self.interaction(frame, exc_traceback)
 
     # General interaction function
+    def _cmdloop(self):
+        while True:
+            try:
+                # keyboard interrupts allow for an easy way to cancel
+                # the current command, so allow them during interactive input
+                self.allow_kbdint = True
+                self.cmdloop()
+                self.allow_kbdint = False
+                break
+            except KeyboardInterrupt:
+                self.message('--KeyboardInterrupt--')
+
+    # Called before loop, handles display expressions
+    def preloop(self):
+        displaying = self.displaying.get(self.curframe)
+        if displaying:
+            for expr, oldvalue in displaying.items():
+                newvalue = self._getval_except(expr)
+                # check for identity first; this prevents custom __eq__ to
+                # be called at every loop, and also prevents instances whose
+                # fields are changed to be displayed
+                if newvalue is not oldvalue and newvalue != oldvalue:
+                    displaying[expr] = newvalue
+                    self.message('display %s: %r  [old: %r]' %
+                                 (expr, newvalue, oldvalue))
 
     def interaction(self, frame, traceback):
         if self.setup(frame, traceback):
@@ -293,7 +339,7 @@
             self.forget()
             return
         self.print_stack_entry(self.stack[self.curindex])
-        self.cmdloop()
+        self._cmdloop()
         self.forget()
 
     def displayhook(self, obj):
@@ -337,7 +383,7 @@
             for tmpArg in args[1:]:
                 line = line.replace("%" + str(ii),
                                       tmpArg)
-                ii = ii + 1
+                ii += 1
             line = line.replace("%*", ' '.join(args[1:]))
             args = line.split()
         # split into ';;' separated commands
@@ -774,7 +820,7 @@
             except ValueError as err:
                 self.error(err)
             else:
-                self.clear_break(bp.file, bp.line)
+                self.clear_bpbynumber(i)
                 self.message('Deleted %s' % bp)
     do_cl = do_clear # 'c' is already an abbreviation for 'continue'
 
@@ -908,6 +954,9 @@
         """c(ont(inue))
         Continue execution, only stop when a breakpoint is encountered.
         """
+        if not self.nosigint:
+            self._previous_sigint_handler = \
+                signal.signal(signal.SIGINT, self.sigint_handler)
         self.set_continue()
         return 1
     do_c = do_cont = do_continue
@@ -962,7 +1011,7 @@
         """q(uit)\nexit
         Quit from the debugger. The program being executed is aborted.
         """
-        self._user_requested_quit = 1
+        self._user_requested_quit = True
         self.set_quit()
         return 1
 
@@ -974,7 +1023,7 @@
         Handles the receipt of EOF as a command.
         """
         self.message('')
-        self._user_requested_quit = 1
+        self._user_requested_quit = True
         self.set_quit()
         return 1
 
@@ -1013,6 +1062,17 @@
             self.error(traceback.format_exception_only(*exc_info)[-1].strip())
             raise
 
+    def _getval_except(self, arg, frame=None):
+        try:
+            if frame is None:
+                return eval(arg, self.curframe.f_globals, self.curframe_locals)
+            else:
+                return eval(arg, frame.f_globals, frame.f_locals)
+        except:
+            exc_info = sys.exc_info()[:2]
+            err = traceback.format_exception_only(*exc_info)[-1].strip()
+            return _rstr('** raised %s **' % err)
+
     def do_p(self, arg):
         """p(rint) expression
         Print the value of the expression.
@@ -1167,6 +1227,48 @@
         # None of the above...
         self.message(type(value))
 
+    def do_display(self, arg):
+        """display [expression]
+
+        Display the value of the expression if it changed, each time execution
+        stops in the current frame.
+
+        Without expression, list all display expressions for the current frame.
+        """
+        if not arg:
+            self.message('Currently displaying:')
+            for item in self.displaying.get(self.curframe, {}).items():
+                self.message('%s: %r' % item)
+        else:
+            val = self._getval_except(arg)
+            self.displaying.setdefault(self.curframe, {})[arg] = val
+            self.message('display %s: %r' % (arg, val))
+
+    def do_undisplay(self, arg):
+        """undisplay [expression]
+
+        Do not display the expression any more in the current frame.
+
+        Without expression, clear all display expressions for the current frame.
+        """
+        if arg:
+            try:
+                del self.displaying.get(self.curframe, {})[arg]
+            except KeyError:
+                self.error('not displaying %s' % arg)
+        else:
+            self.displaying.pop(self.curframe, None)
+
+    def do_interact(self, arg):
+        """interact
+
+        Start an interative interpreter whose global namespace
+        contains all the (global and local) names found in the current scope.
+        """
+        ns = self.curframe.f_globals.copy()
+        ns.update(self.curframe_locals)
+        code.interact("*interactive*", local=ns)
+
     def do_alias(self, arg):
         """alias [name [command [parameter parameter ...] ]]
         Create an alias called 'name' that executes 'command'.  The
@@ -1326,9 +1428,9 @@
         # events depends on python version). So we take special measures to
         # avoid stopping before we reach the main script (see user_line and
         # user_call for details).
-        self._wait_for_mainpyfile = 1
+        self._wait_for_mainpyfile = True
         self.mainpyfile = self.canonic(filename)
-        self._user_requested_quit = 0
+        self._user_requested_quit = False
         with open(filename, "rb") as fp:
             statement = "exec(compile(%r, %r, 'exec'))" % \
                         (fp.read(), self.mainpyfile)
@@ -1342,8 +1444,8 @@
         'help', 'where', 'down', 'up', 'break', 'tbreak', 'clear', 'disable',
         'enable', 'ignore', 'condition', 'commands', 'step', 'next', 'until',
         'jump', 'return', 'retval', 'run', 'continue', 'list', 'longlist',
-        'args', 'print', 'pp', 'whatis', 'source', 'alias', 'unalias',
-        'debug', 'quit',
+        'args', 'print', 'pp', 'whatis', 'source', 'display', 'undisplay',
+        'interact', 'alias', 'unalias', 'debug', 'quit',
     ]
 
     for _command in _help_order:

Modified: python/branches/pep-3151/Lib/poplib.py
==============================================================================
--- python/branches/pep-3151/Lib/poplib.py	(original)
+++ python/branches/pep-3151/Lib/poplib.py	Sat Feb 26 08:16:32 2011
@@ -250,15 +250,18 @@
 
     def quit(self):
         """Signoff: commit changes on server, unlock mailbox, close connection."""
-        try:
-            resp = self._shortcmd('QUIT')
-        except error_proto as val:
-            resp = val
-        self.file.close()
-        self.sock.close()
-        del self.file, self.sock
+        resp = self._shortcmd('QUIT')
+        self.close()
         return resp
 
+    def close(self):
+        """Close the connection without assuming anything about it."""
+        if self.file is not None:
+            self.file.close()
+        if self.sock is not None:
+            self.sock.close()
+        self.file = self.sock = None
+
     #__del__ = quit
 
 

Modified: python/branches/pep-3151/Lib/pstats.py
==============================================================================
--- python/branches/pep-3151/Lib/pstats.py	(original)
+++ python/branches/pep-3151/Lib/pstats.py	Sat Feb 26 08:16:32 2011
@@ -348,7 +348,7 @@
         print(indent, self.total_calls, "function calls", end=' ', file=self.stream)
         if self.total_calls != self.prim_calls:
             print("(%d primitive calls)" % self.prim_calls, end=' ', file=self.stream)
-        print("in %.3f CPU seconds" % self.total_tt, file=self.stream)
+        print("in %.3f seconds" % self.total_tt, file=self.stream)
         print(file=self.stream)
         width, list = self.get_print_list(amount)
         if list:

Modified: python/branches/pep-3151/Lib/py_compile.py
==============================================================================
--- python/branches/pep-3151/Lib/py_compile.py	(original)
+++ python/branches/pep-3151/Lib/py_compile.py	Sat Feb 26 08:16:32 2011
@@ -72,7 +72,7 @@
                    (x >> 16) & 0xff,
                    (x >> 24) & 0xff]))
 
-def compile(file, cfile=None, dfile=None, doraise=False):
+def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1):
     """Byte-compile one Python source file to Python bytecode.
 
     :param file: The source file name.
@@ -86,6 +86,10 @@
         will be printed, and the function will return to the caller. If an
         exception occurs and this flag is set to True, a PyCompileError
         exception will be raised.
+    :param optimize: The optimization level for the compiler.  Valid values
+        are -1, 0, 1 and 2.  A value of -1 means to use the optimization
+        level of the current interpreter, as given by -O command line options.
+
     :return: Path to the resulting byte compiled file.
 
     Note that it isn't necessary to byte-compile Python modules for
@@ -111,7 +115,8 @@
             timestamp = int(os.stat(file).st_mtime)
         codestring = f.read()
     try:
-        codeobject = builtins.compile(codestring, dfile or file,'exec')
+        codeobject = builtins.compile(codestring, dfile or file, 'exec',
+                                      optimize=optimize)
     except Exception as err:
         py_exc = PyCompileError(err.__class__, err, dfile or file)
         if doraise:
@@ -120,7 +125,10 @@
             sys.stderr.write(py_exc.msg + '\n')
             return
     if cfile is None:
-        cfile = imp.cache_from_source(file)
+        if optimize >= 0:
+            cfile = imp.cache_from_source(file, debug_override=not optimize)
+        else:
+            cfile = imp.cache_from_source(file)
     try:
         os.makedirs(os.path.dirname(cfile))
     except OSError as error:

Modified: python/branches/pep-3151/Lib/pyclbr.py
==============================================================================
--- python/branches/pep-3151/Lib/pyclbr.py	(original)
+++ python/branches/pep-3151/Lib/pyclbr.py	Sat Feb 26 08:16:32 2011
@@ -325,7 +325,7 @@
     else:
         path = []
     dict = readmodule_ex(mod, path)
-    objs = dict.values()
+    objs = list(dict.values())
     objs.sort(key=lambda a: getattr(a, 'lineno', 0))
     for obj in objs:
         if isinstance(obj, Class):

Modified: python/branches/pep-3151/Lib/pydoc.py
==============================================================================
--- python/branches/pep-3151/Lib/pydoc.py	(original)
+++ python/branches/pep-3151/Lib/pydoc.py	Sat Feb 26 08:16:32 2011
@@ -15,24 +15,30 @@
 Run "pydoc -k <keyword>" to search for a keyword in the synopsis lines
 of all available modules.
 
-Run "pydoc -p <port>" to start an HTTP server on a given port on the
-local machine to generate documentation web pages.
+Run "pydoc -p <port>" to start an HTTP server on the given port on the
+local machine.  Port number 0 can be used to get an arbitrary unused port.
+
+Run "pydoc -b" to start an HTTP server on an arbitrary unused port and
+open a Web browser to interactively browse documentation.  The -p option
+can be used with the -b option to explicitly specify the server port.
 
 For platforms without a command line, "pydoc -g" starts the HTTP server
-and also pops up a little window for controlling it.
+and also pops up a little window for controlling it.  This option is
+deprecated, since the server can now be controlled directly from HTTP
+clients.
 
 Run "pydoc -w <name>" to write out the HTML documentation for a module
 to a file named "<name>.html".
 
 Module docs for core modules are assumed to be in
 
-    http://docs.python.org/library/
+    http://docs.python.org/X.Y/library/
 
 This can be overridden by setting the PYTHONDOCS environment variable
 to a different URL or to a local directory containing the Library
 Reference Manual pages.
 """
-
+__all__ = ['help']
 __author__ = "Ka-Ping Yee <ping at lfw.org>"
 __date__ = "26 February 2001"
 
@@ -51,16 +57,21 @@
 #     the current directory is changed with os.chdir(), an incorrect
 #     path will be displayed.
 
-import sys, imp, os, re, inspect, builtins, pkgutil
+import os
+import sys
+import builtins
+import imp
+import io
+import inspect
+import pkgutil
+import platform
+import re
+import time
+import warnings
+from collections import deque
 from reprlib import Repr
-from traceback import extract_tb as _extract_tb
-try:
-    from collections import deque
-except ImportError:
-    # Python 2.3 compatibility
-    class deque(list):
-        def popleft(self):
-            return self.pop(0)
+from traceback import extract_tb, format_exception_only
+
 
 # --------------------------------------------------------- common routines
 
@@ -159,7 +170,8 @@
     # Certain special names are redundant.
     _hidden_names = ('__builtins__', '__doc__', '__file__', '__path__',
                      '__module__', '__name__', '__slots__', '__package__',
-                     '__cached__')
+                     '__cached__', '__author__', '__credits__', '__date__',
+                     '__version__')
     if name in _hidden_names: return 0
     # Private names are hidden, but special names are displayed.
     if name.startswith('__') and name.endswith('__'): return 1
@@ -291,7 +303,7 @@
         elif exc is SyntaxError:
             # A SyntaxError occurred before we could execute the module.
             raise ErrorDuringImport(value.filename, info)
-        elif exc is ImportError and _extract_tb(tb)[-1][2]=='safeimport':
+        elif exc is ImportError and extract_tb(tb)[-1][2]=='safeimport':
             # The import error occurred directly in this function,
             # which means there is no such module in the path.
             return None
@@ -306,6 +318,11 @@
 # ---------------------------------------------------- formatter base class
 
 class Doc:
+
+    PYTHONDOCS = os.environ.get("PYTHONDOCS",
+                                "http://docs.python.org/%d.%d/library"
+                                % sys.version_info[:2])
+
     def document(self, object, name=None, *args):
         """Generate documentation for an object."""
         args = (object, name) + args
@@ -340,10 +357,10 @@
         except TypeError:
             file = '(built-in)'
 
-        docloc = os.environ.get("PYTHONDOCS",
-                                "http://docs.python.org/library")
+        docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS)
+
         basedir = os.path.join(sys.exec_prefix, "lib",
-                               "python"+sys.version[0:3])
+                               "python%d.%d" %  sys.version_info[:2])
         if (isinstance(object, type(os)) and
             (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
                                  'marshal', 'posix', 'signal', 'sys',
@@ -514,6 +531,10 @@
             text = name
         return '<a href="%s">%s</a>' % (url, text)
 
+    def filelink(self, url, path):
+        """Make a link to source file."""
+        return '<a href="file:%s">%s</a>' % (url, path)
+
     def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
         """Mark up some plain text, given a context of symbols to look for.
         Each context dictionary maps object names to anchor names."""
@@ -592,7 +613,7 @@
             if sys.platform == 'win32':
                 import nturl2path
                 url = nturl2path.pathname2url(path)
-            filelink = '<a href="file:%s">%s</a>' % (url, path)
+            filelink = self.filelink(url, path)
         except TypeError:
             filelink = '(built-in)'
         info = []
@@ -607,7 +628,7 @@
             head = head + ' (%s)' % ', '.join(info)
         docloc = self.getdocloc(object)
         if docloc is not None:
-            docloc = '<br><a href="%(docloc)s">Module Docs</a>' % locals()
+            docloc = '<br><a href="%(docloc)s">Module Reference</a>' % locals()
         else:
             docloc = ''
         result = self.heading(
@@ -979,7 +1000,7 @@
 
     def bold(self, text):
         """Format a string in bold by overstriking."""
-        return ''.join(map(lambda ch: ch + '\b' + ch, text))
+        return ''.join(ch + '\b' + ch for ch in text)
 
     def indent(self, text, prefix='    '):
         """Indent text by prepending a given prefix to each line."""
@@ -1003,7 +1024,7 @@
                 c, bases = entry
                 result = result + prefix + classname(c, modname)
                 if bases and bases != (parent,):
-                    parents = map(lambda c, m=modname: classname(c, m), bases)
+                    parents = (classname(c, modname) for c in bases)
                     result = result + '(%s)' % ', '.join(parents)
                 result = result + '\n'
             elif type(entry) is type([]):
@@ -1016,21 +1037,16 @@
         name = object.__name__ # ignore the passed-in name
         synop, desc = splitdoc(getdoc(object))
         result = self.section('NAME', name + (synop and ' - ' + synop))
-
-        try:
-            all = object.__all__
-        except AttributeError:
-            all = None
-
-        try:
-            file = inspect.getabsfile(object)
-        except TypeError:
-            file = '(built-in)'
-        result = result + self.section('FILE', file)
-
+        all = getattr(object, '__all__', None)
         docloc = self.getdocloc(object)
         if docloc is not None:
-            result = result + self.section('MODULE DOCS', docloc)
+            result = result + self.section('MODULE REFERENCE', docloc + """
+
+The following documentation is automatically generated from the Python source
+files.  It may be incomplete, incorrect or include features that are considered
+implementation detail and may vary between Python implementations.  When in
+doubt, consult the module reference at the location listed above.
+""")
 
         if desc:
             result = result + self.section('DESCRIPTION', desc)
@@ -1109,9 +1125,14 @@
             result = result + self.section('AUTHOR', str(object.__author__))
         if hasattr(object, '__credits__'):
             result = result + self.section('CREDITS', str(object.__credits__))
+        try:
+            file = inspect.getabsfile(object)
+        except TypeError:
+            file = '(built-in)'
+        result = result + self.section('FILE', file)
         return result
 
-    def docclass(self, object, name=None, mod=None):
+    def docclass(self, object, name=None, mod=None, *ignored):
         """Produce text documentation for a given class object."""
         realname = object.__name__
         name = name or realname
@@ -1311,6 +1332,11 @@
             line += '\n' + self.indent(str(doc))
         return line
 
+class _PlainTextDoc(TextDoc):
+    """Subclass of TextDoc which overrides string styling"""
+    def bold(self, text):
+        return text
+
 # --------------------------------------------------------- user interfaces
 
 def pager(text):
@@ -1465,6 +1491,7 @@
 # --------------------------------------- interactive interpreter interface
 
 text = TextDoc()
+plaintext = _PlainTextDoc()
 html = HTMLDoc()
 
 def resolve(thing, forceload=0):
@@ -1477,8 +1504,11 @@
     else:
         return thing, getattr(thing, '__name__', None)
 
-def render_doc(thing, title='Python Library Documentation: %s', forceload=0):
+def render_doc(thing, title='Python Library Documentation: %s', forceload=0,
+        renderer=None):
     """Render text documentation, given an object or a path to an object."""
+    if renderer is None:
+        renderer = text
     object, name = resolve(thing, forceload)
     desc = describe(object)
     module = inspect.getmodule(object)
@@ -1497,12 +1527,16 @@
         # document its available methods instead of its value.
         object = type(object)
         desc += ' object'
-    return title % desc + '\n\n' + text.document(object, name)
+    return title % desc + '\n\n' + renderer.document(object, name)
 
-def doc(thing, title='Python Library Documentation: %s', forceload=0):
+def doc(thing, title='Python Library Documentation: %s', forceload=0,
+        output=None):
     """Display text documentation, given an object or a path to an object."""
     try:
-        pager(render_doc(thing, title, forceload))
+        if output is None:
+            pager(render_doc(thing, title, forceload))
+        else:
+            output.write(render_doc(thing, title, forceload, plaintext))
     except (ImportError, ErrorDuringImport) as value:
         print(value)
 
@@ -1553,12 +1587,13 @@
         'finally': 'try',
         'for': ('for', 'break continue while'),
         'from': 'import',
-        'global': ('global', 'NAMESPACES'),
+        'global': ('global', 'nonlocal NAMESPACES'),
         'if': ('if', 'TRUTHVALUE'),
         'import': ('import', 'MODULES'),
         'in': ('in', 'SEQUENCEMETHODS'),
         'is': 'COMPARISON',
         'lambda': ('lambda', 'FUNCTIONS'),
+        'nonlocal': ('nonlocal', 'global NAMESPACES'),
         'not': 'BOOLEAN',
         'or': 'BOOLEAN',
         'pass': ('pass', ''),
@@ -1653,7 +1688,7 @@
         'NUMBERMETHODS': ('numeric-types', 'NUMBERS AUGMENTEDASSIGNMENT '
                           'SPECIALMETHODS'),
         'EXECUTION': ('execmodel', 'NAMESPACES DYNAMICFEATURES EXCEPTIONS'),
-        'NAMESPACES': ('naming', 'global ASSIGNMENT DELETION DYNAMICFEATURES'),
+        'NAMESPACES': ('naming', 'global nonlocal ASSIGNMENT DELETION DYNAMICFEATURES'),
         'DYNAMICFEATURES': ('dynamic-features', ''),
         'SCOPING': 'NAMESPACES',
         'FRAMES': 'NAMESPACES',
@@ -1755,9 +1790,9 @@
             elif request in self.symbols: self.showsymbol(request)
             elif request in self.keywords: self.showtopic(request)
             elif request in self.topics: self.showtopic(request)
-            elif request: doc(request, 'Help on %s:')
+            elif request: doc(request, 'Help on %s:', output=self._output)
         elif isinstance(request, Helper): self()
-        else: doc(request, 'Help on %s:')
+        else: doc(request, 'Help on %s:', output=self._output)
         self.output.write('\n')
 
     def intro(self):
@@ -1838,12 +1873,39 @@
         if more_xrefs:
             xrefs = (xrefs or '') + ' ' + more_xrefs
         if xrefs:
-            import io, formatter
+            import formatter
             buffer = io.StringIO()
             formatter.DumbWriter(buffer).send_flowing_data(
                 'Related help topics: ' + ', '.join(xrefs.split()) + '\n')
             self.output.write('\n%s\n' % buffer.getvalue())
 
+    def _gettopic(self, topic, more_xrefs=''):
+        """Return unbuffered tuple of (topic, xrefs).
+
+        If an error occurs here, the exception is caught and displayed by
+        the url handler.
+
+        This function duplicates the showtopic method but returns its
+        result directly so it can be formatted for display in an html page.
+        """
+        try:
+            import pydoc_data.topics
+        except ImportError:
+            return('''
+Sorry, topic and keyword documentation is not available because the
+module "pydoc_data.topics" could not be found.
+''' , '')
+        target = self.topics.get(topic, self.keywords.get(topic))
+        if not target:
+            raise ValueError('could not find topic')
+        if isinstance(target, str):
+            return self._gettopic(target, more_xrefs)
+        label, xrefs = target
+        doc = pydoc_data.topics.topics[label]
+        if more_xrefs:
+            xrefs = (xrefs or '') + ' ' + more_xrefs
+        return doc, xrefs
+
     def showsymbol(self, symbol):
         target = self.symbols[symbol]
         topic, _, xrefs = target.partition(' ')
@@ -1925,6 +1987,15 @@
         for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
             if self.quit:
                 break
+
+            # XXX Skipping this file is a workaround for a bug
+            # that causes python to crash with a segfault.
+            # http://bugs.python.org/issue9319
+            #
+            # TODO Remove this once the bug is fixed.
+            if modname in {'test.badsyntax_pep3120', 'badsyntax_pep3120'}:
+                continue
+
             if key is None:
                 callback(None, modname, '')
             else:
@@ -1940,7 +2011,6 @@
                         if onerror:
                             onerror(modname)
                         continue
-                    import io
                     desc = source_synopsis(io.StringIO(source)) or ''
                     if hasattr(loader, 'get_filename'):
                         path = loader.get_filename(modname)
@@ -1970,16 +2040,18 @@
         print(modname, desc and '- ' + desc)
     def onerror(modname):
         pass
-    try: import warnings
-    except ImportError: pass
-    else: warnings.filterwarnings('ignore') # ignore problems during import
-    ModuleScanner().run(callback, key, onerror=onerror)
+    with warnings.catch_warnings():
+        warnings.filterwarnings('ignore') # ignore problems during import
+        ModuleScanner().run(callback, key, onerror=onerror)
 
-# --------------------------------------------------- web browser interface
+# --------------------------------------------------- Web browser interface
 
 def serve(port, callback=None, completer=None):
     import http.server, email.message, select
 
+    msg = 'the pydoc.serve() function is deprecated'
+    warnings.warn(msg, DeprecationWarning, stacklevel=2)
+
     class DocHandler(http.server.BaseHTTPRequestHandler):
         def send_document(self, title, contents):
             try:
@@ -2039,6 +2111,7 @@
             while not self.quit:
                 rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
                 if rd: self.handle_request()
+            self.server_close()
 
         def server_activate(self):
             self.base.server_activate(self)
@@ -2058,7 +2131,12 @@
 # ----------------------------------------------------- graphical interface
 
 def gui():
-    """Graphical interface (starts web server and pops up a control window)."""
+    """Graphical interface (starts Web server and pops up a control window)."""
+
+    msg = ('the pydoc.gui() function and "pydoc -g" option are deprecated\n',
+           'use "pydoc.browse() function and "pydoc -b" option instead.')
+    warnings.warn(msg, DeprecationWarning, stacklevel=2)
+
     class GUI:
         def __init__(self, window, port=7464):
             self.window = window
@@ -2138,15 +2216,8 @@
 
         def open(self, event=None, url=None):
             url = url or self.server.url
-            try:
-                import webbrowser
-                webbrowser.open(url)
-            except ImportError: # pre-webbrowser.py compatibility
-                if sys.platform == 'win32':
-                    os.system('start "%s"' % url)
-                else:
-                    rc = os.system('netscape -remote "openURL(%s)" &' % url)
-                    if rc: os.system('netscape "%s" &' % url)
+            import webbrowser
+            webbrowser.open(url)
 
         def quit(self, event=None):
             if self.server:
@@ -2238,6 +2309,444 @@
     except KeyboardInterrupt:
         pass
 
+
+# --------------------------------------- enhanced Web browser interface
+
+def _start_server(urlhandler, port):
+    """Start an HTTP server thread on a specific port.
+
+    Start an HTML/text server thread, so HTML or text documents can be
+    browsed dynamically and interactively with a Web browser.  Example use:
+
+        >>> import time
+        >>> import pydoc
+
+        Define a URL handler.  To determine what the client is asking
+        for, check the URL and content_type.
+
+        Then get or generate some text or HTML code and return it.
+
+        >>> def my_url_handler(url, content_type):
+        ...     text = 'the URL sent was: (%s, %s)' % (url, content_type)
+        ...     return text
+
+        Start server thread on port 0.
+        If you use port 0, the server will pick a random port number.
+        You can then use serverthread.port to get the port number.
+
+        >>> port = 0
+        >>> serverthread = pydoc._start_server(my_url_handler, port)
+
+        Check that the server is really started.  If it is, open browser
+        and get first page.  Use serverthread.url as the starting page.
+
+        >>> if serverthread.serving:
+        ...    import webbrowser
+
+        The next two lines are commented out so a browser doesn't open if
+        doctest is run on this module.
+
+        #...    webbrowser.open(serverthread.url)
+        #True
+
+        Let the server do its thing. We just need to monitor its status.
+        Use time.sleep so the loop doesn't hog the CPU.
+
+        >>> starttime = time.time()
+        >>> timeout = 1                    #seconds
+
+        This is a short timeout for testing purposes.
+
+        >>> while serverthread.serving:
+        ...     time.sleep(.01)
+        ...     if serverthread.serving and time.time() - starttime > timeout:
+        ...          serverthread.stop()
+        ...          break
+
+        Print any errors that may have occurred.
+
+        >>> print(serverthread.error)
+        None
+   """
+    import http.server
+    import email.message
+    import select
+    import threading
+
+    class DocHandler(http.server.BaseHTTPRequestHandler):
+
+        def do_GET(self):
+            """Process a request from an HTML browser.
+
+            The URL received is in self.path.
+            Get an HTML page from self.urlhandler and send it.
+            """
+            if self.path.endswith('.css'):
+                content_type = 'text/css'
+            else:
+                content_type = 'text/html'
+            self.send_response(200)
+            self.send_header('Content-Type', '%s; charset=UTF-8' % content_type)
+            self.end_headers()
+            self.wfile.write(self.urlhandler(
+                self.path, content_type).encode('utf-8'))
+
+        def log_message(self, *args):
+            # Don't log messages.
+            pass
+
+    class DocServer(http.server.HTTPServer):
+
+        def __init__(self, port, callback):
+            self.host = (sys.platform == 'mac') and '127.0.0.1' or 'localhost'
+            self.address = ('', port)
+            self.callback = callback
+            self.base.__init__(self, self.address, self.handler)
+            self.quit = False
+
+        def serve_until_quit(self):
+            while not self.quit:
+                rd, wr, ex = select.select([self.socket.fileno()], [], [], 1)
+                if rd:
+                    self.handle_request()
+            self.server_close()
+
+        def server_activate(self):
+            self.base.server_activate(self)
+            if self.callback:
+                self.callback(self)
+
+    class ServerThread(threading.Thread):
+
+        def __init__(self, urlhandler, port):
+            self.urlhandler = urlhandler
+            self.port = int(port)
+            threading.Thread.__init__(self)
+            self.serving = False
+            self.error = None
+
+        def run(self):
+            """Start the server."""
+            try:
+                DocServer.base = http.server.HTTPServer
+                DocServer.handler = DocHandler
+                DocHandler.MessageClass = email.message.Message
+                DocHandler.urlhandler = staticmethod(self.urlhandler)
+                docsvr = DocServer(self.port, self.ready)
+                self.docserver = docsvr
+                docsvr.serve_until_quit()
+            except Exception as e:
+                self.error = e
+
+        def ready(self, server):
+            self.serving = True
+            self.host = server.host
+            self.port = server.server_port
+            self.url = 'http://%s:%d/' % (self.host, self.port)
+
+        def stop(self):
+            """Stop the server and this thread nicely"""
+            self.docserver.quit = True
+            self.serving = False
+            self.url = None
+
+    thread = ServerThread(urlhandler, port)
+    thread.start()
+    # Wait until thread.serving is True to make sure we are
+    # really up before returning.
+    while not thread.error and not thread.serving:
+        time.sleep(.01)
+    return thread
+
+
+def _url_handler(url, content_type="text/html"):
+    """The pydoc url handler for use with the pydoc server.
+
+    If the content_type is 'text/css', the _pydoc.css style
+    sheet is read and returned if it exits.
+
+    If the content_type is 'text/html', then the result of
+    get_html_page(url) is returned.
+    """
+    class _HTMLDoc(HTMLDoc):
+
+        def page(self, title, contents):
+            """Format an HTML page."""
+            css_path = "pydoc_data/_pydoc.css"
+            css_link = (
+                '<link rel="stylesheet" type="text/css" href="%s">' %
+                css_path)
+            return '''\
+<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<html><head><title>Pydoc: %s</title>
+<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+%s</head><body bgcolor="#f0f0f8">%s<div style="clear:both;padding-top:.5em;">%s</div>
+</body></html>''' % (title, css_link, html_navbar(), contents)
+
+        def filelink(self, url, path):
+            return '<a href="getfile?key=%s">%s</a>' % (url, path)
+
+
+    html = _HTMLDoc()
+
+    def html_navbar():
+        version = html.escape("%s [%s, %s]" % (platform.python_version(),
+                                               platform.python_build()[0],
+                                               platform.python_compiler()))
+        return """
+            <div style='float:left'>
+                Python %s<br>%s
+            </div>
+            <div style='float:right'>
+                <div style='text-align:center'>
+                  <a href="index.html">Module Index</a>
+                  : <a href="topics.html">Topics</a>
+                  : <a href="keywords.html">Keywords</a>
+                </div>
+                <div>
+                    <form action="get" style='display:inline;'>
+                      <input type=text name=key size=15>
+                      <input type=submit value="Get">
+                    </form>&nbsp;
+                    <form action="search" style='display:inline;'>
+                      <input type=text name=key size=15>
+                      <input type=submit value="Search">
+                    </form>
+                </div>
+            </div>
+            """ % (version, html.escape(platform.platform(terse=True)))
+
+    def html_index():
+        """Module Index page."""
+
+        def bltinlink(name):
+            return '<a href="%s.html">%s</a>' % (name, name)
+
+        heading = html.heading(
+            '<big><big><strong>Index of Modules</strong></big></big>',
+            '#ffffff', '#7799ee')
+        names = [name for name in sys.builtin_module_names
+                 if name != '__main__']
+        contents = html.multicolumn(names, bltinlink)
+        contents = [heading, '<p>' + html.bigsection(
+            'Built-in Modules', '#ffffff', '#ee77aa', contents)]
+
+        seen = {}
+        for dir in sys.path:
+            contents.append(html.index(dir, seen))
+
+        contents.append(
+            '<p align=right><font color="#909090" face="helvetica,'
+            'arial"><strong>pydoc</strong> by Ka-Ping Yee'
+            '&lt;ping at lfw.org&gt;</font>')
+        return 'Index of Modules', ''.join(contents)
+
+    def html_search(key):
+        """Search results page."""
+        # scan for modules
+        search_result = []
+
+        def callback(path, modname, desc):
+            if modname[-9:] == '.__init__':
+                modname = modname[:-9] + ' (package)'
+            search_result.append((modname, desc and '- ' + desc))
+
+        with warnings.catch_warnings():
+            warnings.filterwarnings('ignore') # ignore problems during import
+            ModuleScanner().run(callback, key)
+
+        # format page
+        def bltinlink(name):
+            return '<a href="%s.html">%s</a>' % (name, name)
+
+        results = []
+        heading = html.heading(
+            '<big><big><strong>Search Results</strong></big></big>',
+            '#ffffff', '#7799ee')
+        for name, desc in search_result:
+            results.append(bltinlink(name) + desc)
+        contents = heading + html.bigsection(
+            'key = %s' % key, '#ffffff', '#ee77aa', '<br>'.join(results))
+        return 'Search Results', contents
+
+    def html_getfile(path):
+        """Get and display a source file listing safely."""
+        path = path.replace('%20', ' ')
+        with open(path, 'r') as fp:
+            lines = html.escape(fp.read())
+        body = '<pre>%s</pre>' % lines
+        heading = html.heading(
+            '<big><big><strong>File Listing</strong></big></big>',
+            '#ffffff', '#7799ee')
+        contents = heading + html.bigsection(
+            'File: %s' % path, '#ffffff', '#ee77aa', body)
+        return 'getfile %s' % path, contents
+
+    def html_topics():
+        """Index of topic texts available."""
+
+        def bltinlink(name):
+            return '<a href="topic?key=%s">%s</a>' % (name, name)
+
+        heading = html.heading(
+            '<big><big><strong>INDEX</strong></big></big>',
+            '#ffffff', '#7799ee')
+        names = sorted(Helper.topics.keys())
+
+        contents = html.multicolumn(names, bltinlink)
+        contents = heading + html.bigsection(
+            'Topics', '#ffffff', '#ee77aa', contents)
+        return 'Topics', contents
+
+    def html_keywords():
+        """Index of keywords."""
+        heading = html.heading(
+            '<big><big><strong>INDEX</strong></big></big>',
+            '#ffffff', '#7799ee')
+        names = sorted(Helper.keywords.keys())
+
+        def bltinlink(name):
+            return '<a href="topic?key=%s">%s</a>' % (name, name)
+
+        contents = html.multicolumn(names, bltinlink)
+        contents = heading + html.bigsection(
+            'Keywords', '#ffffff', '#ee77aa', contents)
+        return 'Keywords', contents
+
+    def html_topicpage(topic):
+        """Topic or keyword help page."""
+        buf = io.StringIO()
+        htmlhelp = Helper(buf, buf)
+        contents, xrefs = htmlhelp._gettopic(topic)
+        if topic in htmlhelp.keywords:
+            title = 'KEYWORD'
+        else:
+            title = 'TOPIC'
+        heading = html.heading(
+            '<big><big><strong>%s</strong></big></big>' % title,
+            '#ffffff', '#7799ee')
+        contents = '<pre>%s</pre>' % html.markup(contents)
+        contents = html.bigsection(topic , '#ffffff','#ee77aa', contents)
+        if xrefs:
+            xrefs = sorted(xrefs.split())
+
+            def bltinlink(name):
+                return '<a href="topic?key=%s">%s</a>' % (name, name)
+
+            xrefs = html.multicolumn(xrefs, bltinlink)
+            xrefs = html.section('Related help topics: ',
+                                 '#ffffff', '#ee77aa', xrefs)
+        return ('%s %s' % (title, topic),
+                ''.join((heading, contents, xrefs)))
+
+    def html_getobj(url):
+        obj = locate(url, forceload=1)
+        if obj is None and url != 'None':
+            raise ValueError('could not find object')
+        title = describe(obj)
+        content = html.document(obj, url)
+        return title, content
+
+    def html_error(url, exc):
+        heading = html.heading(
+            '<big><big><strong>Error</strong></big></big>',
+            '#ffffff', '#7799ee')
+        contents = '<br>'.join(html.escape(line) for line in
+                               format_exception_only(type(exc), exc))
+        contents = heading + html.bigsection(url, '#ffffff', '#bb0000',
+                                             contents)
+        return "Error - %s" % url, contents
+
+    def get_html_page(url):
+        """Generate an HTML page for url."""
+        complete_url = url
+        if url.endswith('.html'):
+            url = url[:-5]
+        try:
+            if url in ("", "index"):
+                title, content = html_index()
+            elif url == "topics":
+                title, content = html_topics()
+            elif url == "keywords":
+                title, content = html_keywords()
+            elif '=' in url:
+                op, _, url = url.partition('=')
+                if op == "search?key":
+                    title, content = html_search(url)
+                elif op == "getfile?key":
+                    title, content = html_getfile(url)
+                elif op == "topic?key":
+                    # try topics first, then objects.
+                    try:
+                        title, content = html_topicpage(url)
+                    except ValueError:
+                        title, content = html_getobj(url)
+                elif op == "get?key":
+                    # try objects first, then topics.
+                    if url in ("", "index"):
+                        title, content = html_index()
+                    else:
+                        try:
+                            title, content = html_getobj(url)
+                        except ValueError:
+                            title, content = html_topicpage(url)
+                else:
+                    raise ValueError('bad pydoc url')
+            else:
+                title, content = html_getobj(url)
+        except Exception as exc:
+            # Catch any errors and display them in an error page.
+            title, content = html_error(complete_url, exc)
+        return html.page(title, content)
+
+    if url.startswith('/'):
+        url = url[1:]
+    if content_type == 'text/css':
+        path_here = os.path.dirname(os.path.realpath(__file__))
+        css_path = os.path.join(path_here, url)
+        with open(css_path) as fp:
+            return ''.join(fp.readlines())
+    elif content_type == 'text/html':
+        return get_html_page(url)
+    # Errors outside the url handler are caught by the server.
+    raise TypeError('unknown content type %r for url %s' % (content_type, url))
+
+
+def browse(port=0, *, open_browser=True):
+    """Start the enhanced pydoc Web server and open a Web browser.
+
+    Use port '0' to start the server on an arbitrary port.
+    Set open_browser to False to suppress opening a browser.
+    """
+    import webbrowser
+    serverthread = _start_server(_url_handler, port)
+    if serverthread.error:
+        print(serverthread.error)
+        return
+    if serverthread.serving:
+        server_help_msg = 'Server commands: [b]rowser, [q]uit'
+        if open_browser:
+            webbrowser.open(serverthread.url)
+        try:
+            print('Server ready at', serverthread.url)
+            print(server_help_msg)
+            while serverthread.serving:
+                cmd = input('server> ')
+                cmd = cmd.lower()
+                if cmd == 'q':
+                    break
+                elif cmd == 'b':
+                    webbrowser.open(serverthread.url)
+                else:
+                    print(server_help_msg)
+        except (KeyboardInterrupt, EOFError):
+            print()
+        finally:
+            if serverthread.serving:
+                serverthread.stop()
+                print('Server stopped')
+
+
 # -------------------------------------------------- command-line interface
 
 def ispath(x):
@@ -2257,29 +2766,32 @@
         sys.path.insert(0, '.')
 
     try:
-        opts, args = getopt.getopt(sys.argv[1:], 'gk:p:w')
-        writing = 0
-
+        opts, args = getopt.getopt(sys.argv[1:], 'bgk:p:w')
+        writing = False
+        start_server = False
+        open_browser = False
+        port = None
         for opt, val in opts:
             if opt == '-g':
                 gui()
                 return
+            if opt == '-b':
+                start_server = True
+                open_browser = True
             if opt == '-k':
                 apropos(val)
                 return
             if opt == '-p':
-                try:
-                    port = int(val)
-                except ValueError:
-                    raise BadUsage
-                def ready(server):
-                    print('pydoc server ready at %s' % server.url)
-                def stopped():
-                    print('pydoc server stopped')
-                serve(port, ready, stopped)
-                return
+                start_server = True
+                port = val
             if opt == '-w':
-                writing = 1
+                writing = True
+
+        if start_server == True:
+            if port == None:
+                port = 0
+            browse(port, open_browser=open_browser)
+            return
 
         if not args: raise BadUsage
         for arg in args:
@@ -2300,30 +2812,37 @@
                 print(value)
 
     except (getopt.error, BadUsage):
-        cmd = os.path.basename(sys.argv[0])
+        cmd = os.path.splitext(os.path.basename(sys.argv[0]))[0]
         print("""pydoc - the Python documentation tool
 
-%s <name> ...
+{cmd} <name> ...
     Show text documentation on something.  <name> may be the name of a
     Python keyword, topic, function, module, or package, or a dotted
     reference to a class or function within a module or module in a
-    package.  If <name> contains a '%s', it is used as the path to a
+    package.  If <name> contains a '{sep}', it is used as the path to a
     Python source file to document. If name is 'keywords', 'topics',
     or 'modules', a listing of these things is displayed.
 
-%s -k <keyword>
+{cmd} -k <keyword>
     Search for a keyword in the synopsis lines of all available modules.
 
-%s -p <port>
-    Start an HTTP server on the given port on the local machine.
+{cmd} -p <port>
+    Start an HTTP server on the given port on the local machine.  Port
+    number 0 can be used to get an arbitrary unused port.
+
+{cmd} -b
+    Start an HTTP server on an arbitrary unused port and open a Web browser
+    to interactively browse documentation.  The -p option can be used with
+    the -b option to explicitly specify the server port.
 
-%s -g
-    Pop up a graphical interface for finding and serving documentation.
+{cmd} -g
+    Deprecated.
 
-%s -w <name> ...
+{cmd} -w <name> ...
     Write out the HTML documentation for a module to a file in the current
-    directory.  If <name> contains a '%s', it is treated as a filename; if
+    directory.  If <name> contains a '{sep}', it is treated as a filename; if
     it names a directory, documentation is written for all the contents.
-""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep))
+""".format(cmd=cmd, sep=os.sep))
 
-if __name__ == '__main__': cli()
+if __name__ == '__main__':
+    cli()

Modified: python/branches/pep-3151/Lib/pydoc_data/topics.py
==============================================================================
--- python/branches/pep-3151/Lib/pydoc_data/topics.py	(original)
+++ python/branches/pep-3151/Lib/pydoc_data/topics.py	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,4 @@
-# Autogenerated by Sphinx on Sun Oct 10 11:36:38 2010
+# Autogenerated by Sphinx on Sun Feb 20 10:16:17 2011
 topics = {'assert': '\nThe ``assert`` statement\n************************\n\nAssert statements are a convenient way to insert debugging assertions\ninto a program:\n\n   assert_stmt ::= "assert" expression ["," expression]\n\nThe simple form, ``assert expression``, is equivalent to\n\n   if __debug__:\n      if not expression: raise AssertionError\n\nThe extended form, ``assert expression1, expression2``, is equivalent\nto\n\n   if __debug__:\n      if not expression1: raise AssertionError(expression2)\n\nThese equivalences assume that ``__debug__`` and ``AssertionError``\nrefer to the built-in variables with those names.  In the current\nimplementation, the built-in variable ``__debug__`` is ``True`` under\nnormal circumstances, ``False`` when optimization is requested\n(command line option -O).  The current code generator emits no code\nfor an assert statement when optimization is requested at compile\ntime.  Note that it is unnecessary to include the source code for the\nexpression that failed in the error message; it will be displayed as\npart of the stack trace.\n\nAssignments to ``__debug__`` are illegal.  The value for the built-in\nvariable is determined when the interpreter starts.\n',
  'assignment': '\nAssignment statements\n*********************\n\nAssignment statements are used to (re)bind names to values and to\nmodify attributes or items of mutable objects:\n\n   assignment_stmt ::= (target_list "=")+ (expression_list | yield_expression)\n   target_list     ::= target ("," target)* [","]\n   target          ::= identifier\n              | "(" target_list ")"\n              | "[" target_list "]"\n              | attributeref\n              | subscription\n              | slicing\n              | "*" target\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn assignment statement evaluates the expression list (remember that\nthis can be a single expression or a comma-separated list, the latter\nyielding a tuple) and assigns the single resulting object to each of\nthe target lists, from left to right.\n\nAssignment is defined recursively depending on the form of the target\n(list). When a target is part of a mutable object (an attribute\nreference, subscription or slicing), the mutable object must\nultimately perform the assignment and decide about its validity, and\nmay raise an exception if the assignment is unacceptable.  The rules\nobserved by various types and the exceptions raised are given with the\ndefinition of the object types (see section *The standard type\nhierarchy*).\n\nAssignment of an object to a target list, optionally enclosed in\nparentheses or square brackets, is recursively defined as follows.\n\n* If the target list is a single target: The object is assigned to\n  that target.\n\n* If the target list is a comma-separated list of targets: The object\n  must be an iterable with the same number of items as there are\n  targets in the target list, and the items are assigned, from left to\n  right, to the corresponding targets. (This rule is relaxed as of\n  Python 1.5; in earlier versions, the object had to be a tuple.\n  Since strings are sequences, an assignment like ``a, b = "xy"`` is\n  now legal as long as the string has the right length.)\n\n  * If the target list contains one target prefixed with an asterisk,\n    called a "starred" target: The object must be a sequence with at\n    least as many items as there are targets in the target list, minus\n    one.  The first items of the sequence are assigned, from left to\n    right, to the targets before the starred target.  The final items\n    of the sequence are assigned to the targets after the starred\n    target.  A list of the remaining items in the sequence is then\n    assigned to the starred target (the list can be empty).\n\n  * Else: The object must be a sequence with the same number of items\n    as there are targets in the target list, and the items are\n    assigned, from left to right, to the corresponding targets.\n\nAssignment of an object to a single target is recursively defined as\nfollows.\n\n* If the target is an identifier (name):\n\n  * If the name does not occur in a ``global`` or ``nonlocal``\n    statement in the current code block: the name is bound to the\n    object in the current local namespace.\n\n  * Otherwise: the name is bound to the object in the global namespace\n    or the outer namespace determined by ``nonlocal``, respectively.\n\n  The name is rebound if it was already bound.  This may cause the\n  reference count for the object previously bound to the name to reach\n  zero, causing the object to be deallocated and its destructor (if it\n  has one) to be called.\n\n* If the target is a target list enclosed in parentheses or in square\n  brackets: The object must be an iterable with the same number of\n  items as there are targets in the target list, and its items are\n  assigned, from left to right, to the corresponding targets.\n\n* If the target is an attribute reference: The primary expression in\n  the reference is evaluated.  It should yield an object with\n  assignable attributes; if this is not the case, ``TypeError`` is\n  raised.  That object is then asked to assign the assigned object to\n  the given attribute; if it cannot perform the assignment, it raises\n  an exception (usually but not necessarily ``AttributeError``).\n\n  Note: If the object is a class instance and the attribute reference\n  occurs on both sides of the assignment operator, the RHS expression,\n  ``a.x`` can access either an instance attribute or (if no instance\n  attribute exists) a class attribute.  The LHS target ``a.x`` is\n  always set as an instance attribute, creating it if necessary.\n  Thus, the two occurrences of ``a.x`` do not necessarily refer to the\n  same attribute: if the RHS expression refers to a class attribute,\n  the LHS creates a new instance attribute as the target of the\n  assignment:\n\n     class Cls:\n         x = 3             # class variable\n     inst = Cls()\n     inst.x = inst.x + 1   # writes inst.x as 4 leaving Cls.x as 3\n\n  This description does not necessarily apply to descriptor\n  attributes, such as properties created with ``property()``.\n\n* If the target is a subscription: The primary expression in the\n  reference is evaluated.  It should yield either a mutable sequence\n  object (such as a list) or a mapping object (such as a dictionary).\n  Next, the subscript expression is evaluated.\n\n  If the primary is a mutable sequence object (such as a list), the\n  subscript must yield an integer.  If it is negative, the sequence\'s\n  length is added to it.  The resulting value must be a nonnegative\n  integer less than the sequence\'s length, and the sequence is asked\n  to assign the assigned object to its item with that index.  If the\n  index is out of range, ``IndexError`` is raised (assignment to a\n  subscripted sequence cannot add new items to a list).\n\n  If the primary is a mapping object (such as a dictionary), the\n  subscript must have a type compatible with the mapping\'s key type,\n  and the mapping is then asked to create a key/datum pair which maps\n  the subscript to the assigned object.  This can either replace an\n  existing key/value pair with the same key value, or insert a new\n  key/value pair (if no key with the same value existed).\n\n  For user-defined objects, the ``__setitem__()`` method is called\n  with appropriate arguments.\n\n* If the target is a slicing: The primary expression in the reference\n  is evaluated.  It should yield a mutable sequence object (such as a\n  list).  The assigned object should be a sequence object of the same\n  type.  Next, the lower and upper bound expressions are evaluated,\n  insofar they are present; defaults are zero and the sequence\'s\n  length.  The bounds should evaluate to integers. If either bound is\n  negative, the sequence\'s length is added to it.  The resulting\n  bounds are clipped to lie between zero and the sequence\'s length,\n  inclusive.  Finally, the sequence object is asked to replace the\n  slice with the items of the assigned sequence.  The length of the\n  slice may be different from the length of the assigned sequence,\n  thus changing the length of the target sequence, if the object\n  allows it.\n\n**CPython implementation detail:** In the current implementation, the\nsyntax for targets is taken to be the same as for expressions, and\ninvalid syntax is rejected during the code generation phase, causing\nless detailed error messages.\n\nWARNING: Although the definition of assignment implies that overlaps\nbetween the left-hand side and the right-hand side are \'safe\' (for\nexample ``a, b = b, a`` swaps two variables), overlaps *within* the\ncollection of assigned-to variables are not safe!  For instance, the\nfollowing program prints ``[0, 2]``:\n\n   x = [0, 1]\n   i = 0\n   i, x[i] = 1, 2\n   print(x)\n\nSee also:\n\n   **PEP 3132** - Extended Iterable Unpacking\n      The specification for the ``*target`` feature.\n\n\nAugmented assignment statements\n===============================\n\nAugmented assignment is the combination, in a single statement, of a\nbinary operation and an assignment statement:\n\n   augmented_assignment_stmt ::= augtarget augop (expression_list | yield_expression)\n   augtarget                 ::= identifier | attributeref | subscription | slicing\n   augop                     ::= "+=" | "-=" | "*=" | "/=" | "//=" | "%=" | "**="\n             | ">>=" | "<<=" | "&=" | "^=" | "|="\n\n(See section *Primaries* for the syntax definitions for the last three\nsymbols.)\n\nAn augmented assignment evaluates the target (which, unlike normal\nassignment statements, cannot be an unpacking) and the expression\nlist, performs the binary operation specific to the type of assignment\non the two operands, and assigns the result to the original target.\nThe target is only evaluated once.\n\nAn augmented assignment expression like ``x += 1`` can be rewritten as\n``x = x + 1`` to achieve a similar, but not exactly equal effect. In\nthe augmented version, ``x`` is only evaluated once. Also, when\npossible, the actual operation is performed *in-place*, meaning that\nrather than creating a new object and assigning that to the target,\nthe old object is modified instead.\n\nWith the exception of assigning to tuples and multiple targets in a\nsingle statement, the assignment done by augmented assignment\nstatements is handled the same way as normal assignments. Similarly,\nwith the exception of the possible *in-place* behavior, the binary\noperation performed by augmented assignment is the same as the normal\nbinary operations.\n\nFor targets which are attribute references, the same *caveat about\nclass and instance attributes* applies as for regular assignments.\n',
  'atom-identifiers': '\nIdentifiers (Names)\n*******************\n\nAn identifier occurring as an atom is a name.  See section\n*Identifiers and keywords* for lexical definition and section *Naming\nand binding* for documentation of naming and binding.\n\nWhen the name is bound to an object, evaluation of the atom yields\nthat object. When a name is not bound, an attempt to evaluate it\nraises a ``NameError`` exception.\n\n**Private name mangling:** When an identifier that textually occurs in\na class definition begins with two or more underscore characters and\ndoes not end in two or more underscores, it is considered a *private\nname* of that class. Private names are transformed to a longer form\nbefore code is generated for them.  The transformation inserts the\nclass name in front of the name, with leading underscores removed, and\na single underscore inserted in front of the class name.  For example,\nthe identifier ``__spam`` occurring in a class named ``Ham`` will be\ntransformed to ``_Ham__spam``.  This transformation is independent of\nthe syntactical context in which the identifier is used.  If the\ntransformed name is extremely long (longer than 255 characters),\nimplementation defined truncation may happen.  If the class name\nconsists only of underscores, no transformation is done.\n',
@@ -16,41 +16,41 @@
  'break': '\nThe ``break`` statement\n***********************\n\n   break_stmt ::= "break"\n\n``break`` may only occur syntactically nested in a ``for`` or\n``while`` loop, but not nested in a function or class definition\nwithin that loop.\n\nIt terminates the nearest enclosing loop, skipping the optional\n``else`` clause if the loop has one.\n\nIf a ``for`` loop is terminated by ``break``, the loop control target\nkeeps its current value.\n\nWhen ``break`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nleaving the loop.\n',
  'callable-types': '\nEmulating callable objects\n**************************\n\nobject.__call__(self[, args...])\n\n   Called when the instance is "called" as a function; if this method\n   is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n   ``x.__call__(arg1, arg2, ...)``.\n',
  'calls': '\nCalls\n*****\n\nA call calls a callable object (e.g., a function) with a possibly\nempty series of arguments:\n\n   call                 ::= primary "(" [argument_list [","] | comprehension] ")"\n   argument_list        ::= positional_arguments ["," keyword_arguments]\n                       ["," "*" expression] ["," keyword_arguments]\n                       ["," "**" expression]\n                     | keyword_arguments ["," "*" expression]\n                       ["," keyword_arguments] ["," "**" expression]\n                     | "*" expression ["," keyword_arguments] ["," "**" expression]\n                     | "**" expression\n   positional_arguments ::= expression ("," expression)*\n   keyword_arguments    ::= keyword_item ("," keyword_item)*\n   keyword_item         ::= identifier "=" expression\n\nA trailing comma may be present after the positional and keyword\narguments but does not affect the semantics.\n\nThe primary must evaluate to a callable object (user-defined\nfunctions, built-in functions, methods of built-in objects, class\nobjects, methods of class instances, and all objects having a\n``__call__()`` method are callable).  All argument expressions are\nevaluated before the call is attempted.  Please refer to section\n*Function definitions* for the syntax of formal parameter lists.\n\nIf keyword arguments are present, they are first converted to\npositional arguments, as follows.  First, a list of unfilled slots is\ncreated for the formal parameters.  If there are N positional\narguments, they are placed in the first N slots.  Next, for each\nkeyword argument, the identifier is used to determine the\ncorresponding slot (if the identifier is the same as the first formal\nparameter name, the first slot is used, and so on).  If the slot is\nalready filled, a ``TypeError`` exception is raised. Otherwise, the\nvalue of the argument is placed in the slot, filling it (even if the\nexpression is ``None``, it fills the slot).  When all arguments have\nbeen processed, the slots that are still unfilled are filled with the\ncorresponding default value from the function definition.  (Default\nvalues are calculated, once, when the function is defined; thus, a\nmutable object such as a list or dictionary used as default value will\nbe shared by all calls that don\'t specify an argument value for the\ncorresponding slot; this should usually be avoided.)  If there are any\nunfilled slots for which no default value is specified, a\n``TypeError`` exception is raised.  Otherwise, the list of filled\nslots is used as the argument list for the call.\n\n**CPython implementation detail:** An implementation may provide\nbuilt-in functions whose positional parameters do not have names, even\nif they are \'named\' for the purpose of documentation, and which\ntherefore cannot be supplied by keyword.  In CPython, this is the case\nfor functions implemented in C that use ``PyArg_ParseTuple()`` to\nparse their arguments.\n\nIf there are more positional arguments than there are formal parameter\nslots, a ``TypeError`` exception is raised, unless a formal parameter\nusing the syntax ``*identifier`` is present; in this case, that formal\nparameter receives a tuple containing the excess positional arguments\n(or an empty tuple if there were no excess positional arguments).\n\nIf any keyword argument does not correspond to a formal parameter\nname, a ``TypeError`` exception is raised, unless a formal parameter\nusing the syntax ``**identifier`` is present; in this case, that\nformal parameter receives a dictionary containing the excess keyword\narguments (using the keywords as keys and the argument values as\ncorresponding values), or a (new) empty dictionary if there were no\nexcess keyword arguments.\n\nIf the syntax ``*expression`` appears in the function call,\n``expression`` must evaluate to a sequence.  Elements from this\nsequence are treated as if they were additional positional arguments;\nif there are positional arguments *x1*,..., *xN*, and ``expression``\nevaluates to a sequence *y1*, ..., *yM*, this is equivalent to a call\nwith M+N positional arguments *x1*, ..., *xN*, *y1*, ..., *yM*.\n\nA consequence of this is that although the ``*expression`` syntax may\nappear *after* some keyword arguments, it is processed *before* the\nkeyword arguments (and the ``**expression`` argument, if any -- see\nbelow).  So:\n\n   >>> def f(a, b):\n   ...  print(a, b)\n   ...\n   >>> f(b=1, *(2,))\n   2 1\n   >>> f(a=1, *(2,))\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n   TypeError: f() got multiple values for keyword argument \'a\'\n   >>> f(1, *(2,))\n   1 2\n\nIt is unusual for both keyword arguments and the ``*expression``\nsyntax to be used in the same call, so in practice this confusion does\nnot arise.\n\nIf the syntax ``**expression`` appears in the function call,\n``expression`` must evaluate to a mapping, the contents of which are\ntreated as additional keyword arguments.  In the case of a keyword\nappearing in both ``expression`` and as an explicit keyword argument,\na ``TypeError`` exception is raised.\n\nFormal parameters using the syntax ``*identifier`` or ``**identifier``\ncannot be used as positional argument slots or as keyword argument\nnames.\n\nA call always returns some value, possibly ``None``, unless it raises\nan exception.  How this value is computed depends on the type of the\ncallable object.\n\nIf it is---\n\na user-defined function:\n   The code block for the function is executed, passing it the\n   argument list.  The first thing the code block will do is bind the\n   formal parameters to the arguments; this is described in section\n   *Function definitions*.  When the code block executes a ``return``\n   statement, this specifies the return value of the function call.\n\na built-in function or method:\n   The result is up to the interpreter; see *Built-in Functions* for\n   the descriptions of built-in functions and methods.\n\na class object:\n   A new instance of that class is returned.\n\na class instance method:\n   The corresponding user-defined function is called, with an argument\n   list that is one longer than the argument list of the call: the\n   instance becomes the first argument.\n\na class instance:\n   The class must define a ``__call__()`` method; the effect is then\n   the same as if that method was called.\n',
- 'class': '\nClass definitions\n*****************\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [argument_list [","] ] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing.\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.)  When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated; as with functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances.  Instance attributes\ncan be set in a method with ``self.name = value``.  Both class and\ninstance attributes are accessible through the notation\n"``self.name``", and an instance attribute hides a class attribute\nwith the same name when accessed in this way.  Class attributes can be\nused as defaults for instance attributes, but using mutable values\nthere can lead to unexpected results.  *Descriptors* can be used to\ncreate instance variables with different implementation details.\n\nSee also:\n\n   **PEP 3116** - Metaclasses in Python 3 **PEP 3129** - Class\n   Decorators\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack only if there\n    is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n    exception or the execution of a ``return``, ``continue``, or\n    ``break`` statement.\n\n[3] A string literal appearing as the first statement in the function\n    body is transformed into the function\'s ``__doc__`` attribute and\n    therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n    body is transformed into the namespace\'s ``__doc__`` item and\n    therefore the class\'s *docstring*.\n',
+ 'class': '\nClass definitions\n*****************\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [argument_list [","] | comprehension] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing.  Classes without an inheritance\nlist inherit, by default, from the base class ``object``; hence,\n\n   class Foo:\n       pass\n\nis equivalent to\n\n   class Foo(object):\n       pass\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.)  When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated: just like when decorating functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\nThe evaluation rules for the decorator expressions are the same as for\nfunction decorators.  The result must be a class object, which is then\nbound to the class name.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances.  Instance attributes\ncan be set in a method with ``self.name = value``.  Both class and\ninstance attributes are accessible through the notation\n"``self.name``", and an instance attribute hides a class attribute\nwith the same name when accessed in this way.  Class attributes can be\nused as defaults for instance attributes, but using mutable values\nthere can lead to unexpected results.  *Descriptors* can be used to\ncreate instance variables with different implementation details.\n\nSee also:\n\n   **PEP 3116** - Metaclasses in Python 3 **PEP 3129** - Class\n   Decorators\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack only if there\n    is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n    exception or the execution of a ``return``, ``continue``, or\n    ``break`` statement.\n\n[3] A string literal appearing as the first statement in the function\n    body is transformed into the function\'s ``__doc__`` attribute and\n    therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n    body is transformed into the namespace\'s ``__doc__`` item and\n    therefore the class\'s *docstring*.\n',
  'comparisons': '\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation.  Also unlike C, expressions like ``a < b < c`` have the\ninterpretation that is conventional in mathematics:\n\n   comparison    ::= or_expr ( comp_operator or_expr )*\n   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n                     | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: ``True`` or ``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects.  The objects need not have the same type.\nIf both are numbers, they are converted to a common type.  Otherwise,\nthe ``==`` and ``!=`` operators *always* consider objects of different\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\noperators raise a ``TypeError`` when comparing objects of different\ntypes that do not implement these operators for the given pair of\ntypes.  You can control comparison behavior of objects of non-built-in\ntypes by defining rich comparison methods like ``__gt__()``, described\nin section *Basic customization*.\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* The values ``float(\'NaN\')`` and ``Decimal(\'NaN\')`` are special. The\n  are identical to themselves, ``x is x`` but are not equal to\n  themselves, ``x != x``.  Additionally, comparing any value to a\n  not-a-number value will return ``False``.  For example, both ``3 <\n  float(\'NaN\')`` and ``float(\'NaN\') < 3`` will return ``False``.\n\n* Bytes objects are compared lexicographically using the numeric\n  values of their elements.\n\n* Strings are compared lexicographically using the numeric equivalents\n  (the result of the built-in function ``ord()``) of their characters.\n  [3] String and bytes object can\'t be compared!\n\n* Tuples and lists are compared lexicographically using comparison of\n  corresponding elements.  This means that to compare equal, each\n  element must compare equal and the two sequences must be of the same\n  type and have the same length.\n\n  If not equal, the sequences are ordered the same as their first\n  differing elements.  For example, ``[1,2,x] <= [1,2,y]`` has the\n  same value as ``x <= y``.  If the corresponding element does not\n  exist, the shorter sequence is ordered first (for example, ``[1,2] <\n  [1,2,3]``).\n\n* Mappings (dictionaries) compare equal if and only if they have the\n  same ``(key, value)`` pairs. Order comparisons ``(\'<\', \'<=\', \'>=\',\n  \'>\')`` raise ``TypeError``.\n\n* Sets and frozensets define comparison operators to mean subset and\n  superset tests.  Those relations do not define total orderings (the\n  two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\n  another, nor supersets of one another).  Accordingly, sets are not\n  appropriate arguments for functions which depend on total ordering.\n  For example, ``min()``, ``max()``, and ``sorted()`` produce\n  undefined results given a list of sets as inputs.\n\n* Most other objects of built-in types compare unequal unless they are\n  the same object; the choice whether one object is considered smaller\n  or larger than another one is made arbitrarily but consistently\n  within one execution of a program.\n\nComparison of objects of the differing types depends on whether either\nof the types provide explicit support for the comparison.  Most\nnumeric types can be compared with one another, but comparisons of\n``float`` and ``Decimal`` are not supported to avoid the inevitable\nconfusion arising from representation issues such as ``float(\'1.1\')``\nbeing inexactly represented and therefore not exactly equal to\n``Decimal(\'1.1\')`` which is.  When cross-type comparison is not\nsupported, the comparison method returns ``NotImplemented``.  This can\ncreate the illusion of non-transitivity between supported cross-type\ncomparisons and unsupported comparisons.  For example, ``Decimal(2) ==\n2`` and ``2 == float(2)`` but ``Decimal(2) != float(2)``.\n\nThe operators ``in`` and ``not in`` test for membership.  ``x in s``\nevaluates to true if *x* is a member of *s*, and false otherwise.  ``x\nnot in s`` returns the negation of ``x in s``.  All built-in sequences\nand set types support this as well as dictionary, for which ``in``\ntests whether a the dictionary has a given key. For container types\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for e in\ny)``.\n\nFor the string and bytes types, ``x in y`` is true if and only if *x*\nis a substring of *y*.  An equivalent test is ``y.find(x) != -1``.\nEmpty strings are always considered to be a substring of any other\nstring, so ``"" in "abc"`` will return ``True``.\n\nFor user-defined classes which define the ``__contains__()`` method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\n== z`` is produced while iterating over ``y``.  If an exception is\nraised during the iteration, it is as if ``in`` raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n``__getitem__()``, ``x in y`` is true if and only if there is a non-\nnegative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception.  (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object.  ``x is\nnot y`` yields the inverse truth value. [4]\n',
- 'compound': '\nCompound statements\n*******************\n\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way.  In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\n\nThe ``if``, ``while`` and ``for`` statements implement traditional\ncontrol flow constructs.  ``try`` specifies exception handlers and/or\ncleanup code for a group of statements, while the ``with`` statement\nallows the execution of initialization and finalization code around a\nblock of code.  Function and class definitions are also syntactically\ncompound statements.\n\nCompound statements consist of one or more \'clauses.\'  A clause\nconsists of a header and a \'suite.\'  The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon.  A suite is a group of statements controlled by a\nclause.  A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header\'s\ncolon, or it can be one or more indented statements on subsequent\nlines.  Only the latter form of suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn\'t be\nclear to which ``if`` clause a following ``else`` clause would belong:\n\n   if test1: if test2: print(x)\n\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\n``print()`` calls are executed:\n\n   if x < y < z: print(x); print(y); print(z)\n\nSummarizing:\n\n   compound_stmt ::= if_stmt\n                     | while_stmt\n                     | for_stmt\n                     | try_stmt\n                     | with_stmt\n                     | funcdef\n                     | classdef\n   suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\n   statement     ::= stmt_list NEWLINE | compound_stmt\n   stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]\n\nNote that statements always end in a ``NEWLINE`` possibly followed by\na ``DEDENT``.  Also note that optional continuation clauses always\nbegin with a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling ``else``\' problem is solved in Python by\nrequiring nested ``if`` statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\nThe ``if`` statement\n====================\n\nThe ``if`` statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n\n\nThe ``while`` statement\n=======================\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n   while_stmt ::= "while" expression ":" suite\n                  ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n\n\nThe ``for`` statement\n=====================\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n   for_stmt ::= "for" target_list "in" expression_list ":" suite\n                ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject.  An iterator is created for the result of the\n``expression_list``.  The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices.  Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted.  When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a ``StopIteration``\nexception), the suite in the ``else`` clause, if present, is executed,\nand the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, it will not have been assigned to at all\nby the loop.  Hint: the built-in function ``range()`` returns an\niterator of integers suitable to emulate the effect of Pascal\'s ``for\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\n2]``.\n\nNote: There is a subtlety when the sequence is being modified by the loop\n  (this can only occur for mutable sequences, i.e. lists).  An\n  internal counter is used to keep track of which item is used next,\n  and this is incremented on each iteration.  When this counter has\n  reached the length of the sequence the loop terminates.  This means\n  that if the suite deletes the current (or a previous) item from the\n  sequence, the next item will be skipped (since it gets the index of\n  the current item which has already been treated).  Likewise, if the\n  suite inserts an item in the sequence before the current item, the\n  current item will be treated again the next time through the loop.\n  This can lead to nasty bugs that can be avoided by making a\n  temporary copy using a slice of the whole sequence, e.g.,\n\n     for x in a[:]:\n         if x < 0: a.remove(x)\n\n\nThe ``try`` statement\n=====================\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" target]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started.  This search inspects the except\nclauses in turn until one is found that matches the exception.  An\nexpression-less except clause, if present, must be last; it matches\nany exception.  For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception.  An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause.  Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting\nof: ``exc_type``, the exception class; ``exc_value``, the exception\ninstance; ``exc_traceback``, a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. ``sys.exc_info()`` values are restored to\ntheir previous values (before the call) when returning from a function\nthat handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler.  The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses.  If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted.  If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost.  The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n\n\nThe ``with`` statement\n======================\n\nThe ``with`` statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n   with_stmt ::= "with" with_item ("," with_item)* ":" suite\n   with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression (the expression given in the ``with_item``)\n   is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. If a target was included in the ``with`` statement, the return\n   value from ``__enter__()`` is assigned to it.\n\n   Note: The ``with`` statement guarantees that if the ``__enter__()``\n     method returns without an error, then ``__exit__()`` will always\n     be called. Thus, if an error occurs during the assignment to the\n     target list, it will be treated the same as an error occurring\n     within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s ``__exit__()`` method is invoked.  If an\n   exception caused the suite to be exited, its type, value, and\n   traceback are passed as arguments to ``__exit__()``. Otherwise,\n   three ``None`` arguments are supplied.\n\n   If the suite was exited due to an exception, and the return value\n   from the ``__exit__()`` method was false, the exception is\n   reraised.  If the return value was true, the exception is\n   suppressed, and execution continues with the statement following\n   the ``with`` statement.\n\n   If the suite was exited for any reason other than an exception, the\n   return value from ``__exit__()`` is ignored, and execution proceeds\n   at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n   with A() as a, B() as b:\n       suite\n\nis equivalent to\n\n   with A() as a:\n       with B() as b:\n           suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" [parameter] ("," defparameter)*\n                      [, "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nWhen one or more parameters have the form *parameter* ``=``\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding argument may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the "``*``" must also have a default value ---\nthis is a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated when the function definition\nis executed.** This means that the expression is evaluated once, when\nthe function is defined, and that that same "pre-computed" value is\nused for each call.  This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended.  A way around this is to use ``None`` as the\ndefault, and explicitly test for it in the body of the function, e.g.:\n\n   def whats_on_the_telly(penguin=None):\n       if penguin is None:\n           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple.  If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after "``*``" or "``*identifier``" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "``: expression``"\nfollowing the parameter name.  Any parameter may have an annotation\neven those of the form ``*identifier`` or ``**identifier``.  Functions\nmay have "return" annotation of the form "``-> expression``" after the\nparameter list.  These annotations can be any valid Python expression\nand are evaluated when the function definition is executed.\nAnnotations may be evaluated in a different order than they appear in\nthe source code.  The presence of annotations does not change the\nsemantics of a function.  The annotation values are available as\nvalues of a dictionary keyed by the parameters\' names in the\n``__annotations__`` attribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda forms,\ndescribed in section *Lambdas*.  Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form.  The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A "``def``"\nform executed inside a function definition defines a local function\nthat can be returned or passed around.  Free variables used in the\nnested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n\n\nClass definitions\n=================\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [argument_list [","] ] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing.\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.)  When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated; as with functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances.  Instance attributes\ncan be set in a method with ``self.name = value``.  Both class and\ninstance attributes are accessible through the notation\n"``self.name``", and an instance attribute hides a class attribute\nwith the same name when accessed in this way.  Class attributes can be\nused as defaults for instance attributes, but using mutable values\nthere can lead to unexpected results.  *Descriptors* can be used to\ncreate instance variables with different implementation details.\n\nSee also:\n\n   **PEP 3116** - Metaclasses in Python 3 **PEP 3129** - Class\n   Decorators\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack only if there\n    is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n    exception or the execution of a ``return``, ``continue``, or\n    ``break`` statement.\n\n[3] A string literal appearing as the first statement in the function\n    body is transformed into the function\'s ``__doc__`` attribute and\n    therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n    body is transformed into the namespace\'s ``__doc__`` item and\n    therefore the class\'s *docstring*.\n',
+ 'compound': '\nCompound statements\n*******************\n\nCompound statements contain (groups of) other statements; they affect\nor control the execution of those other statements in some way.  In\ngeneral, compound statements span multiple lines, although in simple\nincarnations a whole compound statement may be contained in one line.\n\nThe ``if``, ``while`` and ``for`` statements implement traditional\ncontrol flow constructs.  ``try`` specifies exception handlers and/or\ncleanup code for a group of statements, while the ``with`` statement\nallows the execution of initialization and finalization code around a\nblock of code.  Function and class definitions are also syntactically\ncompound statements.\n\nCompound statements consist of one or more \'clauses.\'  A clause\nconsists of a header and a \'suite.\'  The clause headers of a\nparticular compound statement are all at the same indentation level.\nEach clause header begins with a uniquely identifying keyword and ends\nwith a colon.  A suite is a group of statements controlled by a\nclause.  A suite can be one or more semicolon-separated simple\nstatements on the same line as the header, following the header\'s\ncolon, or it can be one or more indented statements on subsequent\nlines.  Only the latter form of suite can contain nested compound\nstatements; the following is illegal, mostly because it wouldn\'t be\nclear to which ``if`` clause a following ``else`` clause would belong:\n\n   if test1: if test2: print(x)\n\nAlso note that the semicolon binds tighter than the colon in this\ncontext, so that in the following example, either all or none of the\n``print()`` calls are executed:\n\n   if x < y < z: print(x); print(y); print(z)\n\nSummarizing:\n\n   compound_stmt ::= if_stmt\n                     | while_stmt\n                     | for_stmt\n                     | try_stmt\n                     | with_stmt\n                     | funcdef\n                     | classdef\n   suite         ::= stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT\n   statement     ::= stmt_list NEWLINE | compound_stmt\n   stmt_list     ::= simple_stmt (";" simple_stmt)* [";"]\n\nNote that statements always end in a ``NEWLINE`` possibly followed by\na ``DEDENT``.  Also note that optional continuation clauses always\nbegin with a keyword that cannot start a statement, thus there are no\nambiguities (the \'dangling ``else``\' problem is solved in Python by\nrequiring nested ``if`` statements to be indented).\n\nThe formatting of the grammar rules in the following sections places\neach clause on a separate line for clarity.\n\n\nThe ``if`` statement\n====================\n\nThe ``if`` statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n\n\nThe ``while`` statement\n=======================\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n   while_stmt ::= "while" expression ":" suite\n                  ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n\n\nThe ``for`` statement\n=====================\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n   for_stmt ::= "for" target_list "in" expression_list ":" suite\n                ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject.  An iterator is created for the result of the\n``expression_list``.  The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices.  Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted.  When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a ``StopIteration``\nexception), the suite in the ``else`` clause, if present, is executed,\nand the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, it will not have been assigned to at all\nby the loop.  Hint: the built-in function ``range()`` returns an\niterator of integers suitable to emulate the effect of Pascal\'s ``for\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\n2]``.\n\nNote: There is a subtlety when the sequence is being modified by the loop\n  (this can only occur for mutable sequences, i.e. lists).  An\n  internal counter is used to keep track of which item is used next,\n  and this is incremented on each iteration.  When this counter has\n  reached the length of the sequence the loop terminates.  This means\n  that if the suite deletes the current (or a previous) item from the\n  sequence, the next item will be skipped (since it gets the index of\n  the current item which has already been treated).  Likewise, if the\n  suite inserts an item in the sequence before the current item, the\n  current item will be treated again the next time through the loop.\n  This can lead to nasty bugs that can be avoided by making a\n  temporary copy using a slice of the whole sequence, e.g.,\n\n     for x in a[:]:\n         if x < 0: a.remove(x)\n\n\nThe ``try`` statement\n=====================\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" target]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started.  This search inspects the except\nclauses in turn until one is found that matches the exception.  An\nexpression-less except clause, if present, must be last; it matches\nany exception.  For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception.  An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause.  Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting of\nthe exception class, the exception instance and a traceback object\n(see section *The standard type hierarchy*) identifying the point in\nthe program where the exception occurred.  ``sys.exc_info()`` values\nare restored to their previous values (before the call) when returning\nfrom a function that handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler.  The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses.  If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted.  If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost.  The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n\n\nThe ``with`` statement\n======================\n\nThe ``with`` statement is used to wrap the execution of a block with\nmethods defined by a context manager (see section *With Statement\nContext Managers*). This allows common\n``try``...``except``...``finally`` usage patterns to be encapsulated\nfor convenient reuse.\n\n   with_stmt ::= "with" with_item ("," with_item)* ":" suite\n   with_item ::= expression ["as" target]\n\nThe execution of the ``with`` statement with one "item" proceeds as\nfollows:\n\n1. The context expression (the expression given in the ``with_item``)\n   is evaluated to obtain a context manager.\n\n2. The context manager\'s ``__exit__()`` is loaded for later use.\n\n3. The context manager\'s ``__enter__()`` method is invoked.\n\n4. If a target was included in the ``with`` statement, the return\n   value from ``__enter__()`` is assigned to it.\n\n   Note: The ``with`` statement guarantees that if the ``__enter__()``\n     method returns without an error, then ``__exit__()`` will always\n     be called. Thus, if an error occurs during the assignment to the\n     target list, it will be treated the same as an error occurring\n     within the suite would be. See step 6 below.\n\n5. The suite is executed.\n\n6. The context manager\'s ``__exit__()`` method is invoked.  If an\n   exception caused the suite to be exited, its type, value, and\n   traceback are passed as arguments to ``__exit__()``. Otherwise,\n   three ``None`` arguments are supplied.\n\n   If the suite was exited due to an exception, and the return value\n   from the ``__exit__()`` method was false, the exception is\n   reraised.  If the return value was true, the exception is\n   suppressed, and execution continues with the statement following\n   the ``with`` statement.\n\n   If the suite was exited for any reason other than an exception, the\n   return value from ``__exit__()`` is ignored, and execution proceeds\n   at the normal location for the kind of exit that was taken.\n\nWith more than one item, the context managers are processed as if\nmultiple ``with`` statements were nested:\n\n   with A() as a, B() as b:\n       suite\n\nis equivalent to\n\n   with A() as a:\n       with B() as b:\n           suite\n\nChanged in version 3.1: Support for multiple context expressions.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n\n\nFunction definitions\n====================\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" [parameter] ("," defparameter)*\n                      [, "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nWhen one or more parameters have the form *parameter* ``=``\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding argument may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the "``*``" must also have a default value ---\nthis is a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated when the function definition\nis executed.** This means that the expression is evaluated once, when\nthe function is defined, and that that same "pre-computed" value is\nused for each call.  This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended.  A way around this is to use ``None`` as the\ndefault, and explicitly test for it in the body of the function, e.g.:\n\n   def whats_on_the_telly(penguin=None):\n       if penguin is None:\n           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple.  If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after "``*``" or "``*identifier``" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "``: expression``"\nfollowing the parameter name.  Any parameter may have an annotation\neven those of the form ``*identifier`` or ``**identifier``.  Functions\nmay have "return" annotation of the form "``-> expression``" after the\nparameter list.  These annotations can be any valid Python expression\nand are evaluated when the function definition is executed.\nAnnotations may be evaluated in a different order than they appear in\nthe source code.  The presence of annotations does not change the\nsemantics of a function.  The annotation values are available as\nvalues of a dictionary keyed by the parameters\' names in the\n``__annotations__`` attribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda forms,\ndescribed in section *Lambdas*.  Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form.  The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A "``def``"\nform executed inside a function definition defines a local function\nthat can be returned or passed around.  Free variables used in the\nnested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n\n\nClass definitions\n=================\n\nA class definition defines a class object (see section *The standard\ntype hierarchy*):\n\n   classdef    ::= [decorators] "class" classname [inheritance] ":" suite\n   inheritance ::= "(" [argument_list [","] | comprehension] ")"\n   classname   ::= identifier\n\nA class definition is an executable statement.  The inheritance list\nusually gives a list of base classes (see *Customizing class creation*\nfor more advanced uses), so each item in the list should evaluate to a\nclass object which allows subclassing.  Classes without an inheritance\nlist inherit, by default, from the base class ``object``; hence,\n\n   class Foo:\n       pass\n\nis equivalent to\n\n   class Foo(object):\n       pass\n\nThe class\'s suite is then executed in a new execution frame (see\n*Naming and binding*), using a newly created local namespace and the\noriginal global namespace. (Usually, the suite contains mostly\nfunction definitions.)  When the class\'s suite finishes execution, its\nexecution frame is discarded but its local namespace is saved. [4] A\nclass object is then created using the inheritance list for the base\nclasses and the saved local namespace for the attribute dictionary.\nThe class name is bound to this class object in the original local\nnamespace.\n\nClass creation can be customized heavily using *metaclasses*.\n\nClasses can also be decorated: just like when decorating functions,\n\n   @f1(arg)\n   @f2\n   class Foo: pass\n\nis equivalent to\n\n   class Foo: pass\n   Foo = f1(arg)(f2(Foo))\n\nThe evaluation rules for the decorator expressions are the same as for\nfunction decorators.  The result must be a class object, which is then\nbound to the class name.\n\n**Programmer\'s note:** Variables defined in the class definition are\nclass attributes; they are shared by instances.  Instance attributes\ncan be set in a method with ``self.name = value``.  Both class and\ninstance attributes are accessible through the notation\n"``self.name``", and an instance attribute hides a class attribute\nwith the same name when accessed in this way.  Class attributes can be\nused as defaults for instance attributes, but using mutable values\nthere can lead to unexpected results.  *Descriptors* can be used to\ncreate instance variables with different implementation details.\n\nSee also:\n\n   **PEP 3116** - Metaclasses in Python 3 **PEP 3129** - Class\n   Decorators\n\n-[ Footnotes ]-\n\n[1] The exception is propagated to the invocation stack only if there\n    is no ``finally`` clause that negates the exception.\n\n[2] Currently, control "flows off the end" except in the case of an\n    exception or the execution of a ``return``, ``continue``, or\n    ``break`` statement.\n\n[3] A string literal appearing as the first statement in the function\n    body is transformed into the function\'s ``__doc__`` attribute and\n    therefore the function\'s *docstring*.\n\n[4] A string literal appearing as the first statement in the class\n    body is transformed into the namespace\'s ``__doc__`` item and\n    therefore the class\'s *docstring*.\n',
  'context-managers': '\nWith Statement Context Managers\n*******************************\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code.  Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n   Enter the runtime context related to this object. The ``with``\n   statement will bind this method\'s return value to the target(s)\n   specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n   Exit the runtime context related to this object. The parameters\n   describe the exception that caused the context to be exited. If the\n   context was exited without an exception, all three arguments will\n   be ``None``.\n\n   If an exception is supplied, and the method wishes to suppress the\n   exception (i.e., prevent it from being propagated), it should\n   return a true value. Otherwise, the exception will be processed\n   normally upon exit from this method.\n\n   Note that ``__exit__()`` methods should not reraise the passed-in\n   exception; this is the caller\'s responsibility.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n',
  'continue': '\nThe ``continue`` statement\n**************************\n\n   continue_stmt ::= "continue"\n\n``continue`` may only occur syntactically nested in a ``for`` or\n``while`` loop, but not nested in a function or class definition or\n``finally`` clause within that loop.  It continues with the next cycle\nof the nearest enclosing loop.\n\nWhen ``continue`` passes control out of a ``try`` statement with a\n``finally`` clause, that ``finally`` clause is executed before really\nstarting the next loop cycle.\n',
  'conversions': '\nArithmetic conversions\n**********************\n\nWhen a description of an arithmetic operator below uses the phrase\n"the numeric arguments are converted to a common type," this means\nthat the operator implementation for built-in types works that way:\n\n* If either argument is a complex number, the other is converted to\n  complex;\n\n* otherwise, if either argument is a floating point number, the other\n  is converted to floating point;\n\n* otherwise, both must be integers and no conversion is necessary.\n\nSome additional rules apply for certain operators (e.g., a string left\nargument to the \'%\' operator).  Extensions must define their own\nconversion behavior.\n',
  'customization': '\nBasic customization\n*******************\n\nobject.__new__(cls[, ...])\n\n   Called to create a new instance of class *cls*.  ``__new__()`` is a\n   static method (special-cased so you need not declare it as such)\n   that takes the class of which an instance was requested as its\n   first argument.  The remaining arguments are those passed to the\n   object constructor expression (the call to the class).  The return\n   value of ``__new__()`` should be the new object instance (usually\n   an instance of *cls*).\n\n   Typical implementations create a new instance of the class by\n   invoking the superclass\'s ``__new__()`` method using\n   ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n   arguments and then modifying the newly-created instance as\n   necessary before returning it.\n\n   If ``__new__()`` returns an instance of *cls*, then the new\n   instance\'s ``__init__()`` method will be invoked like\n   ``__init__(self[, ...])``, where *self* is the new instance and the\n   remaining arguments are the same as were passed to ``__new__()``.\n\n   If ``__new__()`` does not return an instance of *cls*, then the new\n   instance\'s ``__init__()`` method will not be invoked.\n\n   ``__new__()`` is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called when the instance is created.  The arguments are those\n   passed to the class constructor expression.  If a base class has an\n   ``__init__()`` method, the derived class\'s ``__init__()`` method,\n   if any, must explicitly call it to ensure proper initialization of\n   the base class part of the instance; for example:\n   ``BaseClass.__init__(self, [args...])``.  As a special constraint\n   on constructors, no value may be returned; doing so will cause a\n   ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n   Called when the instance is about to be destroyed.  This is also\n   called a destructor.  If a base class has a ``__del__()`` method,\n   the derived class\'s ``__del__()`` method, if any, must explicitly\n   call it to ensure proper deletion of the base class part of the\n   instance.  Note that it is possible (though not recommended!) for\n   the ``__del__()`` method to postpone destruction of the instance by\n   creating a new reference to it.  It may then be called at a later\n   time when this new reference is deleted.  It is not guaranteed that\n   ``__del__()`` methods are called for objects that still exist when\n   the interpreter exits.\n\n   Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n     decrements the reference count for ``x`` by one, and the latter\n     is only called when ``x``\'s reference count reaches zero.  Some\n     common situations that may prevent the reference count of an\n     object from going to zero include: circular references between\n     objects (e.g., a doubly-linked list or a tree data structure with\n     parent and child pointers); a reference to the object on the\n     stack frame of a function that caught an exception (the traceback\n     stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n     a reference to the object on the stack frame that raised an\n     unhandled exception in interactive mode (the traceback stored in\n     ``sys.last_traceback`` keeps the stack frame alive).  The first\n     situation can only be remedied by explicitly breaking the cycles;\n     the latter two situations can be resolved by storing ``None`` in\n     ``sys.last_traceback``. Circular references which are garbage are\n     detected when the option cycle detector is enabled (it\'s on by\n     default), but can only be cleaned up if there are no Python-\n     level ``__del__()`` methods involved. Refer to the documentation\n     for the ``gc`` module for more information about how\n     ``__del__()`` methods are handled by the cycle detector,\n     particularly the description of the ``garbage`` value.\n\n   Warning: Due to the precarious circumstances under which ``__del__()``\n     methods are invoked, exceptions that occur during their execution\n     are ignored, and a warning is printed to ``sys.stderr`` instead.\n     Also, when ``__del__()`` is invoked in response to a module being\n     deleted (e.g., when execution of the program is done), other\n     globals referenced by the ``__del__()`` method may already have\n     been deleted or in the process of being torn down (e.g. the\n     import machinery shutting down).  For this reason, ``__del__()``\n     methods should do the absolute minimum needed to maintain\n     external invariants.  Starting with version 1.5, Python\n     guarantees that globals whose name begins with a single\n     underscore are deleted from their module before other globals are\n     deleted; if no other references to such globals exist, this may\n     help in assuring that imported modules are still available at the\n     time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n   Called by the ``repr()`` built-in function to compute the\n   "official" string representation of an object.  If at all possible,\n   this should look like a valid Python expression that could be used\n   to recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   ``<...some useful description...>`` should be returned. The return\n   value must be a string object. If a class defines ``__repr__()``\n   but not ``__str__()``, then ``__repr__()`` is also used when an\n   "informal" string representation of instances of that class is\n   required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by the ``str()`` built-in function and by the ``print()``\n   function to compute the "informal" string representation of an\n   object.  This differs from ``__repr__()`` in that it does not have\n   to be a valid Python expression: a more convenient or concise\n   representation may be used instead. The return value must be a\n   string object.\n\nobject.__format__(self, format_spec)\n\n   Called by the ``format()`` built-in function (and by extension, the\n   ``format()`` method of class ``str``) to produce a "formatted"\n   string representation of an object. The ``format_spec`` argument is\n   a string that contains a description of the formatting options\n   desired. The interpretation of the ``format_spec`` argument is up\n   to the type implementing ``__format__()``, however most classes\n   will either delegate formatting to one of the built-in types, or\n   use a similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\n   ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\n   ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n   ``x.__ge__(y)``.\n\n   A rich comparison method may return the singleton\n   ``NotImplemented`` if it does not implement the operation for a\n   given pair of arguments. By convention, ``False`` and ``True`` are\n   returned for a successful comparison. However, these methods can\n   return any value, so if the comparison operator is used in a\n   Boolean context (e.g., in the condition of an ``if`` statement),\n   Python will call ``bool()`` on the value to determine if the result\n   is true or false.\n\n   There are no implied relationships among the comparison operators.\n   The truth of ``x==y`` does not imply that ``x!=y`` is false.\n   Accordingly, when defining ``__eq__()``, one should also define\n   ``__ne__()`` so that the operators will behave as expected.  See\n   the paragraph on ``__hash__()`` for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\n\n   There are no swapped-argument versions of these methods (to be used\n   when the left argument does not support the operation but the right\n   argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n   other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n   reflection, and ``__eq__()`` and ``__ne__()`` are their own\n   reflection.\n\n   Arguments to rich comparison methods are never coerced.\n\n   To automatically generate ordering operations from a single root\n   operation, see ``functools.total_ordering()``.\n\nobject.__hash__(self)\n\n   Called by built-in function ``hash()`` and for operations on\n   members of hashed collections including ``set``, ``frozenset``, and\n   ``dict``.  ``__hash__()`` should return an integer.  The only\n   required property is that objects which compare equal have the same\n   hash value; it is advised to somehow mix together (e.g. using\n   exclusive or) the hash values for the components of the object that\n   also play a part in comparison of objects.\n\n   If a class does not define an ``__eq__()`` method it should not\n   define a ``__hash__()`` operation either; if it defines\n   ``__eq__()`` but not ``__hash__()``, its instances will not be\n   usable as items in hashable collections.  If a class defines\n   mutable objects and implements an ``__eq__()`` method, it should\n   not implement ``__hash__()``, since the implementation of hashable\n   collections requires that a key\'s hash value is immutable (if the\n   object\'s hash value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n   by default; with them, all objects compare unequal (except with\n   themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n   Classes which inherit a ``__hash__()`` method from a parent class\n   but change the meaning of ``__eq__()`` such that the hash value\n   returned is no longer appropriate (e.g. by switching to a value-\n   based concept of equality instead of the default identity based\n   equality) can explicitly flag themselves as being unhashable by\n   setting ``__hash__ = None`` in the class definition. Doing so means\n   that not only will instances of the class raise an appropriate\n   ``TypeError`` when a program attempts to retrieve their hash value,\n   but they will also be correctly identified as unhashable when\n   checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n   which define their own ``__hash__()`` to explicitly raise\n   ``TypeError``).\n\n   If a class that overrides ``__eq__()`` needs to retain the\n   implementation of ``__hash__()`` from a parent class, the\n   interpreter must be told this explicitly by setting ``__hash__ =\n   <ParentClass>.__hash__``. Otherwise the inheritance of\n   ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n   explicitly set to ``None``.\n\nobject.__bool__(self)\n\n   Called to implement truth value testing and the built-in operation\n   ``bool()``; should return ``False`` or ``True``.  When this method\n   is not defined, ``__len__()`` is called, if it is defined, and the\n   object is considered true if its result is nonzero.  If a class\n   defines neither ``__len__()`` nor ``__bool__()``, all its instances\n   are considered true.\n',
- 'debugger': '\n``pdb`` --- The Python Debugger\n*******************************\n\nThe module ``pdb`` defines an interactive source code debugger for\nPython programs.  It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame.  It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible -- it is actually defined as the class\n``Pdb``. This is currently undocumented but easily understood by\nreading the source.  The extension interface uses the modules ``bdb``\nand ``cmd``.\n\nThe debugger\'s prompt is ``(Pdb)``. Typical usage to run a program\nunder control of the debugger is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> pdb.run(\'mymodule.test()\')\n   > <string>(0)?()\n   (Pdb) continue\n   > <string>(1)?()\n   (Pdb) continue\n   NameError: \'spam\'\n   > <string>(1)?()\n   (Pdb)\n\n``pdb.py`` can also be invoked as a script to debug other scripts.\nFor example:\n\n   python3 -m pdb myscript.py\n\nWhen invoked as a script, pdb will automatically enter post-mortem\ndebugging if the program being debugged exits abnormally.  After post-\nmortem debugging (or after normal exit of the program), pdb will\nrestart the program.  Automatic restarting preserves pdb\'s state (such\nas breakpoints) and in most cases is more useful than quitting the\ndebugger upon program\'s exit.\n\nNew in version 3.2: ``pdb.py`` now accepts a ``-c`` option that\nexecutes commands as if given in a ``.pdbrc`` file, see *Debugger\nCommands*.\n\nThe typical usage to break into the debugger from a running program is\nto insert\n\n   import pdb; pdb.set_trace()\n\nat the location you want to break into the debugger.  You can then\nstep through the code following this statement, and continue running\nwithout the debugger using the ``continue`` command.\n\nThe typical usage to inspect a crashed program is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> mymodule.test()\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n     File "./mymodule.py", line 4, in test\n       test2()\n     File "./mymodule.py", line 3, in test2\n       print(spam)\n   NameError: spam\n   >>> pdb.pm()\n   > ./mymodule.py(3)test2()\n   -> print(spam)\n   (Pdb)\n\nThe module defines the following functions; each enters the debugger\nin a slightly different way:\n\npdb.run(statement, globals=None, locals=None)\n\n   Execute the *statement* (given as a string or a code object) under\n   debugger control.  The debugger prompt appears before any code is\n   executed; you can set breakpoints and type ``continue``, or you can\n   step through the statement using ``step`` or ``next`` (all these\n   commands are explained below).  The optional *globals* and *locals*\n   arguments specify the environment in which the code is executed; by\n   default the dictionary of the module ``__main__`` is used.  (See\n   the explanation of the built-in ``exec()`` or ``eval()``\n   functions.)\n\npdb.runeval(expression, globals=None, locals=None)\n\n   Evaluate the *expression* (given as a string or a code object)\n   under debugger control.  When ``runeval()`` returns, it returns the\n   value of the expression.  Otherwise this function is similar to\n   ``run()``.\n\npdb.runcall(function, *args, **kwds)\n\n   Call the *function* (a function or method object, not a string)\n   with the given arguments.  When ``runcall()`` returns, it returns\n   whatever the function call returned.  The debugger prompt appears\n   as soon as the function is entered.\n\npdb.set_trace()\n\n   Enter the debugger at the calling stack frame.  This is useful to\n   hard-code a breakpoint at a given point in a program, even if the\n   code is not otherwise being debugged (e.g. when an assertion\n   fails).\n\npdb.post_mortem(traceback=None)\n\n   Enter post-mortem debugging of the given *traceback* object.  If no\n   *traceback* is given, it uses the one of the exception that is\n   currently being handled (an exception must be being handled if the\n   default is to be used).\n\npdb.pm()\n\n   Enter post-mortem debugging of the traceback found in\n   ``sys.last_traceback``.\n\nThe ``run_*`` functions and ``set_trace()`` are aliases for\ninstantiating the ``Pdb`` class and calling the method of the same\nname.  If you want to access further features, you have to do this\nyourself:\n\nclass class pdb.Pdb(completekey=\'tab\', stdin=None, stdout=None, skip=None)\n\n   ``Pdb`` is the debugger class.\n\n   The *completekey*, *stdin* and *stdout* arguments are passed to the\n   underlying ``cmd.Cmd`` class; see the description there.\n\n   The *skip* argument, if given, must be an iterable of glob-style\n   module name patterns.  The debugger will not step into frames that\n   originate in a module that matches one of these patterns. [1]\n\n   Example call to enable tracing with *skip*:\n\n      import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n   New in version 3.1: The *skip* argument.\n\n   run(statement, globals=None, locals=None)\n   runeval(expression, globals=None, locals=None)\n   runcall(function, *args, **kwds)\n   set_trace()\n\n      See the documentation for the functions explained above.\n',
+ 'debugger': '\n``pdb`` --- The Python Debugger\n*******************************\n\nThe module ``pdb`` defines an interactive source code debugger for\nPython programs.  It supports setting (conditional) breakpoints and\nsingle stepping at the source line level, inspection of stack frames,\nsource code listing, and evaluation of arbitrary Python code in the\ncontext of any stack frame.  It also supports post-mortem debugging\nand can be called under program control.\n\nThe debugger is extensible -- it is actually defined as the class\n``Pdb``. This is currently undocumented but easily understood by\nreading the source.  The extension interface uses the modules ``bdb``\nand ``cmd``.\n\nThe debugger\'s prompt is ``(Pdb)``. Typical usage to run a program\nunder control of the debugger is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> pdb.run(\'mymodule.test()\')\n   > <string>(0)?()\n   (Pdb) continue\n   > <string>(1)?()\n   (Pdb) continue\n   NameError: \'spam\'\n   > <string>(1)?()\n   (Pdb)\n\n``pdb.py`` can also be invoked as a script to debug other scripts.\nFor example:\n\n   python3 -m pdb myscript.py\n\nWhen invoked as a script, pdb will automatically enter post-mortem\ndebugging if the program being debugged exits abnormally.  After post-\nmortem debugging (or after normal exit of the program), pdb will\nrestart the program.  Automatic restarting preserves pdb\'s state (such\nas breakpoints) and in most cases is more useful than quitting the\ndebugger upon program\'s exit.\n\nNew in version 3.2: ``pdb.py`` now accepts a ``-c`` option that\nexecutes commands as if given in a ``.pdbrc`` file, see *Debugger\nCommands*.\n\nThe typical usage to break into the debugger from a running program is\nto insert\n\n   import pdb; pdb.set_trace()\n\nat the location you want to break into the debugger.  You can then\nstep through the code following this statement, and continue running\nwithout the debugger using the ``continue`` command.\n\nThe typical usage to inspect a crashed program is:\n\n   >>> import pdb\n   >>> import mymodule\n   >>> mymodule.test()\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in ?\n     File "./mymodule.py", line 4, in test\n       test2()\n     File "./mymodule.py", line 3, in test2\n       print(spam)\n   NameError: spam\n   >>> pdb.pm()\n   > ./mymodule.py(3)test2()\n   -> print(spam)\n   (Pdb)\n\nThe module defines the following functions; each enters the debugger\nin a slightly different way:\n\npdb.run(statement, globals=None, locals=None)\n\n   Execute the *statement* (given as a string or a code object) under\n   debugger control.  The debugger prompt appears before any code is\n   executed; you can set breakpoints and type ``continue``, or you can\n   step through the statement using ``step`` or ``next`` (all these\n   commands are explained below).  The optional *globals* and *locals*\n   arguments specify the environment in which the code is executed; by\n   default the dictionary of the module ``__main__`` is used.  (See\n   the explanation of the built-in ``exec()`` or ``eval()``\n   functions.)\n\npdb.runeval(expression, globals=None, locals=None)\n\n   Evaluate the *expression* (given as a string or a code object)\n   under debugger control.  When ``runeval()`` returns, it returns the\n   value of the expression.  Otherwise this function is similar to\n   ``run()``.\n\npdb.runcall(function, *args, **kwds)\n\n   Call the *function* (a function or method object, not a string)\n   with the given arguments.  When ``runcall()`` returns, it returns\n   whatever the function call returned.  The debugger prompt appears\n   as soon as the function is entered.\n\npdb.set_trace()\n\n   Enter the debugger at the calling stack frame.  This is useful to\n   hard-code a breakpoint at a given point in a program, even if the\n   code is not otherwise being debugged (e.g. when an assertion\n   fails).\n\npdb.post_mortem(traceback=None)\n\n   Enter post-mortem debugging of the given *traceback* object.  If no\n   *traceback* is given, it uses the one of the exception that is\n   currently being handled (an exception must be being handled if the\n   default is to be used).\n\npdb.pm()\n\n   Enter post-mortem debugging of the traceback found in\n   ``sys.last_traceback``.\n\nThe ``run*`` functions and ``set_trace()`` are aliases for\ninstantiating the ``Pdb`` class and calling the method of the same\nname.  If you want to access further features, you have to do this\nyourself:\n\nclass class pdb.Pdb(completekey=\'tab\', stdin=None, stdout=None, skip=None, nosigint=False)\n\n   ``Pdb`` is the debugger class.\n\n   The *completekey*, *stdin* and *stdout* arguments are passed to the\n   underlying ``cmd.Cmd`` class; see the description there.\n\n   The *skip* argument, if given, must be an iterable of glob-style\n   module name patterns.  The debugger will not step into frames that\n   originate in a module that matches one of these patterns. [1]\n\n   By default, Pdb sets a handler for the SIGINT signal (which is sent\n   when the user presses Ctrl-C on the console) when you give a\n   ``continue`` command. This allows you to break into the debugger\n   again by pressing Ctrl-C.  If you want Pdb not to touch the SIGINT\n   handler, set *nosigint* tot true.\n\n   Example call to enable tracing with *skip*:\n\n      import pdb; pdb.Pdb(skip=[\'django.*\']).set_trace()\n\n   New in version 3.1: The *skip* argument.\n\n   New in version 3.2: The *nosigint* argument.  Previously, a SIGINT\n   handler was never set by Pdb.\n\n   run(statement, globals=None, locals=None)\n   runeval(expression, globals=None, locals=None)\n   runcall(function, *args, **kwds)\n   set_trace()\n\n      See the documentation for the functions explained above.\n\n\nDebugger Commands\n=================\n\nThe commands recognized by the debugger are listed below.  Most\ncommands can be abbreviated to one or two letters as indicated; e.g.\n``h(elp)`` means that either ``h`` or ``help`` can be used to enter\nthe help command (but not ``he`` or ``hel``, nor ``H`` or ``Help`` or\n``HELP``).  Arguments to commands must be separated by whitespace\n(spaces or tabs).  Optional arguments are enclosed in square brackets\n(``[]``) in the command syntax; the square brackets must not be typed.\nAlternatives in the command syntax are separated by a vertical bar\n(``|``).\n\nEntering a blank line repeats the last command entered.  Exception: if\nthe last command was a ``list`` command, the next 11 lines are listed.\n\nCommands that the debugger doesn\'t recognize are assumed to be Python\nstatements and are executed in the context of the program being\ndebugged.  Python statements can also be prefixed with an exclamation\npoint (``!``).  This is a powerful way to inspect the program being\ndebugged; it is even possible to change a variable or call a function.\nWhen an exception occurs in such a statement, the exception name is\nprinted but the debugger\'s state is not changed.\n\nThe debugger supports *aliases*.  Aliases can have parameters which\nallows one a certain level of adaptability to the context under\nexamination.\n\nMultiple commands may be entered on a single line, separated by\n``;;``.  (A single ``;`` is not used as it is the separator for\nmultiple commands in a line that is passed to the Python parser.)  No\nintelligence is applied to separating the commands; the input is split\nat the first ``;;`` pair, even if it is in the middle of a quoted\nstring.\n\nIf a file ``.pdbrc`` exists in the user\'s home directory or in the\ncurrent directory, it is read in and executed as if it had been typed\nat the debugger prompt.  This is particularly useful for aliases.  If\nboth files exist, the one in the home directory is read first and\naliases defined there can be overridden by the local file.\n\nChanged in version 3.2: ``.pdbrc`` can now contain commands that\ncontinue debugging, such as ``continue`` or ``next``.  Previously,\nthese commands had no effect.\n\nh(elp) [command]\n\n   Without argument, print the list of available commands.  With a\n   *command* as argument, print help about that command.  ``help pdb``\n   displays the full documentation (the docstring of the ``pdb``\n   module).  Since the *command* argument must be an identifier,\n   ``help exec`` must be entered to get help on the ``!`` command.\n\nw(here)\n\n   Print a stack trace, with the most recent frame at the bottom.  An\n   arrow indicates the current frame, which determines the context of\n   most commands.\n\nd(own) [count]\n\n   Move the current frame *count* (default one) levels down in the\n   stack trace (to a newer frame).\n\nu(p) [count]\n\n   Move the current frame *count* (default one) levels up in the stack\n   trace (to an older frame).\n\nb(reak) [([filename:]lineno | function) [, condition]]\n\n   With a *lineno* argument, set a break there in the current file.\n   With a *function* argument, set a break at the first executable\n   statement within that function.  The line number may be prefixed\n   with a filename and a colon, to specify a breakpoint in another\n   file (probably one that hasn\'t been loaded yet).  The file is\n   searched on ``sys.path``.  Note that each breakpoint is assigned a\n   number to which all the other breakpoint commands refer.\n\n   If a second argument is present, it is an expression which must\n   evaluate to true before the breakpoint is honored.\n\n   Without argument, list all breaks, including for each breakpoint,\n   the number of times that breakpoint has been hit, the current\n   ignore count, and the associated condition if any.\n\ntbreak [([filename:]lineno | function) [, condition]]\n\n   Temporary breakpoint, which is removed automatically when it is\n   first hit. The arguments are the same as for ``break``.\n\ncl(ear) [filename:lineno | bpnumber [bpnumber ...]]\n\n   With a *filename:lineno* argument, clear all the breakpoints at\n   this line. With a space separated list of breakpoint numbers, clear\n   those breakpoints. Without argument, clear all breaks (but first\n   ask confirmation).\n\ndisable [bpnumber [bpnumber ...]]\n\n   Disable the breakpoints given as a space separated list of\n   breakpoint numbers.  Disabling a breakpoint means it cannot cause\n   the program to stop execution, but unlike clearing a breakpoint, it\n   remains in the list of breakpoints and can be (re-)enabled.\n\nenable [bpnumber [bpnumber ...]]\n\n   Enable the breakpoints specified.\n\nignore bpnumber [count]\n\n   Set the ignore count for the given breakpoint number.  If count is\n   omitted, the ignore count is set to 0.  A breakpoint becomes active\n   when the ignore count is zero.  When non-zero, the count is\n   decremented each time the breakpoint is reached and the breakpoint\n   is not disabled and any associated condition evaluates to true.\n\ncondition bpnumber [condition]\n\n   Set a new *condition* for the breakpoint, an expression which must\n   evaluate to true before the breakpoint is honored.  If *condition*\n   is absent, any existing condition is removed; i.e., the breakpoint\n   is made unconditional.\n\ncommands [bpnumber]\n\n   Specify a list of commands for breakpoint number *bpnumber*.  The\n   commands themselves appear on the following lines.  Type a line\n   containing just ``end`` to terminate the commands. An example:\n\n      (Pdb) commands 1\n      (com) print some_variable\n      (com) end\n      (Pdb)\n\n   To remove all commands from a breakpoint, type commands and follow\n   it immediately with ``end``; that is, give no commands.\n\n   With no *bpnumber* argument, commands refers to the last breakpoint\n   set.\n\n   You can use breakpoint commands to start your program up again.\n   Simply use the continue command, or step, or any other command that\n   resumes execution.\n\n   Specifying any command resuming execution (currently continue,\n   step, next, return, jump, quit and their abbreviations) terminates\n   the command list (as if that command was immediately followed by\n   end). This is because any time you resume execution (even with a\n   simple next or step), you may encounter another breakpoint--which\n   could have its own command list, leading to ambiguities about which\n   list to execute.\n\n   If you use the \'silent\' command in the command list, the usual\n   message about stopping at a breakpoint is not printed.  This may be\n   desirable for breakpoints that are to print a specific message and\n   then continue.  If none of the other commands print anything, you\n   see no sign that the breakpoint was reached.\n\ns(tep)\n\n   Execute the current line, stop at the first possible occasion\n   (either in a function that is called or on the next line in the\n   current function).\n\nn(ext)\n\n   Continue execution until the next line in the current function is\n   reached or it returns.  (The difference between ``next`` and\n   ``step`` is that ``step`` stops inside a called function, while\n   ``next`` executes called functions at (nearly) full speed, only\n   stopping at the next line in the current function.)\n\nunt(il) [lineno]\n\n   Without argument, continue execution until the line with a number\n   greater than the current one is reached.\n\n   With a line number, continue execution until a line with a number\n   greater or equal to that is reached.  In both cases, also stop when\n   the current frame returns.\n\n   Changed in version 3.2: Allow giving an explicit line number.\n\nr(eturn)\n\n   Continue execution until the current function returns.\n\nc(ont(inue))\n\n   Continue execution, only stop when a breakpoint is encountered.\n\nj(ump) lineno\n\n   Set the next line that will be executed.  Only available in the\n   bottom-most frame.  This lets you jump back and execute code again,\n   or jump forward to skip code that you don\'t want to run.\n\n   It should be noted that not all jumps are allowed -- for instance\n   it is not possible to jump into the middle of a ``for`` loop or out\n   of a ``finally`` clause.\n\nl(ist) [first[, last]]\n\n   List source code for the current file.  Without arguments, list 11\n   lines around the current line or continue the previous listing.\n   With ``.`` as argument, list 11 lines around the current line.\n   With one argument, list 11 lines around at that line.  With two\n   arguments, list the given range; if the second argument is less\n   than the first, it is interpreted as a count.\n\n   The current line in the current frame is indicated by ``->``.  If\n   an exception is being debugged, the line where the exception was\n   originally raised or propagated is indicated by ``>>``, if it\n   differs from the current line.\n\n   New in version 3.2: The ``>>`` marker.\n\nll | longlist\n\n   List all source code for the current function or frame.\n   Interesting lines are marked as for ``list``.\n\n   New in version 3.2.\n\na(rgs)\n\n   Print the argument list of the current function.\n\np(rint) expression\n\n   Evaluate the *expression* in the current context and print its\n   value.\n\npp expression\n\n   Like the ``print`` command, except the value of the expression is\n   pretty-printed using the ``pprint`` module.\n\nwhatis expression\n\n   Print the type of the *expression*.\n\nsource expression\n\n   Try to get source code for the given object and display it.\n\n   New in version 3.2.\n\ndisplay [expression]\n\n   Display the value of the expression if it changed, each time\n   execution stops in the current frame.\n\n   Without expression, list all display expressions for the current\n   frame.\n\n   New in version 3.2.\n\nundisplay [expression]\n\n   Do not display the expression any more in the current frame.\n   Without expression, clear all display expressions for the current\n   frame.\n\n   New in version 3.2.\n\ninteract\n\n   Start an interative interpreter (using the ``code`` module) whose\n   global namespace contains all the (global and local) names found in\n   the current scope.\n\n   New in version 3.2.\n\nalias [name [command]]\n\n   Create an alias called *name* that executes *command*.  The command\n   must *not* be enclosed in quotes.  Replaceable parameters can be\n   indicated by ``%1``, ``%2``, and so on, while ``%*`` is replaced by\n   all the parameters. If no command is given, the current alias for\n   *name* is shown. If no arguments are given, all aliases are listed.\n\n   Aliases may be nested and can contain anything that can be legally\n   typed at the pdb prompt.  Note that internal pdb commands *can* be\n   overridden by aliases.  Such a command is then hidden until the\n   alias is removed.  Aliasing is recursively applied to the first\n   word of the command line; all other words in the line are left\n   alone.\n\n   As an example, here are two useful aliases (especially when placed\n   in the ``.pdbrc`` file):\n\n      # Print instance variables (usage "pi classInst")\n      alias pi for k in %1.__dict__.keys(): print("%1.",k,"=",%1.__dict__[k])\n      # Print instance variables in self\n      alias ps pi self\n\nunalias name\n\n   Delete the specified alias.\n\n! statement\n\n   Execute the (one-line) *statement* in the context of the current\n   stack frame. The exclamation point can be omitted unless the first\n   word of the statement resembles a debugger command.  To set a\n   global variable, you can prefix the assignment command with a\n   ``global`` statement on the same line, e.g.:\n\n      (Pdb) global list_options; list_options = [\'-l\']\n      (Pdb)\n\nrun [args ...]\nrestart [args ...]\n\n   Restart the debugged Python program.  If an argument is supplied,\n   it is split with ``shlex`` and the result is used as the new\n   ``sys.argv``. History, breakpoints, actions and debugger options\n   are preserved. ``restart`` is an alias for ``run``.\n\nq(uit)\n\n   Quit from the debugger.  The program being executed is aborted.\n\n-[ Footnotes ]-\n\n[1] Whether a frame is considered to originate in a certain module is\n    determined by the ``__name__`` in the frame globals.\n',
  'del': '\nThe ``del`` statement\n*********************\n\n   del_stmt ::= "del" target_list\n\nDeletion is recursively defined very similar to the way assignment is\ndefined. Rather that spelling it out in full details, here are some\nhints.\n\nDeletion of a target list recursively deletes each target, from left\nto right.\n\nDeletion of a name removes the binding of that name from the local or\nglobal namespace, depending on whether the name occurs in a ``global``\nstatement in the same code block.  If the name is unbound, a\n``NameError`` exception will be raised.\n\nDeletion of attribute references, subscriptions and slicings is passed\nto the primary object involved; deletion of a slicing is in general\nequivalent to assignment of an empty slice of the right type (but even\nthis is determined by the sliced object).\n\nChanged in version 3.2.\n',
  'dict': '\nDictionary displays\n*******************\n\nA dictionary display is a possibly empty series of key/datum pairs\nenclosed in curly braces:\n\n   dict_display       ::= "{" [key_datum_list | dict_comprehension] "}"\n   key_datum_list     ::= key_datum ("," key_datum)* [","]\n   key_datum          ::= expression ":" expression\n   dict_comprehension ::= expression ":" expression comp_for\n\nA dictionary display yields a new dictionary object.\n\nIf a comma-separated sequence of key/datum pairs is given, they are\nevaluated from left to right to define the entries of the dictionary:\neach key object is used as a key into the dictionary to store the\ncorresponding datum.  This means that you can specify the same key\nmultiple times in the key/datum list, and the final dictionary\'s value\nfor that key will be the last one given.\n\nA dict comprehension, in contrast to list and set comprehensions,\nneeds two expressions separated with a colon followed by the usual\n"for" and "if" clauses. When the comprehension is run, the resulting\nkey and value elements are inserted in the new dictionary in the order\nthey are produced.\n\nRestrictions on the types of the key values are listed earlier in\nsection *The standard type hierarchy*.  (To summarize, the key type\nshould be *hashable*, which excludes all mutable objects.)  Clashes\nbetween duplicate keys are not detected; the last datum (textually\nrightmost in the display) stored for a given key value prevails.\n',
  'dynamic-features': '\nInteraction with dynamic features\n*********************************\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n',
  'else': '\nThe ``if`` statement\n********************\n\nThe ``if`` statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n',
  'exceptions': '\nExceptions\n**********\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions.  An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero).  A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement.  The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop.  In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances.  The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof.  The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nNote: Exception messages are not part of the Python API.  Their contents\n  may change from one version of Python to the next without warning\n  and should not be relied on by code which will run under multiple\n  versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n    operations is not available at the time the module is compiled.\n',
- 'execmodel': '\nExecution model\n***************\n\n\nNaming and binding\n==================\n\n*Names* refer to objects.  Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block.  A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the \'**-c**\' option) is a code block.  The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*.  A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block\'s execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block.  If a local\nvariable is defined in a block, its scope includes that block.  If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name.  The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope.  This\nmeans that the following will fail:\n\n   class A:\n       a = 42\n       b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope.  The set of all such scopes visible to a code block\nis called the block\'s *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``.  If a name is bound at the module\nlevel, it is a global variable.  (The variables of the module code\nblock are local and global.)  If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised.  ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or ``except`` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore.  This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).  It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block.  This can lead to errors when a name is used within a\nblock before it is bound.  This rule is subtle.  Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block.  The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace.  Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtins namespace, the\nnamespace of the module ``builtins``.  The global namespace is\nsearched first.  If the name is not found there, the builtins\nnamespace is searched.  The global statement must precede all uses of\nthe name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module\'s dictionary is used).  By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail.  Users\nwanting to override values in the builtins namespace should ``import``\nthe ``builtins`` module and modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported.  The main module for a script is always called\n``__main__``.\n\nThe global statement has the same scope as a name binding operation in\nthe same block.  If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class.  Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n---------------------------------\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n\n\nExceptions\n==========\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions.  An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero).  A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement.  The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop.  In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances.  The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof.  The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nNote: Exception messages are not part of the Python API.  Their contents\n  may change from one version of Python to the next without warning\n  and should not be relied on by code which will run under multiple\n  versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n    operations is not available at the time the module is compiled.\n',
+ 'execmodel': '\nExecution model\n***************\n\n\nNaming and binding\n==================\n\n*Names* refer to objects.  Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block.  A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the \'**-c**\' option) is a code block.  The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*.  A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block\'s execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block.  If a local\nvariable is defined in a block, its scope includes that block.  If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name.  The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope.  This\nmeans that the following will fail:\n\n   class A:\n       a = 42\n       b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope.  The set of all such scopes visible to a code block\nis called the block\'s *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``.  If a name is bound at the module\nlevel, it is a global variable.  (The variables of the module code\nblock are local and global.)  If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised.  ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or ``except`` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore.  This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).  It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block.  This can lead to errors when a name is used within a\nblock before it is bound.  This rule is subtle.  Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block.  The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace.  Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtins namespace, the\nnamespace of the module ``builtins``.  The global namespace is\nsearched first.  If the name is not found there, the builtins\nnamespace is searched.  The global statement must precede all uses of\nthe name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module\'s dictionary is used).  By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail.  Users\nwanting to override values in the builtins namespace should ``import``\nthe ``builtins`` module and modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported.  The main module for a script is always called\n``__main__``.\n\nThe ``global`` statement has the same scope as a name binding\noperation in the same block.  If the nearest enclosing scope for a\nfree variable contains a global statement, the free variable is\ntreated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class.  Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n---------------------------------\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n\n\nExceptions\n==========\n\nExceptions are a means of breaking out of the normal flow of control\nof a code block in order to handle errors or other exceptional\nconditions.  An exception is *raised* at the point where the error is\ndetected; it may be *handled* by the surrounding code block or by any\ncode block that directly or indirectly invoked the code block where\nthe error occurred.\n\nThe Python interpreter raises an exception when it detects a run-time\nerror (such as division by zero).  A Python program can also\nexplicitly raise an exception with the ``raise`` statement. Exception\nhandlers are specified with the ``try`` ... ``except`` statement.  The\n``finally`` clause of such a statement can be used to specify cleanup\ncode which does not handle the exception, but is executed whether an\nexception occurred or not in the preceding code.\n\nPython uses the "termination" model of error handling: an exception\nhandler can find out what happened and continue execution at an outer\nlevel, but it cannot repair the cause of the error and retry the\nfailing operation (except by re-entering the offending piece of code\nfrom the top).\n\nWhen an exception is not handled at all, the interpreter terminates\nexecution of the program, or returns to its interactive main loop.  In\neither case, it prints a stack backtrace, except when the exception is\n``SystemExit``.\n\nExceptions are identified by class instances.  The ``except`` clause\nis selected depending on the class of the instance: it must reference\nthe class of the instance or a base class thereof.  The instance can\nbe received by the handler and can carry additional information about\nthe exceptional condition.\n\nNote: Exception messages are not part of the Python API.  Their contents\n  may change from one version of Python to the next without warning\n  and should not be relied on by code which will run under multiple\n  versions of the interpreter.\n\nSee also the description of the ``try`` statement in section *The try\nstatement* and ``raise`` statement in section *The raise statement*.\n\n-[ Footnotes ]-\n\n[1] This limitation occurs because the code that is executed by these\n    operations is not available at the time the module is compiled.\n',
  'exprlists': '\nExpression lists\n****************\n\n   expression_list ::= expression ( "," expression )* [","]\n\nAn expression list containing at least one comma yields a tuple.  The\nlength of the tuple is the number of expressions in the list.  The\nexpressions are evaluated from left to right.\n\nThe trailing comma is required only to create a single tuple (a.k.a. a\n*singleton*); it is optional in all other cases.  A single expression\nwithout a trailing comma doesn\'t create a tuple, but rather yields the\nvalue of that expression. (To create an empty tuple, use an empty pair\nof parentheses: ``()``.)\n',
  'floating': '\nFloating point literals\n***********************\n\nFloating point literals are described by the following lexical\ndefinitions:\n\n   floatnumber   ::= pointfloat | exponentfloat\n   pointfloat    ::= [intpart] fraction | intpart "."\n   exponentfloat ::= (intpart | pointfloat) exponent\n   intpart       ::= digit+\n   fraction      ::= "." digit+\n   exponent      ::= ("e" | "E") ["+" | "-"] digit+\n\nNote that the integer and exponent parts are always interpreted using\nradix 10. For example, ``077e010`` is legal, and denotes the same\nnumber as ``77e10``. The allowed range of floating point literals is\nimplementation-dependent. Some examples of floating point literals:\n\n   3.14    10.    .001    1e100    3.14e-10    0e0\n\nNote that numeric literals do not include a sign; a phrase like ``-1``\nis actually an expression composed of the unary operator ``-`` and the\nliteral ``1``.\n',
  'for': '\nThe ``for`` statement\n*********************\n\nThe ``for`` statement is used to iterate over the elements of a\nsequence (such as a string, tuple or list) or other iterable object:\n\n   for_stmt ::= "for" target_list "in" expression_list ":" suite\n                ["else" ":" suite]\n\nThe expression list is evaluated once; it should yield an iterable\nobject.  An iterator is created for the result of the\n``expression_list``.  The suite is then executed once for each item\nprovided by the iterator, in the order of ascending indices.  Each\nitem in turn is assigned to the target list using the standard rules\nfor assignments (see *Assignment statements*), and then the suite is\nexecuted.  When the items are exhausted (which is immediately when the\nsequence is empty or an iterator raises a ``StopIteration``\nexception), the suite in the ``else`` clause, if present, is executed,\nand the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ncontinues with the next item, or with the ``else`` clause if there was\nno next item.\n\nThe suite may assign to the variable(s) in the target list; this does\nnot affect the next item assigned to it.\n\nNames in the target list are not deleted when the loop is finished,\nbut if the sequence is empty, it will not have been assigned to at all\nby the loop.  Hint: the built-in function ``range()`` returns an\niterator of integers suitable to emulate the effect of Pascal\'s ``for\ni := a to b do``; e.g., ``list(range(3))`` returns the list ``[0, 1,\n2]``.\n\nNote: There is a subtlety when the sequence is being modified by the loop\n  (this can only occur for mutable sequences, i.e. lists).  An\n  internal counter is used to keep track of which item is used next,\n  and this is incremented on each iteration.  When this counter has\n  reached the length of the sequence the loop terminates.  This means\n  that if the suite deletes the current (or a previous) item from the\n  sequence, the next item will be skipped (since it gets the index of\n  the current item which has already been treated).  Likewise, if the\n  suite inserts an item in the sequence before the current item, the\n  current item will be treated again the next time through the loop.\n  This can lead to nasty bugs that can be avoided by making a\n  temporary copy using a slice of the whole sequence, e.g.,\n\n     for x in a[:]:\n         if x < 0: a.remove(x)\n',
- 'formatstrings': '\nFormat String Syntax\n********************\n\nThe ``str.format()`` method and the ``Formatter`` class share the same\nsyntax for format strings (although in the case of ``Formatter``,\nsubclasses can define their own format string syntax).\n\nFormat strings contain "replacement fields" surrounded by curly braces\n``{}``. Anything that is not contained in braces is considered literal\ntext, which is copied unchanged to the output.  If you need to include\na brace character in the literal text, it can be escaped by doubling:\n``{{`` and ``}}``.\n\nThe grammar for a replacement field is as follows:\n\n      replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"\n      field_name        ::= arg_name ("." attribute_name | "[" element_index "]")*\n      arg_name          ::= [identifier | integer]\n      attribute_name    ::= identifier\n      element_index     ::= integer | index_string\n      index_string      ::= <any source character except "]"> +\n      conversion        ::= "r" | "s" | "a"\n      format_spec       ::= <described in the next section>\n\nIn less formal terms, the replacement field can start with a\n*field_name* that specifies the object whose value is to be formatted\nand inserted into the output instead of the replacement field. The\n*field_name* is optionally followed by a  *conversion* field, which is\npreceded by an exclamation point ``\'!\'``, and a *format_spec*, which\nis preceded by a colon ``\':\'``.  These specify a non-default format\nfor the replacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either\neither a number or a keyword.  If it\'s a number, it refers to a\npositional argument, and if it\'s a keyword, it refers to a named\nkeyword argument.  If the numerical arg_names in a format string are\n0, 1, 2, ... in sequence, they can all be omitted (not just some) and\nthe numbers 0, 1, 2, ... will be automatically inserted in that order.\nThe *arg_name* can be followed by any number of index or attribute\nexpressions. An expression of the form ``\'.name\'`` selects the named\nattribute using ``getattr()``, while an expression of the form\n``\'[index]\'`` does an index lookup using ``__getitem__()``.\n\nChanged in version 3.1: The positional argument specifiers can be\nomitted, so ``\'{} {}\'`` is equivalent to ``\'{0} {1}\'``.\n\nSome simple format string examples:\n\n   "First, thou shalt count to {0}" # References first positional argument\n   "Bring me a {}"                  # Implicitly references the first positional argument\n   "From {} to {}"                  # Same as "From {0} to {1}"\n   "My quest is {name}"             # References keyword argument \'name\'\n   "Weight in tons {0.weight}"      # \'weight\' attribute of first positional arg\n   "Units destroyed: {players[0]}"  # First element of keyword argument \'players\'.\n\nThe *conversion* field causes a type coercion before formatting.\nNormally, the job of formatting a value is done by the\n``__format__()`` method of the value itself.  However, in some cases\nit is desirable to force a type to be formatted as a string,\noverriding its own definition of formatting.  By converting the value\nto a string before calling ``__format__()``, the normal formatting\nlogic is bypassed.\n\nThree conversion flags are currently supported: ``\'!s\'`` which calls\n``str()`` on the value, ``\'!r\'`` which calls ``repr()`` and ``\'!a\'``\nwhich calls ``ascii()``.\n\nSome examples:\n\n   "Harold\'s a clever {0!s}"        # Calls str() on the argument first\n   "Bring out the holy {name!r}"    # Calls repr() on the argument first\n   "More {!a}"                      # Calls ascii() on the argument first\n\nThe *format_spec* field contains a specification of how the value\nshould be presented, including such details as field width, alignment,\npadding, decimal precision and so on.  Each value type can define its\nown "formatting mini-language" or interpretation of the *format_spec*.\n\nMost built-in types support a common formatting mini-language, which\nis described in the next section.\n\nA *format_spec* field can also include nested replacement fields\nwithin it. These nested replacement fields can contain only a field\nname; conversion flags and format specifications are not allowed.  The\nreplacement fields within the format_spec are substituted before the\n*format_spec* string is interpreted. This allows the formatting of a\nvalue to be dynamically specified.\n\nSee the *Format examples* section for some examples.\n\n\nFormat Specification Mini-Language\n==================================\n\n"Format specifications" are used within replacement fields contained\nwithin a format string to define how individual values are presented\n(see *Format String Syntax*).  They can also be passed directly to the\nbuilt-in ``format()`` function.  Each formattable type may define how\nthe format specification is to be interpreted.\n\nMost built-in types implement the following options for format\nspecifications, although some of the formatting options are only\nsupported by the numeric types.\n\nA general convention is that an empty format string (``""``) produces\nthe same result as if you had called ``str()`` on the value. A non-\nempty format string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n   format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n   fill        ::= <a character other than \'}\'>\n   align       ::= "<" | ">" | "=" | "^"\n   sign        ::= "+" | "-" | " "\n   width       ::= integer\n   precision   ::= integer\n   type        ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n\nThe *fill* character can be any character other than \'{\' or \'}\'.  The\npresence of a fill character is signaled by the character following\nit, which must be one of the alignment options.  If the second\ncharacter of *format_spec* is not a valid alignment option, then it is\nassumed that both the fill character and the alignment option are\nabsent.\n\nThe meaning of the various alignment options is as follows:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'<\'``   | Forces the field to be left-aligned within the available   |\n   |           | space (this is the default).                               |\n   +-----------+------------------------------------------------------------+\n   | ``\'>\'``   | Forces the field to be right-aligned within the available  |\n   |           | space.                                                     |\n   +-----------+------------------------------------------------------------+\n   | ``\'=\'``   | Forces the padding to be placed after the sign (if any)    |\n   |           | but before the digits.  This is used for printing fields   |\n   |           | in the form \'+000000120\'. This alignment option is only    |\n   |           | valid for numeric types.                                   |\n   +-----------+------------------------------------------------------------+\n   | ``\'^\'``   | Forces the field to be centered within the available       |\n   |           | space.                                                     |\n   +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'+\'``   | indicates that a sign should be used for both positive as  |\n   |           | well as negative numbers.                                  |\n   +-----------+------------------------------------------------------------+\n   | ``\'-\'``   | indicates that a sign should be used only for negative     |\n   |           | numbers (this is the default behavior).                    |\n   +-----------+------------------------------------------------------------+\n   | space     | indicates that a leading space should be used on positive  |\n   |           | numbers, and a minus sign on negative numbers.             |\n   +-----------+------------------------------------------------------------+\n\nThe ``\'#\'`` option is only valid for integers, and only for binary,\noctal, or hexadecimal output.  If present, it specifies that the\noutput will be prefixed by ``\'0b\'``, ``\'0o\'``, or ``\'0x\'``,\nrespectively.\n\nThe ``\',\'`` option signals the use of a comma for a thousands\nseparator. For a locale aware separator, use the ``\'n\'`` integer\npresentation type instead.\n\nChanged in version 3.1: Added the ``\',\'`` option (see also **PEP\n378**).\n\n*width* is a decimal integer defining the minimum field width.  If not\nspecified, then the field width will be determined by the content.\n\nIf the *width* field is preceded by a zero (``\'0\'``) character, this\nenables zero-padding.  This is equivalent to an *alignment* type of\n``\'=\'`` and a *fill* character of ``\'0\'``.\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with ``\'f\'`` and ``\'F\'``, or before and after the decimal\npoint for a floating point value formatted with ``\'g\'`` or ``\'G\'``.\nFor non-number types the field indicates the maximum field size - in\nother words, how many characters will be used from the field content.\nThe *precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'s\'``   | String format. This is the default type for strings and    |\n   |           | may be omitted.                                            |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as ``\'s\'``.                                       |\n   +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'b\'``   | Binary format. Outputs the number in base 2.               |\n   +-----------+------------------------------------------------------------+\n   | ``\'c\'``   | Character. Converts the integer to the corresponding       |\n   |           | unicode character before printing.                         |\n   +-----------+------------------------------------------------------------+\n   | ``\'d\'``   | Decimal Integer. Outputs the number in base 10.            |\n   +-----------+------------------------------------------------------------+\n   | ``\'o\'``   | Octal format. Outputs the number in base 8.                |\n   +-----------+------------------------------------------------------------+\n   | ``\'x\'``   | Hex format. Outputs the number in base 16, using lower-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'X\'``   | Hex format. Outputs the number in base 16, using upper-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'n\'``   | Number. This is the same as ``\'d\'``, except that it uses   |\n   |           | the current locale setting to insert the appropriate       |\n   |           | number separator characters.                               |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as ``\'d\'``.                                       |\n   +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except\n``\'n\'`` and None). When doing so, ``float()`` is used to convert the\ninteger to a floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'e\'``   | Exponent notation. Prints the number in scientific         |\n   |           | notation using the letter \'e\' to indicate the exponent.    |\n   +-----------+------------------------------------------------------------+\n   | ``\'E\'``   | Exponent notation. Same as ``\'e\'`` except it uses an upper |\n   |           | case \'E\' as the separator character.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'f\'``   | Fixed point. Displays the number as a fixed-point number.  |\n   +-----------+------------------------------------------------------------+\n   | ``\'F\'``   | Fixed point. Same as ``\'f\'``, but converts ``nan`` to      |\n   |           | ``NAN`` and ``inf`` to ``INF``.                            |\n   +-----------+------------------------------------------------------------+\n   | ``\'g\'``   | General format.  For a given precision ``p >= 1``, this    |\n   |           | rounds the number to ``p`` significant digits and then     |\n   |           | formats the result in either fixed-point format or in      |\n   |           | scientific notation, depending on its magnitude.  The      |\n   |           | precise rules are as follows: suppose that the result      |\n   |           | formatted with presentation type ``\'e\'`` and precision     |\n   |           | ``p-1`` would have exponent ``exp``.  Then if ``-4 <= exp  |\n   |           | < p``, the number is formatted with presentation type      |\n   |           | ``\'f\'`` and precision ``p-1-exp``. Otherwise, the number   |\n   |           | is formatted with presentation type ``\'e\'`` and precision  |\n   |           | ``p-1``. In both cases insignificant trailing zeros are    |\n   |           | removed from the significand, and the decimal point is     |\n   |           | also removed if there are no remaining digits following    |\n   |           | it.  Postive and negative infinity, positive and negative  |\n   |           | zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\n   |           | ``-0`` and ``nan`` respectively, regardless of the         |\n   |           | precision.  A precision of ``0`` is treated as equivalent  |\n   |           | to a precision of ``1``.                                   |\n   +-----------+------------------------------------------------------------+\n   | ``\'G\'``   | General format. Same as ``\'g\'`` except switches to ``\'E\'`` |\n   |           | if the number gets too large. The representations of       |\n   |           | infinity and NaN are uppercased, too.                      |\n   +-----------+------------------------------------------------------------+\n   | ``\'n\'``   | Number. This is the same as ``\'g\'``, except that it uses   |\n   |           | the current locale setting to insert the appropriate       |\n   |           | number separator characters.                               |\n   +-----------+------------------------------------------------------------+\n   | ``\'%\'``   | Percentage. Multiplies the number by 100 and displays in   |\n   |           | fixed (``\'f\'``) format, followed by a percent sign.        |\n   +-----------+------------------------------------------------------------+\n   | None      | Similar to ``\'g\'``, except with at least one digit past    |\n   |           | the decimal point and a default precision of 12. This is   |\n   |           | intended to match ``str()``, except you can add the other  |\n   |           | format modifiers.                                          |\n   +-----------+------------------------------------------------------------+\n\n\nFormat examples\n===============\n\nThis section contains examples of the new format syntax and comparison\nwith the old ``%``-formatting.\n\nIn most of the cases the syntax is similar to the old\n``%``-formatting, with the addition of the ``{}`` and with ``:`` used\ninstead of ``%``. For example, ``\'%03.2f\'`` can be translated to\n``\'{:03.2f}\'``.\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n   >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n   \'a, b, c\'\n   >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\')  # 3.1+ only\n   \'a, b, c\'\n   >>> \'{2}, {1}, {0}\'.format(\'a\', \'b\', \'c\')\n   \'c, b, a\'\n   >>> \'{2}, {1}, {0}\'.format(*\'abc\')      # unpacking argument sequence\n   \'c, b, a\'\n   >>> \'{0}{1}{0}\'.format(\'abra\', \'cad\')   # arguments\' indices can be repeated\n   \'abracadabra\'\n\nAccessing arguments by name:\n\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(latitude=\'37.24N\', longitude=\'-115.81W\')\n   \'Coordinates: 37.24N, -115.81W\'\n   >>> coord = {\'latitude\': \'37.24N\', \'longitude\': \'-115.81W\'}\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(**coord)\n   \'Coordinates: 37.24N, -115.81W\'\n\nAccessing arguments\' attributes:\n\n   >>> c = 3-5j\n   >>> (\'The complex number {0} is formed from the real part {0.real} \'\n   ...  \'and the imaginary part {0.imag}.\').format(c)\n   \'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.\'\n   >>> class Point:\n   ...     def __init__(self, x, y):\n   ...         self.x, self.y = x, y\n   ...     def __str__(self):\n   ...         return \'Point({self.x}, {self.y})\'.format(self=self)\n   ...\n   >>> str(Point(4, 2))\n   \'Point(4, 2)\'\n\nAccessing arguments\' items:\n\n   >>> coord = (3, 5)\n   >>> \'X: {0[0]};  Y: {0[1]}\'.format(coord)\n   \'X: 3;  Y: 5\'\n\nReplacing ``%s`` and ``%r``:\n\n   >>> "repr() shows quotes: {!r}; str() doesn\'t: {!s}".format(\'test1\', \'test2\')\n   "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n\nAligning the text and specifying a width:\n\n   >>> \'{:<30}\'.format(\'left aligned\')\n   \'left aligned                  \'\n   >>> \'{:>30}\'.format(\'right aligned\')\n   \'                 right aligned\'\n   >>> \'{:^30}\'.format(\'centered\')\n   \'           centered           \'\n   >>> \'{:*^30}\'.format(\'centered\')  # use \'*\' as a fill char\n   \'***********centered***********\'\n\nReplacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:\n\n   >>> \'{:+f}; {:+f}\'.format(3.14, -3.14)  # show it always\n   \'+3.140000; -3.140000\'\n   >>> \'{: f}; {: f}\'.format(3.14, -3.14)  # show a space for positive numbers\n   \' 3.140000; -3.140000\'\n   >>> \'{:-f}; {:-f}\'.format(3.14, -3.14)  # show only the minus -- same as \'{:f}; {:f}\'\n   \'3.140000; -3.140000\'\n\nReplacing ``%x`` and ``%o`` and converting the value to different\nbases:\n\n   >>> # format also supports binary numbers\n   >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)\n   \'int: 42;  hex: 2a;  oct: 52;  bin: 101010\'\n   >>> # with 0x, 0o, or 0b as prefix:\n   >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)\n   \'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n   >>> \'{:,}\'.format(1234567890)\n   \'1,234,567,890\'\n\nExpressing a percentage:\n\n   >>> points = 19\n   >>> total = 22\n   >>> \'Correct answers: {:.2%}.\'.format(points/total)\n   \'Correct answers: 86.36%\'\n\nUsing type-specific formatting:\n\n   >>> import datetime\n   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n   >>> \'{:%Y-%m-%d %H:%M:%S}\'.format(d)\n   \'2010-07-04 12:15:58\'\n\nNesting arguments and more complex examples:\n\n   >>> for align, text in zip(\'<^>\', [\'left\', \'center\', \'right\']):\n   ...     \'{0:{align}{fill}16}\'.format(text, fill=align, align=align)\n   ...\n   \'left<<<<<<<<<<<<\'\n   \'^^^^^center^^^^^\'\n   \'>>>>>>>>>>>right\'\n   >>>\n   >>> octets = [192, 168, 0, 1]\n   >>> \'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n   \'C0A80001\'\n   >>> int(_, 16)\n   3232235521\n   >>>\n   >>> width = 5\n   >>> for num in range(5,12):\n   ...     for base in \'dXob\':\n   ...         print(\'{0:{width}{base}}\'.format(num, base=base, width=width), end=\' \')\n   ...     print()\n   ...\n       5     5     5   101\n       6     6     6   110\n       7     7     7   111\n       8     8    10  1000\n       9     9    11  1001\n      10     A    12  1010\n      11     B    13  1011\n',
+ 'formatstrings': '\nFormat String Syntax\n********************\n\nThe ``str.format()`` method and the ``Formatter`` class share the same\nsyntax for format strings (although in the case of ``Formatter``,\nsubclasses can define their own format string syntax).\n\nFormat strings contain "replacement fields" surrounded by curly braces\n``{}``. Anything that is not contained in braces is considered literal\ntext, which is copied unchanged to the output.  If you need to include\na brace character in the literal text, it can be escaped by doubling:\n``{{`` and ``}}``.\n\nThe grammar for a replacement field is as follows:\n\n      replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"\n      field_name        ::= arg_name ("." attribute_name | "[" element_index "]")*\n      arg_name          ::= [identifier | integer]\n      attribute_name    ::= identifier\n      element_index     ::= integer | index_string\n      index_string      ::= <any source character except "]"> +\n      conversion        ::= "r" | "s" | "a"\n      format_spec       ::= <described in the next section>\n\nIn less formal terms, the replacement field can start with a\n*field_name* that specifies the object whose value is to be formatted\nand inserted into the output instead of the replacement field. The\n*field_name* is optionally followed by a  *conversion* field, which is\npreceded by an exclamation point ``\'!\'``, and a *format_spec*, which\nis preceded by a colon ``\':\'``.  These specify a non-default format\nfor the replacement value.\n\nSee also the *Format Specification Mini-Language* section.\n\nThe *field_name* itself begins with an *arg_name* that is either\neither a number or a keyword.  If it\'s a number, it refers to a\npositional argument, and if it\'s a keyword, it refers to a named\nkeyword argument.  If the numerical arg_names in a format string are\n0, 1, 2, ... in sequence, they can all be omitted (not just some) and\nthe numbers 0, 1, 2, ... will be automatically inserted in that order.\nThe *arg_name* can be followed by any number of index or attribute\nexpressions. An expression of the form ``\'.name\'`` selects the named\nattribute using ``getattr()``, while an expression of the form\n``\'[index]\'`` does an index lookup using ``__getitem__()``.\n\nChanged in version 3.1: The positional argument specifiers can be\nomitted, so ``\'{} {}\'`` is equivalent to ``\'{0} {1}\'``.\n\nSome simple format string examples:\n\n   "First, thou shalt count to {0}" # References first positional argument\n   "Bring me a {}"                  # Implicitly references the first positional argument\n   "From {} to {}"                  # Same as "From {0} to {1}"\n   "My quest is {name}"             # References keyword argument \'name\'\n   "Weight in tons {0.weight}"      # \'weight\' attribute of first positional arg\n   "Units destroyed: {players[0]}"  # First element of keyword argument \'players\'.\n\nThe *conversion* field causes a type coercion before formatting.\nNormally, the job of formatting a value is done by the\n``__format__()`` method of the value itself.  However, in some cases\nit is desirable to force a type to be formatted as a string,\noverriding its own definition of formatting.  By converting the value\nto a string before calling ``__format__()``, the normal formatting\nlogic is bypassed.\n\nThree conversion flags are currently supported: ``\'!s\'`` which calls\n``str()`` on the value, ``\'!r\'`` which calls ``repr()`` and ``\'!a\'``\nwhich calls ``ascii()``.\n\nSome examples:\n\n   "Harold\'s a clever {0!s}"        # Calls str() on the argument first\n   "Bring out the holy {name!r}"    # Calls repr() on the argument first\n   "More {!a}"                      # Calls ascii() on the argument first\n\nThe *format_spec* field contains a specification of how the value\nshould be presented, including such details as field width, alignment,\npadding, decimal precision and so on.  Each value type can define its\nown "formatting mini-language" or interpretation of the *format_spec*.\n\nMost built-in types support a common formatting mini-language, which\nis described in the next section.\n\nA *format_spec* field can also include nested replacement fields\nwithin it. These nested replacement fields can contain only a field\nname; conversion flags and format specifications are not allowed.  The\nreplacement fields within the format_spec are substituted before the\n*format_spec* string is interpreted. This allows the formatting of a\nvalue to be dynamically specified.\n\nSee the *Format examples* section for some examples.\n\n\nFormat Specification Mini-Language\n==================================\n\n"Format specifications" are used within replacement fields contained\nwithin a format string to define how individual values are presented\n(see *Format String Syntax*).  They can also be passed directly to the\nbuilt-in ``format()`` function.  Each formattable type may define how\nthe format specification is to be interpreted.\n\nMost built-in types implement the following options for format\nspecifications, although some of the formatting options are only\nsupported by the numeric types.\n\nA general convention is that an empty format string (``""``) produces\nthe same result as if you had called ``str()`` on the value. A non-\nempty format string typically modifies the result.\n\nThe general form of a *standard format specifier* is:\n\n   format_spec ::= [[fill]align][sign][#][0][width][,][.precision][type]\n   fill        ::= <a character other than \'}\'>\n   align       ::= "<" | ">" | "=" | "^"\n   sign        ::= "+" | "-" | " "\n   width       ::= integer\n   precision   ::= integer\n   type        ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"\n\nThe *fill* character can be any character other than \'{\' or \'}\'.  The\npresence of a fill character is signaled by the character following\nit, which must be one of the alignment options.  If the second\ncharacter of *format_spec* is not a valid alignment option, then it is\nassumed that both the fill character and the alignment option are\nabsent.\n\nThe meaning of the various alignment options is as follows:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'<\'``   | Forces the field to be left-aligned within the available   |\n   |           | space (this is the default for most objects).              |\n   +-----------+------------------------------------------------------------+\n   | ``\'>\'``   | Forces the field to be right-aligned within the available  |\n   |           | space (this is the default for numbers).                   |\n   +-----------+------------------------------------------------------------+\n   | ``\'=\'``   | Forces the padding to be placed after the sign (if any)    |\n   |           | but before the digits.  This is used for printing fields   |\n   |           | in the form \'+000000120\'. This alignment option is only    |\n   |           | valid for numeric types.                                   |\n   +-----------+------------------------------------------------------------+\n   | ``\'^\'``   | Forces the field to be centered within the available       |\n   |           | space.                                                     |\n   +-----------+------------------------------------------------------------+\n\nNote that unless a minimum field width is defined, the field width\nwill always be the same size as the data to fill it, so that the\nalignment option has no meaning in this case.\n\nThe *sign* option is only valid for number types, and can be one of\nthe following:\n\n   +-----------+------------------------------------------------------------+\n   | Option    | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'+\'``   | indicates that a sign should be used for both positive as  |\n   |           | well as negative numbers.                                  |\n   +-----------+------------------------------------------------------------+\n   | ``\'-\'``   | indicates that a sign should be used only for negative     |\n   |           | numbers (this is the default behavior).                    |\n   +-----------+------------------------------------------------------------+\n   | space     | indicates that a leading space should be used on positive  |\n   |           | numbers, and a minus sign on negative numbers.             |\n   +-----------+------------------------------------------------------------+\n\nThe ``\'#\'`` option causes the "alternate form" to be used for the\nconversion.  The alternate form is defined differently for different\ntypes.  This option is only valid for integer, float, complex and\nDecimal types. For integers, when binary, octal, or hexadecimal output\nis used, this option adds the prefix respective ``\'0b\'``, ``\'0o\'``, or\n``\'0x\'`` to the output value. For floats, complex and Decimal the\nalternate form causes the result of the conversion to always contain a\ndecimal-point character, even if no digits follow it. Normally, a\ndecimal-point character appears in the result of these conversions\nonly if a digit follows it. In addition, for ``\'g\'`` and ``\'G\'``\nconversions, trailing zeros are not removed from the result.\n\nThe ``\',\'`` option signals the use of a comma for a thousands\nseparator. For a locale aware separator, use the ``\'n\'`` integer\npresentation type instead.\n\nChanged in version 3.1: Added the ``\',\'`` option (see also **PEP\n378**).\n\n*width* is a decimal integer defining the minimum field width.  If not\nspecified, then the field width will be determined by the content.\n\nIf the *width* field is preceded by a zero (``\'0\'``) character, this\nenables zero-padding.  This is equivalent to an *alignment* type of\n``\'=\'`` and a *fill* character of ``\'0\'``.\n\nThe *precision* is a decimal number indicating how many digits should\nbe displayed after the decimal point for a floating point value\nformatted with ``\'f\'`` and ``\'F\'``, or before and after the decimal\npoint for a floating point value formatted with ``\'g\'`` or ``\'G\'``.\nFor non-number types the field indicates the maximum field size - in\nother words, how many characters will be used from the field content.\nThe *precision* is not allowed for integer values.\n\nFinally, the *type* determines how the data should be presented.\n\nThe available string presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'s\'``   | String format. This is the default type for strings and    |\n   |           | may be omitted.                                            |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as ``\'s\'``.                                       |\n   +-----------+------------------------------------------------------------+\n\nThe available integer presentation types are:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'b\'``   | Binary format. Outputs the number in base 2.               |\n   +-----------+------------------------------------------------------------+\n   | ``\'c\'``   | Character. Converts the integer to the corresponding       |\n   |           | unicode character before printing.                         |\n   +-----------+------------------------------------------------------------+\n   | ``\'d\'``   | Decimal Integer. Outputs the number in base 10.            |\n   +-----------+------------------------------------------------------------+\n   | ``\'o\'``   | Octal format. Outputs the number in base 8.                |\n   +-----------+------------------------------------------------------------+\n   | ``\'x\'``   | Hex format. Outputs the number in base 16, using lower-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'X\'``   | Hex format. Outputs the number in base 16, using upper-    |\n   |           | case letters for the digits above 9.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'n\'``   | Number. This is the same as ``\'d\'``, except that it uses   |\n   |           | the current locale setting to insert the appropriate       |\n   |           | number separator characters.                               |\n   +-----------+------------------------------------------------------------+\n   | None      | The same as ``\'d\'``.                                       |\n   +-----------+------------------------------------------------------------+\n\nIn addition to the above presentation types, integers can be formatted\nwith the floating point presentation types listed below (except\n``\'n\'`` and None). When doing so, ``float()`` is used to convert the\ninteger to a floating point number before formatting.\n\nThe available presentation types for floating point and decimal values\nare:\n\n   +-----------+------------------------------------------------------------+\n   | Type      | Meaning                                                    |\n   +===========+============================================================+\n   | ``\'e\'``   | Exponent notation. Prints the number in scientific         |\n   |           | notation using the letter \'e\' to indicate the exponent.    |\n   +-----------+------------------------------------------------------------+\n   | ``\'E\'``   | Exponent notation. Same as ``\'e\'`` except it uses an upper |\n   |           | case \'E\' as the separator character.                       |\n   +-----------+------------------------------------------------------------+\n   | ``\'f\'``   | Fixed point. Displays the number as a fixed-point number.  |\n   +-----------+------------------------------------------------------------+\n   | ``\'F\'``   | Fixed point. Same as ``\'f\'``, but converts ``nan`` to      |\n   |           | ``NAN`` and ``inf`` to ``INF``.                            |\n   +-----------+------------------------------------------------------------+\n   | ``\'g\'``   | General format.  For a given precision ``p >= 1``, this    |\n   |           | rounds the number to ``p`` significant digits and then     |\n   |           | formats the result in either fixed-point format or in      |\n   |           | scientific notation, depending on its magnitude.  The      |\n   |           | precise rules are as follows: suppose that the result      |\n   |           | formatted with presentation type ``\'e\'`` and precision     |\n   |           | ``p-1`` would have exponent ``exp``.  Then if ``-4 <= exp  |\n   |           | < p``, the number is formatted with presentation type      |\n   |           | ``\'f\'`` and precision ``p-1-exp``. Otherwise, the number   |\n   |           | is formatted with presentation type ``\'e\'`` and precision  |\n   |           | ``p-1``. In both cases insignificant trailing zeros are    |\n   |           | removed from the significand, and the decimal point is     |\n   |           | also removed if there are no remaining digits following    |\n   |           | it.  Positive and negative infinity, positive and negative |\n   |           | zero, and nans, are formatted as ``inf``, ``-inf``, ``0``, |\n   |           | ``-0`` and ``nan`` respectively, regardless of the         |\n   |           | precision.  A precision of ``0`` is treated as equivalent  |\n   |           | to a precision of ``1``.                                   |\n   +-----------+------------------------------------------------------------+\n   | ``\'G\'``   | General format. Same as ``\'g\'`` except switches to ``\'E\'`` |\n   |           | if the number gets too large. The representations of       |\n   |           | infinity and NaN are uppercased, too.                      |\n   +-----------+------------------------------------------------------------+\n   | ``\'n\'``   | Number. This is the same as ``\'g\'``, except that it uses   |\n   |           | the current locale setting to insert the appropriate       |\n   |           | number separator characters.                               |\n   +-----------+------------------------------------------------------------+\n   | ``\'%\'``   | Percentage. Multiplies the number by 100 and displays in   |\n   |           | fixed (``\'f\'``) format, followed by a percent sign.        |\n   +-----------+------------------------------------------------------------+\n   | None      | Similar to ``\'g\'``, except with at least one digit past    |\n   |           | the decimal point and a default precision of 12. This is   |\n   |           | intended to match ``str()``, except you can add the other  |\n   |           | format modifiers.                                          |\n   +-----------+------------------------------------------------------------+\n\n\nFormat examples\n===============\n\nThis section contains examples of the new format syntax and comparison\nwith the old ``%``-formatting.\n\nIn most of the cases the syntax is similar to the old\n``%``-formatting, with the addition of the ``{}`` and with ``:`` used\ninstead of ``%``. For example, ``\'%03.2f\'`` can be translated to\n``\'{:03.2f}\'``.\n\nThe new format syntax also supports new and different options, shown\nin the follow examples.\n\nAccessing arguments by position:\n\n   >>> \'{0}, {1}, {2}\'.format(\'a\', \'b\', \'c\')\n   \'a, b, c\'\n   >>> \'{}, {}, {}\'.format(\'a\', \'b\', \'c\')  # 3.1+ only\n   \'a, b, c\'\n   >>> \'{2}, {1}, {0}\'.format(\'a\', \'b\', \'c\')\n   \'c, b, a\'\n   >>> \'{2}, {1}, {0}\'.format(*\'abc\')      # unpacking argument sequence\n   \'c, b, a\'\n   >>> \'{0}{1}{0}\'.format(\'abra\', \'cad\')   # arguments\' indices can be repeated\n   \'abracadabra\'\n\nAccessing arguments by name:\n\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(latitude=\'37.24N\', longitude=\'-115.81W\')\n   \'Coordinates: 37.24N, -115.81W\'\n   >>> coord = {\'latitude\': \'37.24N\', \'longitude\': \'-115.81W\'}\n   >>> \'Coordinates: {latitude}, {longitude}\'.format(**coord)\n   \'Coordinates: 37.24N, -115.81W\'\n\nAccessing arguments\' attributes:\n\n   >>> c = 3-5j\n   >>> (\'The complex number {0} is formed from the real part {0.real} \'\n   ...  \'and the imaginary part {0.imag}.\').format(c)\n   \'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.\'\n   >>> class Point:\n   ...     def __init__(self, x, y):\n   ...         self.x, self.y = x, y\n   ...     def __str__(self):\n   ...         return \'Point({self.x}, {self.y})\'.format(self=self)\n   ...\n   >>> str(Point(4, 2))\n   \'Point(4, 2)\'\n\nAccessing arguments\' items:\n\n   >>> coord = (3, 5)\n   >>> \'X: {0[0]};  Y: {0[1]}\'.format(coord)\n   \'X: 3;  Y: 5\'\n\nReplacing ``%s`` and ``%r``:\n\n   >>> "repr() shows quotes: {!r}; str() doesn\'t: {!s}".format(\'test1\', \'test2\')\n   "repr() shows quotes: \'test1\'; str() doesn\'t: test2"\n\nAligning the text and specifying a width:\n\n   >>> \'{:<30}\'.format(\'left aligned\')\n   \'left aligned                  \'\n   >>> \'{:>30}\'.format(\'right aligned\')\n   \'                 right aligned\'\n   >>> \'{:^30}\'.format(\'centered\')\n   \'           centered           \'\n   >>> \'{:*^30}\'.format(\'centered\')  # use \'*\' as a fill char\n   \'***********centered***********\'\n\nReplacing ``%+f``, ``%-f``, and ``% f`` and specifying a sign:\n\n   >>> \'{:+f}; {:+f}\'.format(3.14, -3.14)  # show it always\n   \'+3.140000; -3.140000\'\n   >>> \'{: f}; {: f}\'.format(3.14, -3.14)  # show a space for positive numbers\n   \' 3.140000; -3.140000\'\n   >>> \'{:-f}; {:-f}\'.format(3.14, -3.14)  # show only the minus -- same as \'{:f}; {:f}\'\n   \'3.140000; -3.140000\'\n\nReplacing ``%x`` and ``%o`` and converting the value to different\nbases:\n\n   >>> # format also supports binary numbers\n   >>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)\n   \'int: 42;  hex: 2a;  oct: 52;  bin: 101010\'\n   >>> # with 0x, 0o, or 0b as prefix:\n   >>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)\n   \'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010\'\n\nUsing the comma as a thousands separator:\n\n   >>> \'{:,}\'.format(1234567890)\n   \'1,234,567,890\'\n\nExpressing a percentage:\n\n   >>> points = 19\n   >>> total = 22\n   >>> \'Correct answers: {:.2%}.\'.format(points/total)\n   \'Correct answers: 86.36%\'\n\nUsing type-specific formatting:\n\n   >>> import datetime\n   >>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n   >>> \'{:%Y-%m-%d %H:%M:%S}\'.format(d)\n   \'2010-07-04 12:15:58\'\n\nNesting arguments and more complex examples:\n\n   >>> for align, text in zip(\'<^>\', [\'left\', \'center\', \'right\']):\n   ...     \'{0:{fill}{align}16}\'.format(text, fill=align, align=align)\n   ...\n   \'left<<<<<<<<<<<<\'\n   \'^^^^^center^^^^^\'\n   \'>>>>>>>>>>>right\'\n   >>>\n   >>> octets = [192, 168, 0, 1]\n   >>> \'{:02X}{:02X}{:02X}{:02X}\'.format(*octets)\n   \'C0A80001\'\n   >>> int(_, 16)\n   3232235521\n   >>>\n   >>> width = 5\n   >>> for num in range(5,12):\n   ...     for base in \'dXob\':\n   ...         print(\'{0:{width}{base}}\'.format(num, base=base, width=width), end=\' \')\n   ...     print()\n   ...\n       5     5     5   101\n       6     6     6   110\n       7     7     7   111\n       8     8    10  1000\n       9     9    11  1001\n      10     A    12  1010\n      11     B    13  1011\n',
  'function': '\nFunction definitions\n********************\n\nA function definition defines a user-defined function object (see\nsection *The standard type hierarchy*):\n\n   funcdef        ::= [decorators] "def" funcname "(" [parameter_list] ")" ["->" expression] ":" suite\n   decorators     ::= decorator+\n   decorator      ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE\n   dotted_name    ::= identifier ("." identifier)*\n   parameter_list ::= (defparameter ",")*\n                      (  "*" [parameter] ("," defparameter)*\n                      [, "**" parameter]\n                      | "**" parameter\n                      | defparameter [","] )\n   parameter      ::= identifier [":" expression]\n   defparameter   ::= parameter ["=" expression]\n   funcname       ::= identifier\n\nA function definition is an executable statement.  Its execution binds\nthe function name in the current local namespace to a function object\n(a wrapper around the executable code for the function).  This\nfunction object contains a reference to the current global namespace\nas the global namespace to be used when the function is called.\n\nThe function definition does not execute the function body; this gets\nexecuted only when the function is called. [3]\n\nA function definition may be wrapped by one or more *decorator*\nexpressions. Decorator expressions are evaluated when the function is\ndefined, in the scope that contains the function definition.  The\nresult must be a callable, which is invoked with the function object\nas the only argument. The returned value is bound to the function name\ninstead of the function object.  Multiple decorators are applied in\nnested fashion. For example, the following code\n\n   @f1(arg)\n   @f2\n   def func(): pass\n\nis equivalent to\n\n   def func(): pass\n   func = f1(arg)(f2(func))\n\nWhen one or more parameters have the form *parameter* ``=``\n*expression*, the function is said to have "default parameter values."\nFor a parameter with a default value, the corresponding argument may\nbe omitted from a call, in which case the parameter\'s default value is\nsubstituted.  If a parameter has a default value, all following\nparameters up until the "``*``" must also have a default value ---\nthis is a syntactic restriction that is not expressed by the grammar.\n\n**Default parameter values are evaluated when the function definition\nis executed.** This means that the expression is evaluated once, when\nthe function is defined, and that that same "pre-computed" value is\nused for each call.  This is especially important to understand when a\ndefault parameter is a mutable object, such as a list or a dictionary:\nif the function modifies the object (e.g. by appending an item to a\nlist), the default value is in effect modified. This is generally not\nwhat was intended.  A way around this is to use ``None`` as the\ndefault, and explicitly test for it in the body of the function, e.g.:\n\n   def whats_on_the_telly(penguin=None):\n       if penguin is None:\n           penguin = []\n       penguin.append("property of the zoo")\n       return penguin\n\nFunction call semantics are described in more detail in section\n*Calls*. A function call always assigns values to all parameters\nmentioned in the parameter list, either from position arguments, from\nkeyword arguments, or from default values.  If the form\n"``*identifier``" is present, it is initialized to a tuple receiving\nany excess positional parameters, defaulting to the empty tuple.  If\nthe form "``**identifier``" is present, it is initialized to a new\ndictionary receiving any excess keyword arguments, defaulting to a new\nempty dictionary. Parameters after "``*``" or "``*identifier``" are\nkeyword-only parameters and may only be passed used keyword arguments.\n\nParameters may have annotations of the form "``: expression``"\nfollowing the parameter name.  Any parameter may have an annotation\neven those of the form ``*identifier`` or ``**identifier``.  Functions\nmay have "return" annotation of the form "``-> expression``" after the\nparameter list.  These annotations can be any valid Python expression\nand are evaluated when the function definition is executed.\nAnnotations may be evaluated in a different order than they appear in\nthe source code.  The presence of annotations does not change the\nsemantics of a function.  The annotation values are available as\nvalues of a dictionary keyed by the parameters\' names in the\n``__annotations__`` attribute of the function object.\n\nIt is also possible to create anonymous functions (functions not bound\nto a name), for immediate use in expressions.  This uses lambda forms,\ndescribed in section *Lambdas*.  Note that the lambda form is merely a\nshorthand for a simplified function definition; a function defined in\na "``def``" statement can be passed around or assigned to another name\njust like a function defined by a lambda form.  The "``def``" form is\nactually more powerful since it allows the execution of multiple\nstatements and annotations.\n\n**Programmer\'s note:** Functions are first-class objects.  A "``def``"\nform executed inside a function definition defines a local function\nthat can be returned or passed around.  Free variables used in the\nnested function can access the local variables of the function\ncontaining the def.  See section *Naming and binding* for details.\n',
  'global': '\nThe ``global`` statement\n************************\n\n   global_stmt ::= "global" identifier ("," identifier)*\n\nThe ``global`` statement is a declaration which holds for the entire\ncurrent code block.  It means that the listed identifiers are to be\ninterpreted as globals.  It would be impossible to assign to a global\nvariable without ``global``, although free variables may refer to\nglobals without being declared global.\n\nNames listed in a ``global`` statement must not be used in the same\ncode block textually preceding that ``global`` statement.\n\nNames listed in a ``global`` statement must not be defined as formal\nparameters or in a ``for`` loop control target, ``class`` definition,\nfunction definition, or ``import`` statement.\n\n**CPython implementation detail:** The current implementation does not\nenforce the latter two restrictions, but programs should not abuse\nthis freedom, as future implementations may enforce them or silently\nchange the meaning of the program.\n\n**Programmer\'s note:** the ``global`` is a directive to the parser.\nIt applies only to code parsed at the same time as the ``global``\nstatement. In particular, a ``global`` statement contained in a string\nor code object supplied to the built-in ``exec()`` function does not\naffect the code block *containing* the function call, and code\ncontained in such a string is unaffected by ``global`` statements in\nthe code containing the function call.  The same applies to the\n``eval()`` and ``compile()`` functions.\n',
  'id-classes': '\nReserved classes of identifiers\n*******************************\n\nCertain classes of identifiers (besides keywords) have special\nmeanings.  These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n   Not imported by ``from module import *``.  The special identifier\n   ``_`` is used in the interactive interpreter to store the result of\n   the last evaluation; it is stored in the ``builtins`` module.  When\n   not in interactive mode, ``_`` has no special meaning and is not\n   defined. See section *The import statement*.\n\n   Note: The name ``_`` is often used in conjunction with\n     internationalization; refer to the documentation for the\n     ``gettext`` module for more information on this convention.\n\n``__*__``\n   System-defined names. These names are defined by the interpreter\n   and its implementation (including the standard library).  Current\n   system names are discussed in the *Special method names* section\n   and elsewhere.  More will likely be defined in future versions of\n   Python.  *Any* use of ``__*__`` names, in any context, that does\n   not follow explicitly documented use, is subject to breakage\n   without warning.\n\n``__*``\n   Class-private names.  Names in this category, when used within the\n   context of a class definition, are re-written to use a mangled form\n   to help avoid name clashes between "private" attributes of base and\n   derived classes. See section *Identifiers (Names)*.\n',
- 'identifiers': '\nIdentifiers and keywords\n************************\n\nIdentifiers (also referred to as *names*) are described by the\nfollowing lexical definitions.\n\nThe syntax of identifiers in Python is based on the Unicode standard\nannex UAX-31, with elaboration and changes as defined below; see also\n**PEP 3131** for further details.\n\nWithin the ASCII range (U+0001..U+007F), the valid characters for\nidentifiers are the same as in Python 2.x: the uppercase and lowercase\nletters ``A`` through ``Z``, the underscore ``_`` and, except for the\nfirst character, the digits ``0`` through ``9``.\n\nPython 3.0 introduces additional characters from outside the ASCII\nrange (see **PEP 3131**).  For these characters, the classification\nuses the version of the Unicode Character Database as included in the\n``unicodedata`` module.\n\nIdentifiers are unlimited in length.  Case is significant.\n\n   identifier  ::= id_start id_continue*\n   id_start    ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>\n   id_continue ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>\n\nThe Unicode category codes mentioned above stand for:\n\n* *Lu* - uppercase letters\n\n* *Ll* - lowercase letters\n\n* *Lt* - titlecase letters\n\n* *Lm* - modifier letters\n\n* *Lo* - other letters\n\n* *Nl* - letter numbers\n\n* *Mn* - nonspacing marks\n\n* *Mc* - spacing combining marks\n\n* *Nd* - decimal numbers\n\n* *Pc* - connector punctuations\n\nAll identifiers are converted into the normal form NFC while parsing;\ncomparison of identifiers is based on NFC.\n\nA non-normative HTML file listing all valid identifier characters for\nUnicode 4.1 can be found at http://www.dcl.hpi.uni-\npotsdam.de/home/loewis/table-3131.html.\n\n\nKeywords\n========\n\nThe following identifiers are used as reserved words, or *keywords* of\nthe language, and cannot be used as ordinary identifiers.  They must\nbe spelled exactly as written here:\n\n   False      class      finally    is         return\n   None       continue   for        lambda     try\n   True       def        from       nonlocal   while\n   and        del        global     not        with\n   as         elif       if         or         yield\n   assert     else       import     pass\n   break      except     in         raise\n\n\nReserved classes of identifiers\n===============================\n\nCertain classes of identifiers (besides keywords) have special\nmeanings.  These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n   Not imported by ``from module import *``.  The special identifier\n   ``_`` is used in the interactive interpreter to store the result of\n   the last evaluation; it is stored in the ``builtins`` module.  When\n   not in interactive mode, ``_`` has no special meaning and is not\n   defined. See section *The import statement*.\n\n   Note: The name ``_`` is often used in conjunction with\n     internationalization; refer to the documentation for the\n     ``gettext`` module for more information on this convention.\n\n``__*__``\n   System-defined names. These names are defined by the interpreter\n   and its implementation (including the standard library).  Current\n   system names are discussed in the *Special method names* section\n   and elsewhere.  More will likely be defined in future versions of\n   Python.  *Any* use of ``__*__`` names, in any context, that does\n   not follow explicitly documented use, is subject to breakage\n   without warning.\n\n``__*``\n   Class-private names.  Names in this category, when used within the\n   context of a class definition, are re-written to use a mangled form\n   to help avoid name clashes between "private" attributes of base and\n   derived classes. See section *Identifiers (Names)*.\n',
+ 'identifiers': '\nIdentifiers and keywords\n************************\n\nIdentifiers (also referred to as *names*) are described by the\nfollowing lexical definitions.\n\nThe syntax of identifiers in Python is based on the Unicode standard\nannex UAX-31, with elaboration and changes as defined below; see also\n**PEP 3131** for further details.\n\nWithin the ASCII range (U+0001..U+007F), the valid characters for\nidentifiers are the same as in Python 2.x: the uppercase and lowercase\nletters ``A`` through ``Z``, the underscore ``_`` and, except for the\nfirst character, the digits ``0`` through ``9``.\n\nPython 3.0 introduces additional characters from outside the ASCII\nrange (see **PEP 3131**).  For these characters, the classification\nuses the version of the Unicode Character Database as included in the\n``unicodedata`` module.\n\nIdentifiers are unlimited in length.  Case is significant.\n\n   identifier   ::= xid_start xid_continue*\n   id_start     ::= <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, the underscore, and characters with the Other_ID_Start property>\n   id_continue  ::= <all characters in id_start, plus characters in the categories Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>\n   xid_start    ::= <all characters in id_start whose NFKC normalization is in "id_start xid_continue*">\n   xid_continue ::= <all characters in id_continue whose NFKC normalization is in "id_continue*">\n\nThe Unicode category codes mentioned above stand for:\n\n* *Lu* - uppercase letters\n\n* *Ll* - lowercase letters\n\n* *Lt* - titlecase letters\n\n* *Lm* - modifier letters\n\n* *Lo* - other letters\n\n* *Nl* - letter numbers\n\n* *Mn* - nonspacing marks\n\n* *Mc* - spacing combining marks\n\n* *Nd* - decimal numbers\n\n* *Pc* - connector punctuations\n\n* *Other_ID_Start* - explicit list of characters in PropList.txt to\n  support backwards compatibility\n\n* *Other_ID_Continue* - likewise\n\nAll identifiers are converted into the normal form NFKC while parsing;\ncomparison of identifiers is based on NFKC.\n\nA non-normative HTML file listing all valid identifier characters for\nUnicode 4.1 can be found at http://www.dcl.hpi.uni-\npotsdam.de/home/loewis/table-3131.html.\n\n\nKeywords\n========\n\nThe following identifiers are used as reserved words, or *keywords* of\nthe language, and cannot be used as ordinary identifiers.  They must\nbe spelled exactly as written here:\n\n   False      class      finally    is         return\n   None       continue   for        lambda     try\n   True       def        from       nonlocal   while\n   and        del        global     not        with\n   as         elif       if         or         yield\n   assert     else       import     pass\n   break      except     in         raise\n\n\nReserved classes of identifiers\n===============================\n\nCertain classes of identifiers (besides keywords) have special\nmeanings.  These classes are identified by the patterns of leading and\ntrailing underscore characters:\n\n``_*``\n   Not imported by ``from module import *``.  The special identifier\n   ``_`` is used in the interactive interpreter to store the result of\n   the last evaluation; it is stored in the ``builtins`` module.  When\n   not in interactive mode, ``_`` has no special meaning and is not\n   defined. See section *The import statement*.\n\n   Note: The name ``_`` is often used in conjunction with\n     internationalization; refer to the documentation for the\n     ``gettext`` module for more information on this convention.\n\n``__*__``\n   System-defined names. These names are defined by the interpreter\n   and its implementation (including the standard library).  Current\n   system names are discussed in the *Special method names* section\n   and elsewhere.  More will likely be defined in future versions of\n   Python.  *Any* use of ``__*__`` names, in any context, that does\n   not follow explicitly documented use, is subject to breakage\n   without warning.\n\n``__*``\n   Class-private names.  Names in this category, when used within the\n   context of a class definition, are re-written to use a mangled form\n   to help avoid name clashes between "private" attributes of base and\n   derived classes. See section *Identifiers (Names)*.\n',
  'if': '\nThe ``if`` statement\n********************\n\nThe ``if`` statement is used for conditional execution:\n\n   if_stmt ::= "if" expression ":" suite\n               ( "elif" expression ":" suite )*\n               ["else" ":" suite]\n\nIt selects exactly one of the suites by evaluating the expressions one\nby one until one is found to be true (see section *Boolean operations*\nfor the definition of true and false); then that suite is executed\n(and no other part of the ``if`` statement is executed or evaluated).\nIf all expressions are false, the suite of the ``else`` clause, if\npresent, is executed.\n',
  'imaginary': '\nImaginary literals\n******************\n\nImaginary literals are described by the following lexical definitions:\n\n   imagnumber ::= (floatnumber | intpart) ("j" | "J")\n\nAn imaginary literal yields a complex number with a real part of 0.0.\nComplex numbers are represented as a pair of floating point numbers\nand have the same restrictions on their range.  To create a complex\nnumber with a nonzero real part, add a floating point number to it,\ne.g., ``(3+4j)``.  Some examples of imaginary literals:\n\n   3.14j   10.j    10j     .001j   1e100j  3.14e-10j\n',
- 'import': '\nThe ``import`` statement\n************************\n\n   import_stmt     ::= "import" module ["as" name] ( "," module ["as" name] )*\n                   | "from" relative_module "import" identifier ["as" name]\n                   ( "," identifier ["as" name] )*\n                   | "from" relative_module "import" "(" identifier ["as" name]\n                   ( "," identifier ["as" name] )* [","] ")"\n                   | "from" module "import" "*"\n   module          ::= (identifier ".")* identifier\n   relative_module ::= "."* module | "."+\n   name            ::= identifier\n\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the ``import`` statement occurs). The\nstatement comes in two forms differing on whether it uses the ``from``\nkeyword. The first form (without ``from``) repeats these steps for\neach identifier in the list. The form with ``from`` performs step (1)\nonce, and then performs step (2) repeatedly. For a reference\nimplementation of step (1), see the ``importlib`` module.\n\nTo understand how step (1) occurs, one must first understand how\nPython handles hierarchical naming of modules. To help organize\nmodules and provide a hierarchy in naming, Python has a concept of\npackages. A package can contain other packages and modules while\nmodules cannot contain other modules or packages. From a file system\nperspective, packages are directories and modules are files. The\noriginal specification for packages is still available to read,\nalthough minor details have changed since the writing of that\ndocument.\n\nOnce the name of the module is known (unless otherwise specified, the\nterm "module" will refer to both packages and modules), searching for\nthe module or package can begin. The first place checked is\n``sys.modules``, the cache of all modules that have been imported\npreviously. If the module is found there then it is used in step (2)\nof import unless ``None`` is found in ``sys.modules``, in which case\n``ImportError`` is raised.\n\nIf the module is not found in the cache, then ``sys.meta_path`` is\nsearched (the specification for ``sys.meta_path`` can be found in\n**PEP 302**). The object is a list of *finder* objects which are\nqueried in order as to whether they know how to load the module by\ncalling their ``find_module()`` method with the name of the module. If\nthe module happens to be contained within a package (as denoted by the\nexistence of a dot in the name), then a second argument to\n``find_module()`` is given as the value of the ``__path__`` attribute\nfrom the parent package (everything up to the last dot in the name of\nthe module being imported). If a finder can find the module it returns\na *loader* (discussed later) or returns ``None``.\n\nIf none of the finders on ``sys.meta_path`` are able to find the\nmodule then some implicitly defined finders are queried.\nImplementations of Python vary in what implicit meta path finders are\ndefined. The one they all do define, though, is one that handles\n``sys.path_hooks``, ``sys.path_importer_cache``, and ``sys.path``.\n\nThe implicit finder searches for the requested module in the "paths"\nspecified in one of two places ("paths" do not have to be file system\npaths). If the module being imported is supposed to be contained\nwithin a package then the second argument passed to ``find_module()``,\n``__path__`` on the parent package, is used as the source of paths. If\nthe module is not contained in a package then ``sys.path`` is used as\nthe source of paths.\n\nOnce the source of paths is chosen it is iterated over to find a\nfinder that can handle that path. The dict at\n``sys.path_importer_cache`` caches finders for paths and is checked\nfor a finder. If the path does not have a finder cached then\n``sys.path_hooks`` is searched by calling each object in the list with\na single argument of the path, returning a finder or raises\n``ImportError``. If a finder is returned then it is cached in\n``sys.path_importer_cache`` and then used for that path entry. If no\nfinder can be found but the path exists then a value of ``None`` is\nstored in ``sys.path_importer_cache`` to signify that an implicit,\nfile-based finder that handles modules stored as individual files\nshould be used for that path. If the path does not exist then a finder\nwhich always returns ``None`` is placed in the cache for the path.\n\nIf no finder can find the module then ``ImportError`` is raised.\nOtherwise some finder returned a loader whose ``load_module()`` method\nis called with the name of the module to load (see **PEP 302** for the\noriginal definition of loaders). A loader has several responsibilities\nto perform on a module it loads. First, if the module already exists\nin ``sys.modules`` (a possibility if the loader is called outside of\nthe import machinery) then it is to use that module for initialization\nand not a new module. But if the module does not exist in\n``sys.modules`` then it is to be added to that dict before\ninitialization begins. If an error occurs during loading of the module\nand it was added to ``sys.modules`` it is to be removed from the dict.\nIf an error occurs but the module was already in ``sys.modules`` it is\nleft in the dict.\n\nThe loader must set several attributes on the module. ``__name__`` is\nto be set to the name of the module. ``__file__`` is to be the "path"\nto the file unless the module is built-in (and thus listed in\n``sys.builtin_module_names``) in which case the attribute is not set.\nIf what is being imported is a package then ``__path__`` is to be set\nto a list of paths to be searched when looking for modules and\npackages contained within the package being imported. ``__package__``\nis optional but should be set to the name of package that contains the\nmodule or package (the empty string is used for module not contained\nin a package). ``__loader__`` is also optional but should be set to\nthe loader object that is loading the module.\n\nIf an error occurs during loading then the loader raises\n``ImportError`` if some other exception is not already being\npropagated. Otherwise the loader returns the module that was loaded\nand initialized.\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of ``import`` statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any.  If the module name is followed by ``as``,\nthe name following ``as`` is used as the local name for the module.\n\nThe ``from`` form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound.  As with the first form of ``import``, an alternate local name\ncan be supplied by specifying "``as`` localname".  If a name is not\nfound, ``ImportError`` is raised.  If the list of identifiers is\nreplaced by a star (``\'*\'``), all public names defined in the module\nare bound in the local namespace of the ``import`` statement..\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module.  The names given in ``__all__`` are all considered public\nand are required to exist.  If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope.  The\nwild card form of import --- ``import *`` --- is only allowed at the\nmodule level. Attempting to use it in class or function definitions\nwill raise a ``SyntaxError``.\n\nWhen specifying what module to import you do not have to specify the\nabsolute name of the module. When a module or package is contained\nwithin another package it is possible to make a relative import within\nthe same top package without having to mention the package name. By\nusing leading dots in the specified module or package after ``from``\nyou can specify how high to traverse up the current package hierarchy\nwithout specifying exact names. One leading dot means the current\npackage where the module making the import exists. Two dots means up\none package level. Three dots is up two levels, etc. So if you execute\n``from . import mod`` from a module in the ``pkg`` package then you\nwill end up importing ``pkg.mod``. If you execute ``from ..subpkg2\nimport mod`` from within ``pkg.subpkg1`` you will import\n``pkg.subpkg2.mod``. The specification for relative imports is\ncontained within **PEP 328**.\n\n``importlib.import_module()`` is provided to support applications that\ndetermine which modules need to be loaded dynamically.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python.  The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language.  It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n   future_statement ::= "from" "__future__" "import" feature ["as" name]\n                        ("," feature ["as" name])*\n                        | "from" "__future__" "import" "(" feature ["as" name]\n                        ("," feature ["as" name])* [","] ")"\n   feature          ::= identifier\n   name             ::= identifier\n\nA future statement must appear near the top of the module.  The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 3.0 are ``absolute_import``,\n``division``, ``generators``, ``unicode_literals``,\n``print_function``, ``nested_scopes`` and ``with_statement``.  They\nare all redundant because they are always enabled, and only kept for\nbackwards compatibility.\n\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code.  It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently.  Such decisions cannot be pushed off until\nruntime.\n\nFor any given release, the compiler knows which feature names have\nbeen defined, and raises a compile-time error if a future statement\ncontains a feature not known to it.\n\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module ``__future__``, described later, and it\nwill be imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n   import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by calls to the built-in functions ``exec()`` and\n``compile()`` that occur in a module ``M`` containing a future\nstatement will, by default, use the new syntax or semantics associated\nwith the future statement.  This can be controlled by optional\narguments to ``compile()`` --- see the documentation of that function\nfor details.\n\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session.  If an\ninterpreter is started with the *-i* option, is passed a script name\nto execute, and the script includes a future statement, it will be in\neffect in the interactive session started after the script is\nexecuted.\n\nSee also:\n\n   **PEP 236** - Back to the __future__\n      The original proposal for the __future__ mechanism.\n',
+ 'import': '\nThe ``import`` statement\n************************\n\n   import_stmt     ::= "import" module ["as" name] ( "," module ["as" name] )*\n                   | "from" relative_module "import" identifier ["as" name]\n                   ( "," identifier ["as" name] )*\n                   | "from" relative_module "import" "(" identifier ["as" name]\n                   ( "," identifier ["as" name] )* [","] ")"\n                   | "from" module "import" "*"\n   module          ::= (identifier ".")* identifier\n   relative_module ::= "."* module | "."+\n   name            ::= identifier\n\nImport statements are executed in two steps: (1) find a module, and\ninitialize it if necessary; (2) define a name or names in the local\nnamespace (of the scope where the ``import`` statement occurs). The\nstatement comes in two forms differing on whether it uses the ``from``\nkeyword. The first form (without ``from``) repeats these steps for\neach identifier in the list. The form with ``from`` performs step (1)\nonce, and then performs step (2) repeatedly. For a reference\nimplementation of step (1), see the ``importlib`` module.\n\nTo understand how step (1) occurs, one must first understand how\nPython handles hierarchical naming of modules. To help organize\nmodules and provide a hierarchy in naming, Python has a concept of\npackages. A package can contain other packages and modules while\nmodules cannot contain other modules or packages. From a file system\nperspective, packages are directories and modules are files. The\noriginal specification for packages is still available to read,\nalthough minor details have changed since the writing of that\ndocument.\n\nOnce the name of the module is known (unless otherwise specified, the\nterm "module" will refer to both packages and modules), searching for\nthe module or package can begin. The first place checked is\n``sys.modules``, the cache of all modules that have been imported\npreviously. If the module is found there then it is used in step (2)\nof import unless ``None`` is found in ``sys.modules``, in which case\n``ImportError`` is raised.\n\nIf the module is not found in the cache, then ``sys.meta_path`` is\nsearched (the specification for ``sys.meta_path`` can be found in\n**PEP 302**). The object is a list of *finder* objects which are\nqueried in order as to whether they know how to load the module by\ncalling their ``find_module()`` method with the name of the module. If\nthe module happens to be contained within a package (as denoted by the\nexistence of a dot in the name), then a second argument to\n``find_module()`` is given as the value of the ``__path__`` attribute\nfrom the parent package (everything up to the last dot in the name of\nthe module being imported). If a finder can find the module it returns\na *loader* (discussed later) or returns ``None``.\n\nIf none of the finders on ``sys.meta_path`` are able to find the\nmodule then some implicitly defined finders are queried.\nImplementations of Python vary in what implicit meta path finders are\ndefined. The one they all do define, though, is one that handles\n``sys.path_hooks``, ``sys.path_importer_cache``, and ``sys.path``.\n\nThe implicit finder searches for the requested module in the "paths"\nspecified in one of two places ("paths" do not have to be file system\npaths). If the module being imported is supposed to be contained\nwithin a package then the second argument passed to ``find_module()``,\n``__path__`` on the parent package, is used as the source of paths. If\nthe module is not contained in a package then ``sys.path`` is used as\nthe source of paths.\n\nOnce the source of paths is chosen it is iterated over to find a\nfinder that can handle that path. The dict at\n``sys.path_importer_cache`` caches finders for paths and is checked\nfor a finder. If the path does not have a finder cached then\n``sys.path_hooks`` is searched by calling each object in the list with\na single argument of the path, returning a finder or raises\n``ImportError``. If a finder is returned then it is cached in\n``sys.path_importer_cache`` and then used for that path entry. If no\nfinder can be found but the path exists then a value of ``None`` is\nstored in ``sys.path_importer_cache`` to signify that an implicit,\nfile-based finder that handles modules stored as individual files\nshould be used for that path. If the path does not exist then a finder\nwhich always returns ``None`` is placed in the cache for the path.\n\nIf no finder can find the module then ``ImportError`` is raised.\nOtherwise some finder returned a loader whose ``load_module()`` method\nis called with the name of the module to load (see **PEP 302** for the\noriginal definition of loaders). A loader has several responsibilities\nto perform on a module it loads. First, if the module already exists\nin ``sys.modules`` (a possibility if the loader is called outside of\nthe import machinery) then it is to use that module for initialization\nand not a new module. But if the module does not exist in\n``sys.modules`` then it is to be added to that dict before\ninitialization begins. If an error occurs during loading of the module\nand it was added to ``sys.modules`` it is to be removed from the dict.\nIf an error occurs but the module was already in ``sys.modules`` it is\nleft in the dict.\n\nThe loader must set several attributes on the module. ``__name__`` is\nto be set to the name of the module. ``__file__`` is to be the "path"\nto the file unless the module is built-in (and thus listed in\n``sys.builtin_module_names``) in which case the attribute is not set.\nIf what is being imported is a package then ``__path__`` is to be set\nto a list of paths to be searched when looking for modules and\npackages contained within the package being imported. ``__package__``\nis optional but should be set to the name of package that contains the\nmodule or package (the empty string is used for module not contained\nin a package). ``__loader__`` is also optional but should be set to\nthe loader object that is loading the module.\n\nIf an error occurs during loading then the loader raises\n``ImportError`` if some other exception is not already being\npropagated. Otherwise the loader returns the module that was loaded\nand initialized.\n\nWhen step (1) finishes without raising an exception, step (2) can\nbegin.\n\nThe first form of ``import`` statement binds the module name in the\nlocal namespace to the module object, and then goes on to import the\nnext identifier, if any.  If the module name is followed by ``as``,\nthe name following ``as`` is used as the local name for the module.\n\nThe ``from`` form does not bind the module name: it goes through the\nlist of identifiers, looks each one of them up in the module found in\nstep (1), and binds the name in the local namespace to the object thus\nfound.  As with the first form of ``import``, an alternate local name\ncan be supplied by specifying "``as`` localname".  If a name is not\nfound, ``ImportError`` is raised.  If the list of identifiers is\nreplaced by a star (``\'*\'``), all public names defined in the module\nare bound in the local namespace of the ``import`` statement.\n\nThe *public names* defined by a module are determined by checking the\nmodule\'s namespace for a variable named ``__all__``; if defined, it\nmust be a sequence of strings which are names defined or imported by\nthat module.  The names given in ``__all__`` are all considered public\nand are required to exist.  If ``__all__`` is not defined, the set of\npublic names includes all names found in the module\'s namespace which\ndo not begin with an underscore character (``\'_\'``). ``__all__``\nshould contain the entire public API. It is intended to avoid\naccidentally exporting items that are not part of the API (such as\nlibrary modules which were imported and used within the module).\n\nThe ``from`` form with ``*`` may only occur in a module scope.  The\nwild card form of import --- ``import *`` --- is only allowed at the\nmodule level. Attempting to use it in class or function definitions\nwill raise a ``SyntaxError``.\n\nWhen specifying what module to import you do not have to specify the\nabsolute name of the module. When a module or package is contained\nwithin another package it is possible to make a relative import within\nthe same top package without having to mention the package name. By\nusing leading dots in the specified module or package after ``from``\nyou can specify how high to traverse up the current package hierarchy\nwithout specifying exact names. One leading dot means the current\npackage where the module making the import exists. Two dots means up\none package level. Three dots is up two levels, etc. So if you execute\n``from . import mod`` from a module in the ``pkg`` package then you\nwill end up importing ``pkg.mod``. If you execute ``from ..subpkg2\nimport mod`` from within ``pkg.subpkg1`` you will import\n``pkg.subpkg2.mod``. The specification for relative imports is\ncontained within **PEP 328**.\n\n``importlib.import_module()`` is provided to support applications that\ndetermine which modules need to be loaded dynamically.\n\n\nFuture statements\n=================\n\nA *future statement* is a directive to the compiler that a particular\nmodule should be compiled using syntax or semantics that will be\navailable in a specified future release of Python.  The future\nstatement is intended to ease migration to future versions of Python\nthat introduce incompatible changes to the language.  It allows use of\nthe new features on a per-module basis before the release in which the\nfeature becomes standard.\n\n   future_statement ::= "from" "__future__" "import" feature ["as" name]\n                        ("," feature ["as" name])*\n                        | "from" "__future__" "import" "(" feature ["as" name]\n                        ("," feature ["as" name])* [","] ")"\n   feature          ::= identifier\n   name             ::= identifier\n\nA future statement must appear near the top of the module.  The only\nlines that can appear before a future statement are:\n\n* the module docstring (if any),\n\n* comments,\n\n* blank lines, and\n\n* other future statements.\n\nThe features recognized by Python 3.0 are ``absolute_import``,\n``division``, ``generators``, ``unicode_literals``,\n``print_function``, ``nested_scopes`` and ``with_statement``.  They\nare all redundant because they are always enabled, and only kept for\nbackwards compatibility.\n\nA future statement is recognized and treated specially at compile\ntime: Changes to the semantics of core constructs are often\nimplemented by generating different code.  It may even be the case\nthat a new feature introduces new incompatible syntax (such as a new\nreserved word), in which case the compiler may need to parse the\nmodule differently.  Such decisions cannot be pushed off until\nruntime.\n\nFor any given release, the compiler knows which feature names have\nbeen defined, and raises a compile-time error if a future statement\ncontains a feature not known to it.\n\nThe direct runtime semantics are the same as for any import statement:\nthere is a standard module ``__future__``, described later, and it\nwill be imported in the usual way at the time the future statement is\nexecuted.\n\nThe interesting runtime semantics depend on the specific feature\nenabled by the future statement.\n\nNote that there is nothing special about the statement:\n\n   import __future__ [as name]\n\nThat is not a future statement; it\'s an ordinary import statement with\nno special semantics or syntax restrictions.\n\nCode compiled by calls to the built-in functions ``exec()`` and\n``compile()`` that occur in a module ``M`` containing a future\nstatement will, by default, use the new syntax or semantics associated\nwith the future statement.  This can be controlled by optional\narguments to ``compile()`` --- see the documentation of that function\nfor details.\n\nA future statement typed at an interactive interpreter prompt will\ntake effect for the rest of the interpreter session.  If an\ninterpreter is started with the *-i* option, is passed a script name\nto execute, and the script includes a future statement, it will be in\neffect in the interactive session started after the script is\nexecuted.\n\nSee also:\n\n   **PEP 236** - Back to the __future__\n      The original proposal for the __future__ mechanism.\n',
  'in': '\nComparisons\n***********\n\nUnlike C, all comparison operations in Python have the same priority,\nwhich is lower than that of any arithmetic, shifting or bitwise\noperation.  Also unlike C, expressions like ``a < b < c`` have the\ninterpretation that is conventional in mathematics:\n\n   comparison    ::= or_expr ( comp_operator or_expr )*\n   comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="\n                     | "is" ["not"] | ["not"] "in"\n\nComparisons yield boolean values: ``True`` or ``False``.\n\nComparisons can be chained arbitrarily, e.g., ``x < y <= z`` is\nequivalent to ``x < y and y <= z``, except that ``y`` is evaluated\nonly once (but in both cases ``z`` is not evaluated at all when ``x <\ny`` is found to be false).\n\nFormally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*,\n*op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y\nopN z`` is equivalent to ``a op1 b and b op2 c and ... y opN z``,\nexcept that each expression is evaluated at most once.\n\nNote that ``a op1 b op2 c`` doesn\'t imply any kind of comparison\nbetween *a* and *c*, so that, e.g., ``x < y > z`` is perfectly legal\n(though perhaps not pretty).\n\nThe operators ``<``, ``>``, ``==``, ``>=``, ``<=``, and ``!=`` compare\nthe values of two objects.  The objects need not have the same type.\nIf both are numbers, they are converted to a common type.  Otherwise,\nthe ``==`` and ``!=`` operators *always* consider objects of different\ntypes to be unequal, while the ``<``, ``>``, ``>=`` and ``<=``\noperators raise a ``TypeError`` when comparing objects of different\ntypes that do not implement these operators for the given pair of\ntypes.  You can control comparison behavior of objects of non-built-in\ntypes by defining rich comparison methods like ``__gt__()``, described\nin section *Basic customization*.\n\nComparison of objects of the same type depends on the type:\n\n* Numbers are compared arithmetically.\n\n* The values ``float(\'NaN\')`` and ``Decimal(\'NaN\')`` are special. The\n  are identical to themselves, ``x is x`` but are not equal to\n  themselves, ``x != x``.  Additionally, comparing any value to a\n  not-a-number value will return ``False``.  For example, both ``3 <\n  float(\'NaN\')`` and ``float(\'NaN\') < 3`` will return ``False``.\n\n* Bytes objects are compared lexicographically using the numeric\n  values of their elements.\n\n* Strings are compared lexicographically using the numeric equivalents\n  (the result of the built-in function ``ord()``) of their characters.\n  [3] String and bytes object can\'t be compared!\n\n* Tuples and lists are compared lexicographically using comparison of\n  corresponding elements.  This means that to compare equal, each\n  element must compare equal and the two sequences must be of the same\n  type and have the same length.\n\n  If not equal, the sequences are ordered the same as their first\n  differing elements.  For example, ``[1,2,x] <= [1,2,y]`` has the\n  same value as ``x <= y``.  If the corresponding element does not\n  exist, the shorter sequence is ordered first (for example, ``[1,2] <\n  [1,2,3]``).\n\n* Mappings (dictionaries) compare equal if and only if they have the\n  same ``(key, value)`` pairs. Order comparisons ``(\'<\', \'<=\', \'>=\',\n  \'>\')`` raise ``TypeError``.\n\n* Sets and frozensets define comparison operators to mean subset and\n  superset tests.  Those relations do not define total orderings (the\n  two sets ``{1,2}`` and {2,3} are not equal, nor subsets of one\n  another, nor supersets of one another).  Accordingly, sets are not\n  appropriate arguments for functions which depend on total ordering.\n  For example, ``min()``, ``max()``, and ``sorted()`` produce\n  undefined results given a list of sets as inputs.\n\n* Most other objects of built-in types compare unequal unless they are\n  the same object; the choice whether one object is considered smaller\n  or larger than another one is made arbitrarily but consistently\n  within one execution of a program.\n\nComparison of objects of the differing types depends on whether either\nof the types provide explicit support for the comparison.  Most\nnumeric types can be compared with one another, but comparisons of\n``float`` and ``Decimal`` are not supported to avoid the inevitable\nconfusion arising from representation issues such as ``float(\'1.1\')``\nbeing inexactly represented and therefore not exactly equal to\n``Decimal(\'1.1\')`` which is.  When cross-type comparison is not\nsupported, the comparison method returns ``NotImplemented``.  This can\ncreate the illusion of non-transitivity between supported cross-type\ncomparisons and unsupported comparisons.  For example, ``Decimal(2) ==\n2`` and ``2 == float(2)`` but ``Decimal(2) != float(2)``.\n\nThe operators ``in`` and ``not in`` test for membership.  ``x in s``\nevaluates to true if *x* is a member of *s*, and false otherwise.  ``x\nnot in s`` returns the negation of ``x in s``.  All built-in sequences\nand set types support this as well as dictionary, for which ``in``\ntests whether a the dictionary has a given key. For container types\nsuch as list, tuple, set, frozenset, dict, or collections.deque, the\nexpression ``x in y`` is equivalent to ``any(x is e or x == e for e in\ny)``.\n\nFor the string and bytes types, ``x in y`` is true if and only if *x*\nis a substring of *y*.  An equivalent test is ``y.find(x) != -1``.\nEmpty strings are always considered to be a substring of any other\nstring, so ``"" in "abc"`` will return ``True``.\n\nFor user-defined classes which define the ``__contains__()`` method,\n``x in y`` is true if and only if ``y.__contains__(x)`` is true.\n\nFor user-defined classes which do not define ``__contains__()`` but do\ndefine ``__iter__()``, ``x in y`` is true if some value ``z`` with ``x\n== z`` is produced while iterating over ``y``.  If an exception is\nraised during the iteration, it is as if ``in`` raised that exception.\n\nLastly, the old-style iteration protocol is tried: if a class defines\n``__getitem__()``, ``x in y`` is true if and only if there is a non-\nnegative integer index *i* such that ``x == y[i]``, and all lower\ninteger indices do not raise ``IndexError`` exception.  (If any other\nexception is raised, it is as if ``in`` raised that exception).\n\nThe operator ``not in`` is defined to have the inverse true value of\n``in``.\n\nThe operators ``is`` and ``is not`` test for object identity: ``x is\ny`` is true if and only if *x* and *y* are the same object.  ``x is\nnot y`` yields the inverse truth value. [4]\n',
  'integers': '\nInteger literals\n****************\n\nInteger literals are described by the following lexical definitions:\n\n   integer        ::= decimalinteger | octinteger | hexinteger | bininteger\n   decimalinteger ::= nonzerodigit digit* | "0"+\n   nonzerodigit   ::= "1"..."9"\n   digit          ::= "0"..."9"\n   octinteger     ::= "0" ("o" | "O") octdigit+\n   hexinteger     ::= "0" ("x" | "X") hexdigit+\n   bininteger     ::= "0" ("b" | "B") bindigit+\n   octdigit       ::= "0"..."7"\n   hexdigit       ::= digit | "a"..."f" | "A"..."F"\n   bindigit       ::= "0" | "1"\n\nThere is no limit for the length of integer literals apart from what\ncan be stored in available memory.\n\nNote that leading zeros in a non-zero decimal number are not allowed.\nThis is for disambiguation with C-style octal literals, which Python\nused before version 3.0.\n\nSome examples of integer literals:\n\n   7     2147483647                        0o177    0b100110111\n   3     79228162514264337593543950336     0o377    0x100000000\n         79228162514264337593543950336              0xdeadbeef\n',
  'lambda': '\nLambdas\n*******\n\n   lambda_form        ::= "lambda" [parameter_list]: expression\n   lambda_form_nocond ::= "lambda" [parameter_list]: expression_nocond\n\nLambda forms (lambda expressions) have the same syntactic position as\nexpressions.  They are a shorthand to create anonymous functions; the\nexpression ``lambda arguments: expression`` yields a function object.\nThe unnamed object behaves like a function object defined with\n\n   def <lambda>(arguments):\n       return expression\n\nSee section *Function definitions* for the syntax of parameter lists.\nNote that functions created with lambda forms cannot contain\nstatements or annotations.\n',
  'lists': '\nList displays\n*************\n\nA list display is a possibly empty series of expressions enclosed in\nsquare brackets:\n\n   list_display ::= "[" [expression_list | comprehension] "]"\n\nA list display yields a new list object, the contents being specified\nby either a list of expressions or a comprehension.  When a comma-\nseparated list of expressions is supplied, its elements are evaluated\nfrom left to right and placed into the list object in that order.\nWhen a comprehension is supplied, the list is constructed from the\nelements resulting from the comprehension.\n',
- 'naming': "\nNaming and binding\n******************\n\n*Names* refer to objects.  Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block.  A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the '**-c**' option) is a code block.  The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*.  A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block's execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block.  If a local\nvariable is defined in a block, its scope includes that block.  If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name.  The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope.  This\nmeans that the following will fail:\n\n   class A:\n       a = 42\n       b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope.  The set of all such scopes visible to a code block\nis called the block's *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``.  If a name is bound at the module\nlevel, it is a global variable.  (The variables of the module code\nblock are local and global.)  If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised.  ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or ``except`` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore.  This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).  It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block.  This can lead to errors when a name is used within a\nblock before it is bound.  This rule is subtle.  Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block.  The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace.  Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtins namespace, the\nnamespace of the module ``builtins``.  The global namespace is\nsearched first.  If the name is not found there, the builtins\nnamespace is searched.  The global statement must precede all uses of\nthe name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module's dictionary is used).  By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail.  Users\nwanting to override values in the builtins namespace should ``import``\nthe ``builtins`` module and modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported.  The main module for a script is always called\n``__main__``.\n\nThe global statement has the same scope as a name binding operation in\nthe same block.  If the nearest enclosing scope for a free variable\ncontains a global statement, the free variable is treated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class.  Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n=================================\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n",
+ 'naming': "\nNaming and binding\n******************\n\n*Names* refer to objects.  Names are introduced by name binding\noperations. Each occurrence of a name in the program text refers to\nthe *binding* of that name established in the innermost function block\ncontaining the use.\n\nA *block* is a piece of Python program text that is executed as a\nunit. The following are blocks: a module, a function body, and a class\ndefinition. Each command typed interactively is a block.  A script\nfile (a file given as standard input to the interpreter or specified\non the interpreter command line the first argument) is a code block.\nA script command (a command specified on the interpreter command line\nwith the '**-c**' option) is a code block.  The string argument passed\nto the built-in functions ``eval()`` and ``exec()`` is a code block.\n\nA code block is executed in an *execution frame*.  A frame contains\nsome administrative information (used for debugging) and determines\nwhere and how execution continues after the code block's execution has\ncompleted.\n\nA *scope* defines the visibility of a name within a block.  If a local\nvariable is defined in a block, its scope includes that block.  If the\ndefinition occurs in a function block, the scope extends to any blocks\ncontained within the defining one, unless a contained block introduces\na different binding for the name.  The scope of names defined in a\nclass block is limited to the class block; it does not extend to the\ncode blocks of methods -- this includes comprehensions and generator\nexpressions since they are implemented using a function scope.  This\nmeans that the following will fail:\n\n   class A:\n       a = 42\n       b = list(a + i for i in range(10))\n\nWhen a name is used in a code block, it is resolved using the nearest\nenclosing scope.  The set of all such scopes visible to a code block\nis called the block's *environment*.\n\nIf a name is bound in a block, it is a local variable of that block,\nunless declared as ``nonlocal``.  If a name is bound at the module\nlevel, it is a global variable.  (The variables of the module code\nblock are local and global.)  If a variable is used in a code block\nbut not defined there, it is a *free variable*.\n\nWhen a name is not found at all, a ``NameError`` exception is raised.\nIf the name refers to a local variable that has not been bound, a\n``UnboundLocalError`` exception is raised.  ``UnboundLocalError`` is a\nsubclass of ``NameError``.\n\nThe following constructs bind names: formal parameters to functions,\n``import`` statements, class and function definitions (these bind the\nclass or function name in the defining block), and targets that are\nidentifiers if occurring in an assignment, ``for`` loop header, or\nafter ``as`` in a ``with`` statement or ``except`` clause. The\n``import`` statement of the form ``from ... import *`` binds all names\ndefined in the imported module, except those beginning with an\nunderscore.  This form may only be used at the module level.\n\nA target occurring in a ``del`` statement is also considered bound for\nthis purpose (though the actual semantics are to unbind the name).  It\nis illegal to unbind a name that is referenced by an enclosing scope;\nthe compiler will report a ``SyntaxError``.\n\nEach assignment or import statement occurs within a block defined by a\nclass or function definition or at the module level (the top-level\ncode block).\n\nIf a name binding operation occurs anywhere within a code block, all\nuses of the name within the block are treated as references to the\ncurrent block.  This can lead to errors when a name is used within a\nblock before it is bound.  This rule is subtle.  Python lacks\ndeclarations and allows name binding operations to occur anywhere\nwithin a code block.  The local variables of a code block can be\ndetermined by scanning the entire text of the block for name binding\noperations.\n\nIf the ``global`` statement occurs within a block, all uses of the\nname specified in the statement refer to the binding of that name in\nthe top-level namespace.  Names are resolved in the top-level\nnamespace by searching the global namespace, i.e. the namespace of the\nmodule containing the code block, and the builtins namespace, the\nnamespace of the module ``builtins``.  The global namespace is\nsearched first.  If the name is not found there, the builtins\nnamespace is searched.  The global statement must precede all uses of\nthe name.\n\nThe builtins namespace associated with the execution of a code block\nis actually found by looking up the name ``__builtins__`` in its\nglobal namespace; this should be a dictionary or a module (in the\nlatter case the module's dictionary is used).  By default, when in the\n``__main__`` module, ``__builtins__`` is the built-in module\n``builtins``; when in any other module, ``__builtins__`` is an alias\nfor the dictionary of the ``builtins`` module itself.\n``__builtins__`` can be set to a user-created dictionary to create a\nweak form of restricted execution.\n\n**CPython implementation detail:** Users should not touch\n``__builtins__``; it is strictly an implementation detail.  Users\nwanting to override values in the builtins namespace should ``import``\nthe ``builtins`` module and modify its attributes appropriately.\n\nThe namespace for a module is automatically created the first time a\nmodule is imported.  The main module for a script is always called\n``__main__``.\n\nThe ``global`` statement has the same scope as a name binding\noperation in the same block.  If the nearest enclosing scope for a\nfree variable contains a global statement, the free variable is\ntreated as a global.\n\nA class definition is an executable statement that may use and define\nnames. These references follow the normal rules for name resolution.\nThe namespace of the class definition becomes the attribute dictionary\nof the class.  Names defined at the class scope are not visible in\nmethods.\n\n\nInteraction with dynamic features\n=================================\n\nThere are several cases where Python statements are illegal when used\nin conjunction with nested scopes that contain free variables.\n\nIf a variable is referenced in an enclosing scope, it is illegal to\ndelete the name.  An error will be reported at compile time.\n\nIf the wild card form of import --- ``import *`` --- is used in a\nfunction and the function contains or is a nested block with free\nvariables, the compiler will raise a ``SyntaxError``.\n\nThe ``eval()`` and ``exec()`` functions do not have access to the full\nenvironment for resolving names.  Names may be resolved in the local\nand global namespaces of the caller.  Free variables are not resolved\nin the nearest enclosing namespace, but in the global namespace.  [1]\nThe ``exec()`` and ``eval()`` functions have optional arguments to\noverride the global and local namespace.  If only one namespace is\nspecified, it is used for both.\n",
  'nonlocal': '\nThe ``nonlocal`` statement\n**************************\n\n   nonlocal_stmt ::= "nonlocal" identifier ("," identifier)*\n\nThe ``nonlocal`` statement causes the listed identifiers to refer to\npreviously bound variables in the nearest enclosing scope.  This is\nimportant because the default behavior for binding is to search the\nlocal namespace first.  The statement allows encapsulated code to\nrebind variables outside of the local scope besides the global\n(module) scope.\n\nNames listed in a ``nonlocal`` statement, unlike to those listed in a\n``global`` statement, must refer to pre-existing bindings in an\nenclosing scope (the scope in which a new binding should be created\ncannot be determined unambiguously).\n\nNames listed in a ``nonlocal`` statement must not collide with pre-\nexisting bindings in the local scope.\n\nSee also:\n\n   **PEP 3104** - Access to Names in Outer Scopes\n      The specification for the ``nonlocal`` statement.\n\n-[ Footnotes ]-\n\n[1] It may occur within an ``except`` or ``else`` clause.  The\n    restriction on occurring in the ``try`` clause is implementor\'s\n    laziness and will eventually be lifted.\n',
  'numbers': "\nNumeric literals\n****************\n\nThere are three types of numeric literals: integers, floating point\nnumbers, and imaginary numbers.  There are no complex literals\n(complex numbers can be formed by adding a real number and an\nimaginary number).\n\nNote that numeric literals do not include a sign; a phrase like ``-1``\nis actually an expression composed of the unary operator '``-``' and\nthe literal ``1``.\n",
  'numeric-types': "\nEmulating numeric types\n***********************\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``).  For instance, to evaluate the expression ``x + y``, where\n   *x* is an instance of a class that has an ``__add__()`` method,\n   ``x.__add__(y)`` is called.  The ``__divmod__()`` method should be\n   the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n   should not be related to ``__truediv__()``.  Note that\n   ``__pow__()`` should be defined to accept an optional third\n   argument if the ternary version of the built-in ``pow()`` function\n   is to be supported.\n\n   If one of those methods does not support the operation with the\n   supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``) with reflected (swapped) operands. These functions are only\n   called if the left operand does not support the corresponding\n   operation and the operands are of different types. [2]  For\n   instance, to evaluate the expression ``x - y``, where *y* is an\n   instance of a class that has an ``__rsub__()`` method,\n   ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n   *NotImplemented*.\n\n   Note that ternary ``pow()`` will not try calling ``__rpow__()``\n   (the coercion rules would become too complicated).\n\n   Note: If the right operand's type is a subclass of the left operand's\n     type and that subclass provides the reflected method for the\n     operation, this method will be called before the left operand's\n     non-reflected method.  This behavior allows subclasses to\n     override their ancestors' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n   These methods are called to implement the augmented arithmetic\n   assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n   ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``).  These methods\n   should attempt to do the operation in-place (modifying *self*) and\n   return the result (which could be, but does not have to be,\n   *self*).  If a specific method is not defined, the augmented\n   assignment falls back to the normal methods.  For instance, to\n   execute the statement ``x += y``, where *x* is an instance of a\n   class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n   called.  If *x* is an instance of a class that does not define a\n   ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n   considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n   Called to implement the unary arithmetic operations (``-``, ``+``,\n   ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n   Called to implement the built-in functions ``complex()``,\n   ``int()``, ``float()`` and ``round()``.  Should return a value of\n   the appropriate type.\n\nobject.__index__(self)\n\n   Called to implement ``operator.index()``.  Also called whenever\n   Python needs an integer object (such as in slicing, or in the\n   built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n   an integer.\n",
  'objects': '\nObjects, values and types\n*************************\n\n*Objects* are Python\'s abstraction for data.  All data in a Python\nprogram is represented by objects or by relations between objects. (In\na sense, and in conformance to Von Neumann\'s model of a "stored\nprogram computer," code is also represented by objects.)\n\nEvery object has an identity, a type and a value.  An object\'s\n*identity* never changes once it has been created; you may think of it\nas the object\'s address in memory.  The \'``is``\' operator compares the\nidentity of two objects; the ``id()`` function returns an integer\nrepresenting its identity (currently implemented as its address). An\nobject\'s *type* is also unchangeable. [1] An object\'s type determines\nthe operations that the object supports (e.g., "does it have a\nlength?") and also defines the possible values for objects of that\ntype.  The ``type()`` function returns an object\'s type (which is an\nobject itself).  The *value* of some objects can change.  Objects\nwhose value can change are said to be *mutable*; objects whose value\nis unchangeable once they are created are called *immutable*. (The\nvalue of an immutable container object that contains a reference to a\nmutable object can change when the latter\'s value is changed; however\nthe container is still considered immutable, because the collection of\nobjects it contains cannot be changed.  So, immutability is not\nstrictly the same as having an unchangeable value, it is more subtle.)\nAn object\'s mutability is determined by its type; for instance,\nnumbers, strings and tuples are immutable, while dictionaries and\nlists are mutable.\n\nObjects are never explicitly destroyed; however, when they become\nunreachable they may be garbage-collected.  An implementation is\nallowed to postpone garbage collection or omit it altogether --- it is\na matter of implementation quality how garbage collection is\nimplemented, as long as no objects are collected that are still\nreachable.\n\n**CPython implementation detail:** CPython currently uses a reference-\ncounting scheme with (optional) delayed detection of cyclically linked\ngarbage, which collects most objects as soon as they become\nunreachable, but is not guaranteed to collect garbage containing\ncircular references.  See the documentation of the ``gc`` module for\ninformation on controlling the collection of cyclic garbage. Other\nimplementations act differently and CPython may change.\n\nNote that the use of the implementation\'s tracing or debugging\nfacilities may keep objects alive that would normally be collectable.\nAlso note that catching an exception with a \'``try``...``except``\'\nstatement may keep objects alive.\n\nSome objects contain references to "external" resources such as open\nfiles or windows.  It is understood that these resources are freed\nwhen the object is garbage-collected, but since garbage collection is\nnot guaranteed to happen, such objects also provide an explicit way to\nrelease the external resource, usually a ``close()`` method. Programs\nare strongly recommended to explicitly close such objects.  The\n\'``try``...``finally``\' statement and the \'``with``\' statement provide\nconvenient ways to do this.\n\nSome objects contain references to other objects; these are called\n*containers*. Examples of containers are tuples, lists and\ndictionaries.  The references are part of a container\'s value.  In\nmost cases, when we talk about the value of a container, we imply the\nvalues, not the identities of the contained objects; however, when we\ntalk about the mutability of a container, only the identities of the\nimmediately contained objects are implied.  So, if an immutable\ncontainer (like a tuple) contains a reference to a mutable object, its\nvalue changes if that mutable object is changed.\n\nTypes affect almost all aspects of object behavior.  Even the\nimportance of object identity is affected in some sense: for immutable\ntypes, operations that compute new values may actually return a\nreference to any existing object with the same type and value, while\nfor mutable objects this is not allowed.  E.g., after ``a = 1; b =\n1``, ``a`` and ``b`` may or may not refer to the same object with the\nvalue one, depending on the implementation, but after ``c = []; d =\n[]``, ``c`` and ``d`` are guaranteed to refer to two different,\nunique, newly created empty lists. (Note that ``c = d = []`` assigns\nthe same object to both ``c`` and ``d``.)\n',
- 'operator-summary': '\nSummary\n*******\n\nThe following table summarizes the operator precedences in Python,\nfrom lowest precedence (least binding) to highest precedence (most\nbinding).  Operators in the same box have the same precedence.  Unless\nthe syntax is explicitly given, operators are binary.  Operators in\nthe same box group left to right (except for comparisons, including\ntests, which all have the same precedence and chain from left to right\n--- see section *Comparisons* --- and exponentiation, which groups\nfrom right to left).\n\n+-------------------------------------------------+---------------------------------------+\n| Operator                                        | Description                           |\n+=================================================+=======================================+\n| ``lambda``                                      | Lambda expression                     |\n+-------------------------------------------------+---------------------------------------+\n| ``if`` -- ``else``                              | Conditional expression                |\n+-------------------------------------------------+---------------------------------------+\n| ``or``                                          | Boolean OR                            |\n+-------------------------------------------------+---------------------------------------+\n| ``and``                                         | Boolean AND                           |\n+-------------------------------------------------+---------------------------------------+\n| ``not`` *x*                                     | Boolean NOT                           |\n+-------------------------------------------------+---------------------------------------+\n| ``in``, ``not`` ``in``, ``is``, ``is not``,     | Comparisons, including membership     |\n| ``<``, ``<=``, ``>``, ``>=``, ``!=``, ``==``    | tests and identity tests,             |\n+-------------------------------------------------+---------------------------------------+\n| ``|``                                           | Bitwise OR                            |\n+-------------------------------------------------+---------------------------------------+\n| ``^``                                           | Bitwise XOR                           |\n+-------------------------------------------------+---------------------------------------+\n| ``&``                                           | Bitwise AND                           |\n+-------------------------------------------------+---------------------------------------+\n| ``<<``, ``>>``                                  | Shifts                                |\n+-------------------------------------------------+---------------------------------------+\n| ``+``, ``-``                                    | Addition and subtraction              |\n+-------------------------------------------------+---------------------------------------+\n| ``*``, ``/``, ``//``, ``%``                     | Multiplication, division, remainder   |\n|                                                 | [5]                                   |\n+-------------------------------------------------+---------------------------------------+\n| ``+x``, ``-x``, ``~x``                          | Positive, negative, bitwise NOT       |\n+-------------------------------------------------+---------------------------------------+\n| ``**``                                          | Exponentiation [6]                    |\n+-------------------------------------------------+---------------------------------------+\n| ``x[index]``, ``x[index:index]``,               | Subscription, slicing, call,          |\n| ``x(arguments...)``, ``x.attribute``            | attribute reference                   |\n+-------------------------------------------------+---------------------------------------+\n| ``(expressions...)``, ``[expressions...]``,     | Binding or tuple display, list        |\n| ``{key:datum...}``,                             | display, dictionary display,          |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it\n    may not be true numerically due to roundoff.  For example, and\n    assuming a platform on which a Python float is an IEEE 754 double-\n    precision number, in order that ``-1e-100 % 1e100`` have the same\n    sign as ``1e100``, the computed result is ``-1e-100 + 1e100``,\n    which is numerically exactly equal to ``1e100``.  Function\n    ``fmod()`` in the ``math`` module returns a result whose sign\n    matches the sign of the first argument instead, and so returns\n    ``-1e-100`` in this case. Which approach is more appropriate\n    depends on the application.\n\n[2] If x is very close to an exact integer multiple of y, it\'s\n    possible for ``x//y`` to be one larger than ``(x-x%y)//y`` due to\n    rounding.  In such cases, Python returns the latter result, in\n    order to preserve that ``divmod(x,y)[0] * y + x % y`` be very\n    close to ``x``.\n\n[3] While comparisons between strings make sense at the byte level,\n    they may be counter-intuitive to users.  For example, the strings\n    ``"\\u00C7"`` and ``"\\u0327\\u0043"`` compare differently, even\n    though they both represent the same unicode character (LATIN\n    CAPITAL LETTER C WITH CEDILLA).  To compare strings in a human\n    recognizable way, compare using ``unicodedata.normalize()``.\n\n[4] Due to automatic garbage-collection, free lists, and the dynamic\n    nature of descriptors, you may notice seemingly unusual behaviour\n    in certain uses of the ``is`` operator, like those involving\n    comparisons between instance methods, or constants.  Check their\n    documentation for more info.\n\n[5] The ``%`` is also used for string formatting; the same precedence\n    applies.\n\n[6] The power operator ``**`` binds less tightly than an arithmetic or\n    bitwise unary operator on its right, that is, ``2**-1`` is\n    ``0.5``.\n',
+ 'operator-summary': '\nSummary\n*******\n\nThe following table summarizes the operator precedences in Python,\nfrom lowest precedence (least binding) to highest precedence (most\nbinding).  Operators in the same box have the same precedence.  Unless\nthe syntax is explicitly given, operators are binary.  Operators in\nthe same box group left to right (except for comparisons, including\ntests, which all have the same precedence and chain from left to right\n--- see section *Comparisons* --- and exponentiation, which groups\nfrom right to left).\n\n+-------------------------------------------------+---------------------------------------+\n| Operator                                        | Description                           |\n+=================================================+=======================================+\n| ``lambda``                                      | Lambda expression                     |\n+-------------------------------------------------+---------------------------------------+\n| ``if`` -- ``else``                              | Conditional expression                |\n+-------------------------------------------------+---------------------------------------+\n| ``or``                                          | Boolean OR                            |\n+-------------------------------------------------+---------------------------------------+\n| ``and``                                         | Boolean AND                           |\n+-------------------------------------------------+---------------------------------------+\n| ``not`` *x*                                     | Boolean NOT                           |\n+-------------------------------------------------+---------------------------------------+\n| ``in``, ``not`` ``in``, ``is``, ``is not``,     | Comparisons, including membership     |\n| ``<``, ``<=``, ``>``, ``>=``, ``!=``, ``==``    | tests and identity tests,             |\n+-------------------------------------------------+---------------------------------------+\n| ``|``                                           | Bitwise OR                            |\n+-------------------------------------------------+---------------------------------------+\n| ``^``                                           | Bitwise XOR                           |\n+-------------------------------------------------+---------------------------------------+\n| ``&``                                           | Bitwise AND                           |\n+-------------------------------------------------+---------------------------------------+\n| ``<<``, ``>>``                                  | Shifts                                |\n+-------------------------------------------------+---------------------------------------+\n| ``+``, ``-``                                    | Addition and subtraction              |\n+-------------------------------------------------+---------------------------------------+\n| ``*``, ``/``, ``//``, ``%``                     | Multiplication, division, remainder   |\n|                                                 | [5]                                   |\n+-------------------------------------------------+---------------------------------------+\n| ``+x``, ``-x``, ``~x``                          | Positive, negative, bitwise NOT       |\n+-------------------------------------------------+---------------------------------------+\n| ``**``                                          | Exponentiation [6]                    |\n+-------------------------------------------------+---------------------------------------+\n| ``x[index]``, ``x[index:index]``,               | Subscription, slicing, call,          |\n| ``x(arguments...)``, ``x.attribute``            | attribute reference                   |\n+-------------------------------------------------+---------------------------------------+\n| ``(expressions...)``, ``[expressions...]``,     | Binding or tuple display, list        |\n| ``{key:datum...}``, ``{expressions...}``        | display, dictionary display, set      |\n|                                                 | display                               |\n+-------------------------------------------------+---------------------------------------+\n\n-[ Footnotes ]-\n\n[1] While ``abs(x%y) < abs(y)`` is true mathematically, for floats it\n    may not be true numerically due to roundoff.  For example, and\n    assuming a platform on which a Python float is an IEEE 754 double-\n    precision number, in order that ``-1e-100 % 1e100`` have the same\n    sign as ``1e100``, the computed result is ``-1e-100 + 1e100``,\n    which is numerically exactly equal to ``1e100``.  The function\n    ``math.fmod()`` returns a result whose sign matches the sign of\n    the first argument instead, and so returns ``-1e-100`` in this\n    case. Which approach is more appropriate depends on the\n    application.\n\n[2] If x is very close to an exact integer multiple of y, it\'s\n    possible for ``x//y`` to be one larger than ``(x-x%y)//y`` due to\n    rounding.  In such cases, Python returns the latter result, in\n    order to preserve that ``divmod(x,y)[0] * y + x % y`` be very\n    close to ``x``.\n\n[3] While comparisons between strings make sense at the byte level,\n    they may be counter-intuitive to users.  For example, the strings\n    ``"\\u00C7"`` and ``"\\u0327\\u0043"`` compare differently, even\n    though they both represent the same unicode character (LATIN\n    CAPITAL LETTER C WITH CEDILLA).  To compare strings in a human\n    recognizable way, compare using ``unicodedata.normalize()``.\n\n[4] Due to automatic garbage-collection, free lists, and the dynamic\n    nature of descriptors, you may notice seemingly unusual behaviour\n    in certain uses of the ``is`` operator, like those involving\n    comparisons between instance methods, or constants.  Check their\n    documentation for more info.\n\n[5] The ``%`` operator is also used for string formatting; the same\n    precedence applies.\n\n[6] The power operator ``**`` binds less tightly than an arithmetic or\n    bitwise unary operator on its right, that is, ``2**-1`` is\n    ``0.5``.\n',
  'pass': '\nThe ``pass`` statement\n**********************\n\n   pass_stmt ::= "pass"\n\n``pass`` is a null operation --- when it is executed, nothing happens.\nIt is useful as a placeholder when a statement is required\nsyntactically, but no code needs to be executed, for example:\n\n   def f(arg): pass    # a function that does nothing (yet)\n\n   class C: pass       # a class with no methods (yet)\n',
  'power': '\nThe power operator\n******************\n\nThe power operator binds more tightly than unary operators on its\nleft; it binds less tightly than unary operators on its right.  The\nsyntax is:\n\n   power ::= primary ["**" u_expr]\n\nThus, in an unparenthesized sequence of power and unary operators, the\noperators are evaluated from right to left (this does not constrain\nthe evaluation order for the operands): ``-1**2`` results in ``-1``.\n\nThe power operator has the same semantics as the built-in ``pow()``\nfunction, when called with two arguments: it yields its left argument\nraised to the power of its right argument.  The numeric arguments are\nfirst converted to a common type, and the result is of that type.\n\nFor int operands, the result has the same type as the operands unless\nthe second argument is negative; in that case, all arguments are\nconverted to float and a float result is delivered. For example,\n``10**2`` returns ``100``, but ``10**-2`` returns ``0.01``.\n\nRaising ``0.0`` to a negative power results in a\n``ZeroDivisionError``. Raising a negative number to a fractional power\nresults in a ``complex`` number. (In earlier versions it raised a\n``ValueError``.)\n',
  'raise': '\nThe ``raise`` statement\n***********************\n\n   raise_stmt ::= "raise" [expression ["from" expression]]\n\nIf no expressions are present, ``raise`` re-raises the last exception\nthat was active in the current scope.  If no exception is active in\nthe current scope, a ``TypeError`` exception is raised indicating that\nthis is an error (if running under IDLE, a ``queue.Empty`` exception\nis raised instead).\n\nOtherwise, ``raise`` evaluates the first expression as the exception\nobject.  It must be either a subclass or an instance of\n``BaseException``. If it is a class, the exception instance will be\nobtained when needed by instantiating the class with no arguments.\n\nThe *type* of the exception is the exception instance\'s class, the\n*value* is the instance itself.\n\nA traceback object is normally created automatically when an exception\nis raised and attached to it as the ``__traceback__`` attribute, which\nis writable. You can create an exception and set your own traceback in\none step using the ``with_traceback()`` exception method (which\nreturns the same exception instance, with its traceback set to its\nargument), like so:\n\n   raise Exception("foo occurred").with_traceback(tracebackobj)\n\nThe ``from`` clause is used for exception chaining: if given, the\nsecond *expression* must be another exception class or instance, which\nwill then be attached to the raised exception as the ``__cause__``\nattribute (which is writable).  If the raised exception is not\nhandled, both exceptions will be printed:\n\n   >>> try:\n   ...     print(1 / 0)\n   ... except Exception as exc:\n   ...     raise RuntimeError("Something bad happened") from exc\n   ...\n   Traceback (most recent call last):\n     File "<stdin>", line 2, in <module>\n   ZeroDivisionError: int division or modulo by zero\n\n   The above exception was the direct cause of the following exception:\n\n   Traceback (most recent call last):\n     File "<stdin>", line 4, in <module>\n   RuntimeError: Something bad happened\n\nA similar mechanism works implicitly if an exception is raised inside\nan exception handler: the previous exception is then attached as the\nnew exception\'s ``__context__`` attribute:\n\n   >>> try:\n   ...     print(1 / 0)\n   ... except:\n   ...     raise RuntimeError("Something bad happened")\n   ...\n   Traceback (most recent call last):\n     File "<stdin>", line 2, in <module>\n   ZeroDivisionError: int division or modulo by zero\n\n   During handling of the above exception, another exception occurred:\n\n   Traceback (most recent call last):\n     File "<stdin>", line 4, in <module>\n   RuntimeError: Something bad happened\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information about handling exceptions is in section\n*The try statement*.\n',
@@ -59,18 +59,18 @@
  'shifting': '\nShifting operations\n*******************\n\nThe shifting operations have lower priority than the arithmetic\noperations:\n\n   shift_expr ::= a_expr | shift_expr ( "<<" | ">>" ) a_expr\n\nThese operators accept integers as arguments.  They shift the first\nargument to the left or right by the number of bits given by the\nsecond argument.\n\nA right shift by *n* bits is defined as division by ``pow(2,n)``.  A\nleft shift by *n* bits is defined as multiplication with ``pow(2,n)``.\n\nNote: In the current implementation, the right-hand operand is required to\n  be at most ``sys.maxsize``.  If the right-hand operand is larger\n  than ``sys.maxsize`` an ``OverflowError`` exception is raised.\n',
  'slicings': '\nSlicings\n********\n\nA slicing selects a range of items in a sequence object (e.g., a\nstring, tuple or list).  Slicings may be used as expressions or as\ntargets in assignment or ``del`` statements.  The syntax for a\nslicing:\n\n   slicing      ::= primary "[" slice_list "]"\n   slice_list   ::= slice_item ("," slice_item)* [","]\n   slice_item   ::= expression | proper_slice\n   proper_slice ::= [lower_bound] ":" [upper_bound] [ ":" [stride] ]\n   lower_bound  ::= expression\n   upper_bound  ::= expression\n   stride       ::= expression\n\nThere is ambiguity in the formal syntax here: anything that looks like\nan expression list also looks like a slice list, so any subscription\ncan be interpreted as a slicing.  Rather than further complicating the\nsyntax, this is disambiguated by defining that in this case the\ninterpretation as a subscription takes priority over the\ninterpretation as a slicing (this is the case if the slice list\ncontains no proper slice).\n\nThe semantics for a slicing are as follows.  The primary must evaluate\nto a mapping object, and it is indexed (using the same\n``__getitem__()`` method as normal subscription) with a key that is\nconstructed from the slice list, as follows.  If the slice list\ncontains at least one comma, the key is a tuple containing the\nconversion of the slice items; otherwise, the conversion of the lone\nslice item is the key.  The conversion of a slice item that is an\nexpression is that expression.  The conversion of a proper slice is a\nslice object (see section *The standard type hierarchy*) whose\n``start``, ``stop`` and ``step`` attributes are the values of the\nexpressions given as lower bound, upper bound and stride,\nrespectively, substituting ``None`` for missing expressions.\n',
  'specialattrs': "\nSpecial Attributes\n******************\n\nThe implementation adds a few special read-only attributes to several\nobject types, where they are relevant.  Some of these are not reported\nby the ``dir()`` built-in function.\n\nobject.__dict__\n\n   A dictionary or other mapping object used to store an object's\n   (writable) attributes.\n\ninstance.__class__\n\n   The class to which a class instance belongs.\n\nclass.__bases__\n\n   The tuple of base classes of a class object.\n\nclass.__name__\n\n   The name of the class or type.\n\nThe following attributes are only supported by *new-style class*es.\n\nclass.__mro__\n\n   This attribute is a tuple of classes that are considered when\n   looking for base classes during method resolution.\n\nclass.mro()\n\n   This method can be overridden by a metaclass to customize the\n   method resolution order for its instances.  It is called at class\n   instantiation, and its result is stored in ``__mro__``.\n\nclass.__subclasses__()\n\n   Each new-style class keeps a list of weak references to its\n   immediate subclasses.  This method returns a list of all those\n   references still alive. Example:\n\n      >>> int.__subclasses__()\n      [<type 'bool'>]\n\n-[ Footnotes ]-\n\n[1] Additional information on these special methods may be found in\n    the Python Reference Manual (*Basic customization*).\n\n[2] As a consequence, the list ``[1, 2]`` is considered equal to\n    ``[1.0, 2.0]``, and similarly for tuples.\n\n[3] They must have since the parser can't tell the type of the\n    operands.\n\n[4] To format only a tuple you should therefore provide a singleton\n    tuple whose only element is the tuple to be formatted.\n",
- 'specialnames': '\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators.  For instance, if a class defines\na method named ``__getitem__()``, and ``x`` is an instance of this\nclass, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x,\ni)``.  Except where mentioned, attempts to execute an operation raise\nan exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled.  For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense.  (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n   Called to create a new instance of class *cls*.  ``__new__()`` is a\n   static method (special-cased so you need not declare it as such)\n   that takes the class of which an instance was requested as its\n   first argument.  The remaining arguments are those passed to the\n   object constructor expression (the call to the class).  The return\n   value of ``__new__()`` should be the new object instance (usually\n   an instance of *cls*).\n\n   Typical implementations create a new instance of the class by\n   invoking the superclass\'s ``__new__()`` method using\n   ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n   arguments and then modifying the newly-created instance as\n   necessary before returning it.\n\n   If ``__new__()`` returns an instance of *cls*, then the new\n   instance\'s ``__init__()`` method will be invoked like\n   ``__init__(self[, ...])``, where *self* is the new instance and the\n   remaining arguments are the same as were passed to ``__new__()``.\n\n   If ``__new__()`` does not return an instance of *cls*, then the new\n   instance\'s ``__init__()`` method will not be invoked.\n\n   ``__new__()`` is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called when the instance is created.  The arguments are those\n   passed to the class constructor expression.  If a base class has an\n   ``__init__()`` method, the derived class\'s ``__init__()`` method,\n   if any, must explicitly call it to ensure proper initialization of\n   the base class part of the instance; for example:\n   ``BaseClass.__init__(self, [args...])``.  As a special constraint\n   on constructors, no value may be returned; doing so will cause a\n   ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n   Called when the instance is about to be destroyed.  This is also\n   called a destructor.  If a base class has a ``__del__()`` method,\n   the derived class\'s ``__del__()`` method, if any, must explicitly\n   call it to ensure proper deletion of the base class part of the\n   instance.  Note that it is possible (though not recommended!) for\n   the ``__del__()`` method to postpone destruction of the instance by\n   creating a new reference to it.  It may then be called at a later\n   time when this new reference is deleted.  It is not guaranteed that\n   ``__del__()`` methods are called for objects that still exist when\n   the interpreter exits.\n\n   Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n     decrements the reference count for ``x`` by one, and the latter\n     is only called when ``x``\'s reference count reaches zero.  Some\n     common situations that may prevent the reference count of an\n     object from going to zero include: circular references between\n     objects (e.g., a doubly-linked list or a tree data structure with\n     parent and child pointers); a reference to the object on the\n     stack frame of a function that caught an exception (the traceback\n     stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n     a reference to the object on the stack frame that raised an\n     unhandled exception in interactive mode (the traceback stored in\n     ``sys.last_traceback`` keeps the stack frame alive).  The first\n     situation can only be remedied by explicitly breaking the cycles;\n     the latter two situations can be resolved by storing ``None`` in\n     ``sys.last_traceback``. Circular references which are garbage are\n     detected when the option cycle detector is enabled (it\'s on by\n     default), but can only be cleaned up if there are no Python-\n     level ``__del__()`` methods involved. Refer to the documentation\n     for the ``gc`` module for more information about how\n     ``__del__()`` methods are handled by the cycle detector,\n     particularly the description of the ``garbage`` value.\n\n   Warning: Due to the precarious circumstances under which ``__del__()``\n     methods are invoked, exceptions that occur during their execution\n     are ignored, and a warning is printed to ``sys.stderr`` instead.\n     Also, when ``__del__()`` is invoked in response to a module being\n     deleted (e.g., when execution of the program is done), other\n     globals referenced by the ``__del__()`` method may already have\n     been deleted or in the process of being torn down (e.g. the\n     import machinery shutting down).  For this reason, ``__del__()``\n     methods should do the absolute minimum needed to maintain\n     external invariants.  Starting with version 1.5, Python\n     guarantees that globals whose name begins with a single\n     underscore are deleted from their module before other globals are\n     deleted; if no other references to such globals exist, this may\n     help in assuring that imported modules are still available at the\n     time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n   Called by the ``repr()`` built-in function to compute the\n   "official" string representation of an object.  If at all possible,\n   this should look like a valid Python expression that could be used\n   to recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   ``<...some useful description...>`` should be returned. The return\n   value must be a string object. If a class defines ``__repr__()``\n   but not ``__str__()``, then ``__repr__()`` is also used when an\n   "informal" string representation of instances of that class is\n   required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by the ``str()`` built-in function and by the ``print()``\n   function to compute the "informal" string representation of an\n   object.  This differs from ``__repr__()`` in that it does not have\n   to be a valid Python expression: a more convenient or concise\n   representation may be used instead. The return value must be a\n   string object.\n\nobject.__format__(self, format_spec)\n\n   Called by the ``format()`` built-in function (and by extension, the\n   ``format()`` method of class ``str``) to produce a "formatted"\n   string representation of an object. The ``format_spec`` argument is\n   a string that contains a description of the formatting options\n   desired. The interpretation of the ``format_spec`` argument is up\n   to the type implementing ``__format__()``, however most classes\n   will either delegate formatting to one of the built-in types, or\n   use a similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\n   ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\n   ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n   ``x.__ge__(y)``.\n\n   A rich comparison method may return the singleton\n   ``NotImplemented`` if it does not implement the operation for a\n   given pair of arguments. By convention, ``False`` and ``True`` are\n   returned for a successful comparison. However, these methods can\n   return any value, so if the comparison operator is used in a\n   Boolean context (e.g., in the condition of an ``if`` statement),\n   Python will call ``bool()`` on the value to determine if the result\n   is true or false.\n\n   There are no implied relationships among the comparison operators.\n   The truth of ``x==y`` does not imply that ``x!=y`` is false.\n   Accordingly, when defining ``__eq__()``, one should also define\n   ``__ne__()`` so that the operators will behave as expected.  See\n   the paragraph on ``__hash__()`` for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\n\n   There are no swapped-argument versions of these methods (to be used\n   when the left argument does not support the operation but the right\n   argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n   other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n   reflection, and ``__eq__()`` and ``__ne__()`` are their own\n   reflection.\n\n   Arguments to rich comparison methods are never coerced.\n\n   To automatically generate ordering operations from a single root\n   operation, see ``functools.total_ordering()``.\n\nobject.__hash__(self)\n\n   Called by built-in function ``hash()`` and for operations on\n   members of hashed collections including ``set``, ``frozenset``, and\n   ``dict``.  ``__hash__()`` should return an integer.  The only\n   required property is that objects which compare equal have the same\n   hash value; it is advised to somehow mix together (e.g. using\n   exclusive or) the hash values for the components of the object that\n   also play a part in comparison of objects.\n\n   If a class does not define an ``__eq__()`` method it should not\n   define a ``__hash__()`` operation either; if it defines\n   ``__eq__()`` but not ``__hash__()``, its instances will not be\n   usable as items in hashable collections.  If a class defines\n   mutable objects and implements an ``__eq__()`` method, it should\n   not implement ``__hash__()``, since the implementation of hashable\n   collections requires that a key\'s hash value is immutable (if the\n   object\'s hash value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n   by default; with them, all objects compare unequal (except with\n   themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n   Classes which inherit a ``__hash__()`` method from a parent class\n   but change the meaning of ``__eq__()`` such that the hash value\n   returned is no longer appropriate (e.g. by switching to a value-\n   based concept of equality instead of the default identity based\n   equality) can explicitly flag themselves as being unhashable by\n   setting ``__hash__ = None`` in the class definition. Doing so means\n   that not only will instances of the class raise an appropriate\n   ``TypeError`` when a program attempts to retrieve their hash value,\n   but they will also be correctly identified as unhashable when\n   checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n   which define their own ``__hash__()`` to explicitly raise\n   ``TypeError``).\n\n   If a class that overrides ``__eq__()`` needs to retain the\n   implementation of ``__hash__()`` from a parent class, the\n   interpreter must be told this explicitly by setting ``__hash__ =\n   <ParentClass>.__hash__``. Otherwise the inheritance of\n   ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n   explicitly set to ``None``.\n\nobject.__bool__(self)\n\n   Called to implement truth value testing and the built-in operation\n   ``bool()``; should return ``False`` or ``True``.  When this method\n   is not defined, ``__len__()`` is called, if it is defined, and the\n   object is considered true if its result is nonzero.  If a class\n   defines neither ``__len__()`` nor ``__bool__()``, all its instances\n   are considered true.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n   Called when an attribute lookup has not found the attribute in the\n   usual places (i.e. it is not an instance attribute nor is it found\n   in the class tree for ``self``).  ``name`` is the attribute name.\n   This method should return the (computed) attribute value or raise\n   an ``AttributeError`` exception.\n\n   Note that if the attribute is found through the normal mechanism,\n   ``__getattr__()`` is not called.  (This is an intentional asymmetry\n   between ``__getattr__()`` and ``__setattr__()``.) This is done both\n   for efficiency reasons and because otherwise ``__getattr__()``\n   would have no way to access other attributes of the instance.  Note\n   that at least for instance variables, you can fake total control by\n   not inserting any values in the instance attribute dictionary (but\n   instead inserting them in another object).  See the\n   ``__getattribute__()`` method below for a way to actually get total\n   control over attribute access.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines\n   ``__getattr__()``, the latter will not be called unless\n   ``__getattribute__()`` either calls it explicitly or raises an\n   ``AttributeError``. This method should return the (computed)\n   attribute value or raise an ``AttributeError`` exception. In order\n   to avoid infinite recursion in this method, its implementation\n   should always call the base class method with the same name to\n   access any attributes it needs, for example,\n   ``object.__getattribute__(self, name)``.\n\n   Note: This method may still be bypassed when looking up special methods\n     as the result of implicit invocation via language syntax or\n     built-in functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n   Called when an attribute assignment is attempted.  This is called\n   instead of the normal mechanism (i.e. store the value in the\n   instance dictionary). *name* is the attribute name, *value* is the\n   value to be assigned to it.\n\n   If ``__setattr__()`` wants to assign to an instance attribute, it\n   should call the base class method with the same name, for example,\n   ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n   Like ``__setattr__()`` but for attribute deletion instead of\n   assignment.  This should only be implemented if ``del obj.name`` is\n   meaningful for the object.\n\nobject.__dir__(self)\n\n   Called when ``dir()`` is called on the object.  A list must be\n   returned.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class.  In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n   Called to get the attribute of the owner class (class attribute\n   access) or of an instance of that class (instance attribute\n   access). *owner* is always the owner class, while *instance* is the\n   instance that the attribute was accessed through, or ``None`` when\n   the attribute is accessed through the *owner*.  This method should\n   return the (computed) attribute value or raise an\n   ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n   Called to set the attribute on an instance *instance* of the owner\n   class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n   Called to delete the attribute on an instance *instance* of the\n   owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol:  ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead.  Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n   The simplest and least common call is when user code directly\n   invokes a descriptor method:    ``x.__get__(a)``.\n\nInstance Binding\n   If binding to an object instance, ``a.x`` is transformed into the\n   call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n   If binding to a class, ``A.x`` is transformed into the call:\n   ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n   If ``a`` is an instance of ``super``, then the binding ``super(B,\n   obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n   ``A`` immediately preceding ``B`` and then invokes the descriptor\n   with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined.  A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary.  If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor.  Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method.  Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary.  In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors.  Accordingly, instances can\nredefine and override methods.  This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of classes have a dictionary for attribute\nstorage.  This wastes space for objects having very few instance\nvariables.  The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable.  Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n   This class variable can be assigned a string, iterable, or sequence\n   of strings with variable names used by instances.  If defined in a\n   class, *__slots__* reserves space for the declared variables and\n   prevents the automatic creation of *__dict__* and *__weakref__* for\n   each instance.\n\n\nNotes on using *__slots__*\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n  attribute of that class will always be accessible, so a *__slots__*\n  definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n  variables not listed in the *__slots__* definition.  Attempts to\n  assign to an unlisted variable name raises ``AttributeError``. If\n  dynamic assignment of new variables is desired, then add\n  ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n  declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n  *__slots__* do not support weak references to its instances. If weak\n  reference support is needed, then add ``\'__weakref__\'`` to the\n  sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (*Implementing Descriptors*) for each variable name.  As\n  a result, class attributes cannot be used to set default values for\n  instance variables defined by *__slots__*; otherwise, the class\n  attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n  where it is defined.  As a result, subclasses will have a *__dict__*\n  unless they also define *__slots__* (which must only contain names\n  of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the instance\n  variable defined by the base class slot is inaccessible (except by\n  retrieving its descriptor directly from the base class). This\n  renders the meaning of the program undefined.  In the future, a\n  check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n  "variable-length" built-in types such as ``int``, ``str`` and\n  ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n  also be used; however, in the future, special meaning may be\n  assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n  *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, classes are constructed using ``type()``. A class\ndefinition is read into a separate namespace and the value of class\nname is bound to the result of ``type(name, bases, dict)``.\n\nWhen the class definition is read, if a callable ``metaclass`` keyword\nargument is passed after the bases in the class definition, the\ncallable given will be called instead of ``type()``.  If other keyword\narguments are passed, they will also be passed to the metaclass.  This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing the\n  role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties.  This example adds a new\nelement to the class dictionary before creating the class:\n\n   class metacls(type):\n       def __new__(mcs, name, bases, dict):\n           dict[\'foo\'] = \'metacls was here\'\n           return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\nIf the metaclass has a ``__prepare__()`` attribute (usually\nimplemented as a class or static method), it is called before the\nclass body is evaluated with the name of the class and a tuple of its\nbases for arguments.  It should return an object that supports the\nmapping interface that will be used to store the namespace of the\nclass.  The default is a plain dictionary.  This could be used, for\nexample, to keep track of the order that class attributes are declared\nin by returning an ordered dictionary.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If the ``metaclass`` keyword argument is passed with the bases, it\n  is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n  used.\n\n* Otherwise, the default metaclass (``type``) is used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\nHere is an example of a metaclass that uses an\n``collections.OrderedDict`` to remember the order that class members\nwere defined:\n\n   class OrderedClass(type):\n\n        @classmethod\n        def __prepare__(metacls, name, bases, **kwds):\n           return collections.OrderedDict()\n\n        def __new__(cls, name, bases, classdict):\n           result = type.__new__(cls, name, bases, dict(classdict))\n           result.members = tuple(classdict)\n           return result\n\n   class A(metaclass=OrderedClass):\n       def one(self): pass\n       def two(self): pass\n       def three(self): pass\n       def four(self): pass\n\n   >>> A.members\n   (\'__module__\', \'one\', \'two\', \'three\', \'four\')\n\nWhen the class definition for *A* gets executed, the process begins\nwith calling the metaclass\'s ``__prepare__()`` method which returns an\nempty ``collections.OrderedDict``.  That mapping records the methods\nand attributes of *A* as they are defined within the body of the class\nstatement. Once those definitions are executed, the ordered dictionary\nis fully populated and the metaclass\'s ``__new__()`` method gets\ninvoked.  That method builds the new type and it saves the ordered\ndictionary keys in an attribute called *members*.\n\n\nCustomizing instance and subclass checks\n========================================\n\nThe following methods are used to override the default behavior of the\n``isinstance()`` and ``issubclass()`` built-in functions.\n\nIn particular, the metaclass ``abc.ABCMeta`` implements these methods\nin order to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\n   Return true if *instance* should be considered a (direct or\n   indirect) instance of *class*. If defined, called to implement\n   ``isinstance(instance, class)``.\n\nclass.__subclasscheck__(self, subclass)\n\n   Return true if *subclass* should be considered a (direct or\n   indirect) subclass of *class*.  If defined, called to implement\n   ``issubclass(subclass, class)``.\n\nNote that these methods are looked up on the type (metaclass) of a\nclass.  They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also:\n\n   **PEP 3119** - Introducing Abstract Base Classes\n      Includes the specification for customizing ``isinstance()`` and\n      ``issubclass()`` behavior through ``__instancecheck__()`` and\n      ``__subclasscheck__()``, with motivation for this functionality\n      in the context of adding Abstract Base Classes (see the ``abc``\n      module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n   Called when the instance is "called" as a function; if this method\n   is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n   ``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well.  The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items.  It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python\'s standard\ndictionary objects.  The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects.  Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators.  It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping\'s keys; for\nsequences, it should search through the values.  It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n   Called to implement the built-in function ``len()``.  Should return\n   the length of the object, an integer ``>=`` 0.  Also, an object\n   that doesn\'t define a ``__bool__()`` method and whose ``__len__()``\n   method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods.  A\n  call like\n\n     a[1:2] = b\n\n  is translated to\n\n     a[slice(1, 2, None)] = b\n\n  and so forth.  Missing slice items are always filled in with\n  ``None``.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of ``self[key]``. For sequence\n   types, the accepted keys should be integers and slice objects.\n   Note that the special interpretation of negative indexes (if the\n   class wishes to emulate a sequence type) is up to the\n   ``__getitem__()`` method. If *key* is of an inappropriate type,\n   ``TypeError`` may be raised; if of a value outside the set of\n   indexes for the sequence (after any special interpretation of\n   negative values), ``IndexError`` should be raised. For mapping\n   types, if *key* is missing (not in the container), ``KeyError``\n   should be raised.\n\n   Note: ``for`` loops expect that an ``IndexError`` will be raised for\n     illegal indexes to allow proper detection of the end of the\n     sequence.\n\nobject.__setitem__(self, key, value)\n\n   Called to implement assignment to ``self[key]``.  Same note as for\n   ``__getitem__()``.  This should only be implemented for mappings if\n   the objects support changes to the values for keys, or if new keys\n   can be added, or for sequences if elements can be replaced.  The\n   same exceptions should be raised for improper *key* values as for\n   the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n   Called to implement deletion of ``self[key]``.  Same note as for\n   ``__getitem__()``.  This should only be implemented for mappings if\n   the objects support removal of keys, or for sequences if elements\n   can be removed from the sequence.  The same exceptions should be\n   raised for improper *key* values as for the ``__getitem__()``\n   method.\n\nobject.__iter__(self)\n\n   This method is called when an iterator is required for a container.\n   This method should return a new iterator object that can iterate\n   over all the objects in the container.  For mappings, it should\n   iterate over the keys of the container, and should also be made\n   available as the method ``keys()``.\n\n   Iterator objects also need to implement this method; they are\n   required to return themselves.  For more information on iterator\n   objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n   Called (if present) by the ``reversed()`` built-in to implement\n   reverse iteration.  It should return a new iterator object that\n   iterates over all the objects in the container in reverse order.\n\n   If the ``__reversed__()`` method is not provided, the\n   ``reversed()`` built-in will fall back to using the sequence\n   protocol (``__len__()`` and ``__getitem__()``).  Objects that\n   support the sequence protocol should only provide\n   ``__reversed__()`` if they can provide an implementation that is\n   more efficient than the one provided by ``reversed()``.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence.  However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n   Called to implement membership test operators.  Should return true\n   if *item* is in *self*, false otherwise.  For mapping objects, this\n   should consider the keys of the mapping rather than the values or\n   the key-item pairs.\n\n   For objects that don\'t define ``__contains__()``, the membership\n   test first tries iteration via ``__iter__()``, then the old\n   sequence iteration protocol via ``__getitem__()``, see *this\n   section in the language reference*.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``).  For instance, to evaluate the expression ``x + y``, where\n   *x* is an instance of a class that has an ``__add__()`` method,\n   ``x.__add__(y)`` is called.  The ``__divmod__()`` method should be\n   the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n   should not be related to ``__truediv__()``.  Note that\n   ``__pow__()`` should be defined to accept an optional third\n   argument if the ternary version of the built-in ``pow()`` function\n   is to be supported.\n\n   If one of those methods does not support the operation with the\n   supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``) with reflected (swapped) operands. These functions are only\n   called if the left operand does not support the corresponding\n   operation and the operands are of different types. [2]  For\n   instance, to evaluate the expression ``x - y``, where *y* is an\n   instance of a class that has an ``__rsub__()`` method,\n   ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n   *NotImplemented*.\n\n   Note that ternary ``pow()`` will not try calling ``__rpow__()``\n   (the coercion rules would become too complicated).\n\n   Note: If the right operand\'s type is a subclass of the left operand\'s\n     type and that subclass provides the reflected method for the\n     operation, this method will be called before the left operand\'s\n     non-reflected method.  This behavior allows subclasses to\n     override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n   These methods are called to implement the augmented arithmetic\n   assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n   ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``).  These methods\n   should attempt to do the operation in-place (modifying *self*) and\n   return the result (which could be, but does not have to be,\n   *self*).  If a specific method is not defined, the augmented\n   assignment falls back to the normal methods.  For instance, to\n   execute the statement ``x += y``, where *x* is an instance of a\n   class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n   called.  If *x* is an instance of a class that does not define a\n   ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n   considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n   Called to implement the unary arithmetic operations (``-``, ``+``,\n   ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n   Called to implement the built-in functions ``complex()``,\n   ``int()``, ``float()`` and ``round()``.  Should return a value of\n   the appropriate type.\n\nobject.__index__(self)\n\n   Called to implement ``operator.index()``.  Also called whenever\n   Python needs an integer object (such as in slicing, or in the\n   built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n   an integer.\n\n\nWith Statement Context Managers\n===============================\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code.  Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n   Enter the runtime context related to this object. The ``with``\n   statement will bind this method\'s return value to the target(s)\n   specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n   Exit the runtime context related to this object. The parameters\n   describe the exception that caused the context to be exited. If the\n   context was exited without an exception, all three arguments will\n   be ``None``.\n\n   If an exception is supplied, and the method wishes to suppress the\n   exception (i.e., prevent it from being propagated), it should\n   return a true value. Otherwise, the exception will be processed\n   normally upon exit from this method.\n\n   Note that ``__exit__()`` methods should not reraise the passed-in\n   exception; this is the caller\'s responsibility.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n\n\nSpecial method lookup\n=====================\n\nFor custom classes, implicit invocations of special methods are only\nguaranteed to work correctly if defined on an object\'s type, not in\nthe object\'s instance dictionary.  That behaviour is the reason why\nthe following code raises an exception:\n\n   >>> class C(object):\n   ...     pass\n   ...\n   >>> c = C()\n   >>> c.__len__ = lambda: 5\n   >>> len(c)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n   >>> 1 .__hash__() == hash(1)\n   True\n   >>> int.__hash__() == hash(int)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n   >>> type(1).__hash__(1) == hash(1)\n   True\n   >>> type(int).__hash__(int) == hash(int)\n   True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe ``__getattribute__()`` method even of the object\'s metaclass:\n\n   >>> class Meta(type):\n   ...    def __getattribute__(*args):\n   ...       print("Metaclass getattribute invoked")\n   ...       return type.__getattribute__(*args)\n   ...\n   >>> class C(object, metaclass=Meta):\n   ...     def __len__(self):\n   ...         return 10\n   ...     def __getattribute__(*args):\n   ...         print("Class getattribute invoked")\n   ...         return object.__getattribute__(*args)\n   ...\n   >>> c = C()\n   >>> c.__len__()                 # Explicit lookup via instance\n   Class getattribute invoked\n   10\n   >>> type(c).__len__(c)          # Explicit lookup via type\n   Metaclass getattribute invoked\n   10\n   >>> len(c)                      # Implicit lookup\n   10\n\nBypassing the ``__getattribute__()`` machinery in this fashion\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n    certain controlled conditions. It generally isn\'t a good idea\n    though, since it can lead to some very strange behaviour if it is\n    handled incorrectly.\n\n[2] For operands of the same type, it is assumed that if the non-\n    reflected method (such as ``__add__()``) fails the operation is\n    not supported, which is why the reflected method is not called.\n',
- 'string-methods': '\nString Methods\n**************\n\nString objects support the methods listed below.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, bytes, bytearray, list,\ntuple, range* section. To output formatted strings, see the *String\nFormatting* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n   Return a copy of the string with its first character capitalized\n   and the rest lowercased.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\n   Return the number of non-overlapping occurrences of substring *sub*\n   in the range [*start*, *end*].  Optional arguments *start* and\n   *end* are interpreted as in slice notation.\n\nstr.encode(encoding=sys.getdefaultencoding(), errors="strict")\n\n   Return an encoded version of the string as a bytes object.  Default\n   encoding is the current default string encoding.  *errors* may be\n   given to set a different error handling scheme.  The default for\n   *errors* is ``\'strict\'``, meaning that encoding errors raise a\n   ``UnicodeError``.  Other possible values are ``\'ignore\'``,\n   ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n   any other name registered via ``codecs.register_error()``, see\n   section *Codec Base Classes*. For a list of possible encodings, see\n   section *Standard Encodings*.\n\n   Changed in version 3.1: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return ``True`` if the string ends with the specified *suffix*,\n   otherwise return ``False``.  *suffix* can also be a tuple of\n   suffixes to look for.  With optional *start*, test beginning at\n   that position.  With optional *end*, stop comparing at that\n   position.\n\nstr.expandtabs([tabsize])\n\n   Return a copy of the string where all tab characters are replaced\n   by one or more spaces, depending on the current column and the\n   given tab size.  The column number is reset to zero after each\n   newline occurring in the string. If *tabsize* is not given, a tab\n   size of ``8`` characters is assumed.  This doesn\'t understand other\n   non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n   Return the lowest index in the string where substring *sub* is\n   found, such that *sub* is contained in the slice ``s[start:end]``.\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The string on which this\n   method is called can contain literal text or replacement fields\n   delimited by braces ``{}``.  Each replacement field contains either\n   the numeric index of a positional argument, or the name of a\n   keyword argument.  Returns a copy of the string where each\n   replacement field is replaced with the string value of the\n   corresponding argument.\n\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\n   \'The sum of 1 + 2 is 3\'\n\n   See *Format String Syntax* for a description of the various\n   formatting options that can be specified in format strings.\n\nstr.index(sub[, start[, end]])\n\n   Like ``find()``, but raise ``ValueError`` when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters include digit characters, and all characters that that\n   can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-\n   INDIC DIGIT ZERO.\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n   Return true if all cased characters in the string are lowercase and\n   there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when ``repr()`` is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.isspace()\n\n   Return true if there are only whitespace characters in the string\n   and there is at least one character, false otherwise.\n\nstr.istitle()\n\n   Return true if the string is a titlecased string and there is at\n   least one character, for example uppercase characters may only\n   follow uncased characters and lowercase characters only cased ones.\n   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters in the string are uppercase and\n   there is at least one cased character, false otherwise.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  A ``TypeError`` will be raised if there are\n   any non-string values in *seq*, including ``bytes`` objects.  The\n   separator between elements is the string providing this method.\n\nstr.ljust(width[, fillchar])\n\n   Return the string left justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is a\n   space).  The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.lower()\n\n   Return a copy of the string converted to lowercase.\n\nstr.lstrip([chars])\n\n   Return a copy of the string with leading characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or ``None``, the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.lstrip()\n   \'spacious   \'\n   >>> \'www.example.com\'.lstrip(\'cmowz.\')\n   \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   ``str.translate()``.\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or None.\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   None in the result.\n\nstr.partition(sep)\n\n   Split the string at the first occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\n\n   Return a copy of the string with all occurrences of substring *old*\n   replaced by *new*.  If the optional argument *count* is given, only\n   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n   Return the highest index in the string where substring *sub* is\n   found, such that *sub* is contained within ``s[start:end]``.\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n   is not found.\n\nstr.rjust(width[, fillchar])\n\n   Return the string right justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is a\n   space). The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.rpartition(sep)\n\n   Split the string at the last occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.rsplit([sep[, maxsplit]])\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n   are done, the *rightmost* ones.  If *sep* is not specified or\n   ``None``, any whitespace string is a separator.  Except for\n   splitting from the right, ``rsplit()`` behaves like ``split()``\n   which is described in detail below.\n\nstr.rstrip([chars])\n\n   Return a copy of the string with trailing characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or ``None``, the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.rstrip()\n   \'   spacious\'\n   >>> \'mississippi\'.rstrip(\'ipz\')\n   \'mississ\'\n\nstr.split([sep[, maxsplit]])\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string.  If *maxsplit* is given, at most *maxsplit*\n   splits are done (thus, the list will have at most ``maxsplit+1``\n   elements).  If *maxsplit* is not specified, then there is no limit\n   on the number of splits (all possible splits are made).\n\n   If *sep* is given, consecutive delimiters are not grouped together\n   and are deemed to delimit empty strings (for example,\n   ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``).  The *sep*\n   argument may consist of multiple characters (for example,\n   ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n   an empty string with a specified separator returns ``[\'\']``.\n\n   If *sep* is not specified or is ``None``, a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no empty strings\n   at the start or end if the string has leading or trailing\n   whitespace.  Consequently, splitting an empty string or a string\n   consisting of just whitespace with a ``None`` separator returns\n   ``[]``.\n\n   For example, ``\' 1  2   3  \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n   and ``\'  1  2   3  \'.split(None, 1)`` returns ``[\'1\', \'2   3  \']``.\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return ``True`` if string starts with the *prefix*, otherwise\n   return ``False``. *prefix* can also be a tuple of prefixes to look\n   for.  With optional *start*, test string beginning at that\n   position.  With optional *end*, stop comparing string at that\n   position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or ``None``, the\n   *chars* argument defaults to removing whitespace. The *chars*\n   argument is not a prefix or suffix; rather, all combinations of its\n   values are stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\nstr.title()\n\n   Return a titlecased version of the string where words start with an\n   uppercase character and the remaining characters are lowercase.\n\n   The algorithm uses a simple language-independent definition of a\n   word as groups of consecutive letters.  The definition works in\n   many contexts but it means that apostrophes in contractions and\n   possessives form word boundaries, which may not be the desired\n   result:\n\n      >>> "they\'re bill\'s friends from the UK".title()\n      "They\'Re Bill\'S Friends From The Uk"\n\n   A workaround for apostrophes can be constructed using regular\n   expressions:\n\n      >>> import re\n      >>> def titlecase(s):\n              return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n                            lambda mo: mo.group(0)[0].upper() +\n                                       mo.group(0)[1:].lower(),\n                            s)\n\n      >>> titlecase("they\'re bill\'s friends.")\n      "They\'re Bill\'s Friends."\n\nstr.translate(map)\n\n   Return a copy of the *s* where all characters have been mapped\n   through the *map* which must be a dictionary of Unicode ordinals\n   (integers) to Unicode ordinals, strings or ``None``.  Unmapped\n   characters are left untouched. Characters mapped to ``None`` are\n   deleted.\n\n   You can use ``str.maketrans()`` to create a translation map from\n   character-to-character mappings in different formats.\n\n   Note: An even more flexible approach is to create a custom character\n     mapping codec using the ``codecs`` module (see\n     ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n   Return a copy of the string converted to uppercase.\n\nstr.zfill(width)\n\n   Return the numeric string left filled with zeros in a string of\n   length *width*.  A sign prefix is handled correctly.  The original\n   string is returned if *width* is less than ``len(s)``.\n',
+ 'specialnames': '\nSpecial method names\n********************\n\nA class can implement certain operations that are invoked by special\nsyntax (such as arithmetic operations or subscripting and slicing) by\ndefining methods with special names. This is Python\'s approach to\n*operator overloading*, allowing classes to define their own behavior\nwith respect to language operators.  For instance, if a class defines\na method named ``__getitem__()``, and ``x`` is an instance of this\nclass, then ``x[i]`` is roughly equivalent to ``type(x).__getitem__(x,\ni)``.  Except where mentioned, attempts to execute an operation raise\nan exception when no appropriate method is defined (typically\n``AttributeError`` or ``TypeError``).\n\nWhen implementing a class that emulates any built-in type, it is\nimportant that the emulation only be implemented to the degree that it\nmakes sense for the object being modelled.  For example, some\nsequences may work well with retrieval of individual elements, but\nextracting a slice may not make sense.  (One example of this is the\n``NodeList`` interface in the W3C\'s Document Object Model.)\n\n\nBasic customization\n===================\n\nobject.__new__(cls[, ...])\n\n   Called to create a new instance of class *cls*.  ``__new__()`` is a\n   static method (special-cased so you need not declare it as such)\n   that takes the class of which an instance was requested as its\n   first argument.  The remaining arguments are those passed to the\n   object constructor expression (the call to the class).  The return\n   value of ``__new__()`` should be the new object instance (usually\n   an instance of *cls*).\n\n   Typical implementations create a new instance of the class by\n   invoking the superclass\'s ``__new__()`` method using\n   ``super(currentclass, cls).__new__(cls[, ...])`` with appropriate\n   arguments and then modifying the newly-created instance as\n   necessary before returning it.\n\n   If ``__new__()`` returns an instance of *cls*, then the new\n   instance\'s ``__init__()`` method will be invoked like\n   ``__init__(self[, ...])``, where *self* is the new instance and the\n   remaining arguments are the same as were passed to ``__new__()``.\n\n   If ``__new__()`` does not return an instance of *cls*, then the new\n   instance\'s ``__init__()`` method will not be invoked.\n\n   ``__new__()`` is intended mainly to allow subclasses of immutable\n   types (like int, str, or tuple) to customize instance creation.  It\n   is also commonly overridden in custom metaclasses in order to\n   customize class creation.\n\nobject.__init__(self[, ...])\n\n   Called when the instance is created.  The arguments are those\n   passed to the class constructor expression.  If a base class has an\n   ``__init__()`` method, the derived class\'s ``__init__()`` method,\n   if any, must explicitly call it to ensure proper initialization of\n   the base class part of the instance; for example:\n   ``BaseClass.__init__(self, [args...])``.  As a special constraint\n   on constructors, no value may be returned; doing so will cause a\n   ``TypeError`` to be raised at runtime.\n\nobject.__del__(self)\n\n   Called when the instance is about to be destroyed.  This is also\n   called a destructor.  If a base class has a ``__del__()`` method,\n   the derived class\'s ``__del__()`` method, if any, must explicitly\n   call it to ensure proper deletion of the base class part of the\n   instance.  Note that it is possible (though not recommended!) for\n   the ``__del__()`` method to postpone destruction of the instance by\n   creating a new reference to it.  It may then be called at a later\n   time when this new reference is deleted.  It is not guaranteed that\n   ``__del__()`` methods are called for objects that still exist when\n   the interpreter exits.\n\n   Note: ``del x`` doesn\'t directly call ``x.__del__()`` --- the former\n     decrements the reference count for ``x`` by one, and the latter\n     is only called when ``x``\'s reference count reaches zero.  Some\n     common situations that may prevent the reference count of an\n     object from going to zero include: circular references between\n     objects (e.g., a doubly-linked list or a tree data structure with\n     parent and child pointers); a reference to the object on the\n     stack frame of a function that caught an exception (the traceback\n     stored in ``sys.exc_info()[2]`` keeps the stack frame alive); or\n     a reference to the object on the stack frame that raised an\n     unhandled exception in interactive mode (the traceback stored in\n     ``sys.last_traceback`` keeps the stack frame alive).  The first\n     situation can only be remedied by explicitly breaking the cycles;\n     the latter two situations can be resolved by storing ``None`` in\n     ``sys.last_traceback``. Circular references which are garbage are\n     detected when the option cycle detector is enabled (it\'s on by\n     default), but can only be cleaned up if there are no Python-\n     level ``__del__()`` methods involved. Refer to the documentation\n     for the ``gc`` module for more information about how\n     ``__del__()`` methods are handled by the cycle detector,\n     particularly the description of the ``garbage`` value.\n\n   Warning: Due to the precarious circumstances under which ``__del__()``\n     methods are invoked, exceptions that occur during their execution\n     are ignored, and a warning is printed to ``sys.stderr`` instead.\n     Also, when ``__del__()`` is invoked in response to a module being\n     deleted (e.g., when execution of the program is done), other\n     globals referenced by the ``__del__()`` method may already have\n     been deleted or in the process of being torn down (e.g. the\n     import machinery shutting down).  For this reason, ``__del__()``\n     methods should do the absolute minimum needed to maintain\n     external invariants.  Starting with version 1.5, Python\n     guarantees that globals whose name begins with a single\n     underscore are deleted from their module before other globals are\n     deleted; if no other references to such globals exist, this may\n     help in assuring that imported modules are still available at the\n     time when the ``__del__()`` method is called.\n\nobject.__repr__(self)\n\n   Called by the ``repr()`` built-in function to compute the\n   "official" string representation of an object.  If at all possible,\n   this should look like a valid Python expression that could be used\n   to recreate an object with the same value (given an appropriate\n   environment).  If this is not possible, a string of the form\n   ``<...some useful description...>`` should be returned. The return\n   value must be a string object. If a class defines ``__repr__()``\n   but not ``__str__()``, then ``__repr__()`` is also used when an\n   "informal" string representation of instances of that class is\n   required.\n\n   This is typically used for debugging, so it is important that the\n   representation is information-rich and unambiguous.\n\nobject.__str__(self)\n\n   Called by the ``str()`` built-in function and by the ``print()``\n   function to compute the "informal" string representation of an\n   object.  This differs from ``__repr__()`` in that it does not have\n   to be a valid Python expression: a more convenient or concise\n   representation may be used instead. The return value must be a\n   string object.\n\nobject.__format__(self, format_spec)\n\n   Called by the ``format()`` built-in function (and by extension, the\n   ``format()`` method of class ``str``) to produce a "formatted"\n   string representation of an object. The ``format_spec`` argument is\n   a string that contains a description of the formatting options\n   desired. The interpretation of the ``format_spec`` argument is up\n   to the type implementing ``__format__()``, however most classes\n   will either delegate formatting to one of the built-in types, or\n   use a similar formatting option syntax.\n\n   See *Format Specification Mini-Language* for a description of the\n   standard formatting syntax.\n\n   The return value must be a string object.\n\nobject.__lt__(self, other)\nobject.__le__(self, other)\nobject.__eq__(self, other)\nobject.__ne__(self, other)\nobject.__gt__(self, other)\nobject.__ge__(self, other)\n\n   These are the so-called "rich comparison" methods. The\n   correspondence between operator symbols and method names is as\n   follows: ``x<y`` calls ``x.__lt__(y)``, ``x<=y`` calls\n   ``x.__le__(y)``, ``x==y`` calls ``x.__eq__(y)``, ``x!=y`` calls\n   ``x.__ne__(y)``, ``x>y`` calls ``x.__gt__(y)``, and ``x>=y`` calls\n   ``x.__ge__(y)``.\n\n   A rich comparison method may return the singleton\n   ``NotImplemented`` if it does not implement the operation for a\n   given pair of arguments. By convention, ``False`` and ``True`` are\n   returned for a successful comparison. However, these methods can\n   return any value, so if the comparison operator is used in a\n   Boolean context (e.g., in the condition of an ``if`` statement),\n   Python will call ``bool()`` on the value to determine if the result\n   is true or false.\n\n   There are no implied relationships among the comparison operators.\n   The truth of ``x==y`` does not imply that ``x!=y`` is false.\n   Accordingly, when defining ``__eq__()``, one should also define\n   ``__ne__()`` so that the operators will behave as expected.  See\n   the paragraph on ``__hash__()`` for some important notes on\n   creating *hashable* objects which support custom comparison\n   operations and are usable as dictionary keys.\n\n   There are no swapped-argument versions of these methods (to be used\n   when the left argument does not support the operation but the right\n   argument does); rather, ``__lt__()`` and ``__gt__()`` are each\n   other\'s reflection, ``__le__()`` and ``__ge__()`` are each other\'s\n   reflection, and ``__eq__()`` and ``__ne__()`` are their own\n   reflection.\n\n   Arguments to rich comparison methods are never coerced.\n\n   To automatically generate ordering operations from a single root\n   operation, see ``functools.total_ordering()``.\n\nobject.__hash__(self)\n\n   Called by built-in function ``hash()`` and for operations on\n   members of hashed collections including ``set``, ``frozenset``, and\n   ``dict``.  ``__hash__()`` should return an integer.  The only\n   required property is that objects which compare equal have the same\n   hash value; it is advised to somehow mix together (e.g. using\n   exclusive or) the hash values for the components of the object that\n   also play a part in comparison of objects.\n\n   If a class does not define an ``__eq__()`` method it should not\n   define a ``__hash__()`` operation either; if it defines\n   ``__eq__()`` but not ``__hash__()``, its instances will not be\n   usable as items in hashable collections.  If a class defines\n   mutable objects and implements an ``__eq__()`` method, it should\n   not implement ``__hash__()``, since the implementation of hashable\n   collections requires that a key\'s hash value is immutable (if the\n   object\'s hash value changes, it will be in the wrong hash bucket).\n\n   User-defined classes have ``__eq__()`` and ``__hash__()`` methods\n   by default; with them, all objects compare unequal (except with\n   themselves) and ``x.__hash__()`` returns ``id(x)``.\n\n   Classes which inherit a ``__hash__()`` method from a parent class\n   but change the meaning of ``__eq__()`` such that the hash value\n   returned is no longer appropriate (e.g. by switching to a value-\n   based concept of equality instead of the default identity based\n   equality) can explicitly flag themselves as being unhashable by\n   setting ``__hash__ = None`` in the class definition. Doing so means\n   that not only will instances of the class raise an appropriate\n   ``TypeError`` when a program attempts to retrieve their hash value,\n   but they will also be correctly identified as unhashable when\n   checking ``isinstance(obj, collections.Hashable)`` (unlike classes\n   which define their own ``__hash__()`` to explicitly raise\n   ``TypeError``).\n\n   If a class that overrides ``__eq__()`` needs to retain the\n   implementation of ``__hash__()`` from a parent class, the\n   interpreter must be told this explicitly by setting ``__hash__ =\n   <ParentClass>.__hash__``. Otherwise the inheritance of\n   ``__hash__()`` will be blocked, just as if ``__hash__`` had been\n   explicitly set to ``None``.\n\nobject.__bool__(self)\n\n   Called to implement truth value testing and the built-in operation\n   ``bool()``; should return ``False`` or ``True``.  When this method\n   is not defined, ``__len__()`` is called, if it is defined, and the\n   object is considered true if its result is nonzero.  If a class\n   defines neither ``__len__()`` nor ``__bool__()``, all its instances\n   are considered true.\n\n\nCustomizing attribute access\n============================\n\nThe following methods can be defined to customize the meaning of\nattribute access (use of, assignment to, or deletion of ``x.name``)\nfor class instances.\n\nobject.__getattr__(self, name)\n\n   Called when an attribute lookup has not found the attribute in the\n   usual places (i.e. it is not an instance attribute nor is it found\n   in the class tree for ``self``).  ``name`` is the attribute name.\n   This method should return the (computed) attribute value or raise\n   an ``AttributeError`` exception.\n\n   Note that if the attribute is found through the normal mechanism,\n   ``__getattr__()`` is not called.  (This is an intentional asymmetry\n   between ``__getattr__()`` and ``__setattr__()``.) This is done both\n   for efficiency reasons and because otherwise ``__getattr__()``\n   would have no way to access other attributes of the instance.  Note\n   that at least for instance variables, you can fake total control by\n   not inserting any values in the instance attribute dictionary (but\n   instead inserting them in another object).  See the\n   ``__getattribute__()`` method below for a way to actually get total\n   control over attribute access.\n\nobject.__getattribute__(self, name)\n\n   Called unconditionally to implement attribute accesses for\n   instances of the class. If the class also defines\n   ``__getattr__()``, the latter will not be called unless\n   ``__getattribute__()`` either calls it explicitly or raises an\n   ``AttributeError``. This method should return the (computed)\n   attribute value or raise an ``AttributeError`` exception. In order\n   to avoid infinite recursion in this method, its implementation\n   should always call the base class method with the same name to\n   access any attributes it needs, for example,\n   ``object.__getattribute__(self, name)``.\n\n   Note: This method may still be bypassed when looking up special methods\n     as the result of implicit invocation via language syntax or\n     built-in functions. See *Special method lookup*.\n\nobject.__setattr__(self, name, value)\n\n   Called when an attribute assignment is attempted.  This is called\n   instead of the normal mechanism (i.e. store the value in the\n   instance dictionary). *name* is the attribute name, *value* is the\n   value to be assigned to it.\n\n   If ``__setattr__()`` wants to assign to an instance attribute, it\n   should call the base class method with the same name, for example,\n   ``object.__setattr__(self, name, value)``.\n\nobject.__delattr__(self, name)\n\n   Like ``__setattr__()`` but for attribute deletion instead of\n   assignment.  This should only be implemented if ``del obj.name`` is\n   meaningful for the object.\n\nobject.__dir__(self)\n\n   Called when ``dir()`` is called on the object.  A list must be\n   returned.\n\n\nImplementing Descriptors\n------------------------\n\nThe following methods only apply when an instance of the class\ncontaining the method (a so-called *descriptor* class) appears in the\nclass dictionary of another class, known as the *owner* class.  In the\nexamples below, "the attribute" refers to the attribute whose name is\nthe key of the property in the owner class\' ``__dict__``.\n\nobject.__get__(self, instance, owner)\n\n   Called to get the attribute of the owner class (class attribute\n   access) or of an instance of that class (instance attribute\n   access). *owner* is always the owner class, while *instance* is the\n   instance that the attribute was accessed through, or ``None`` when\n   the attribute is accessed through the *owner*.  This method should\n   return the (computed) attribute value or raise an\n   ``AttributeError`` exception.\n\nobject.__set__(self, instance, value)\n\n   Called to set the attribute on an instance *instance* of the owner\n   class to a new value, *value*.\n\nobject.__delete__(self, instance)\n\n   Called to delete the attribute on an instance *instance* of the\n   owner class.\n\n\nInvoking Descriptors\n--------------------\n\nIn general, a descriptor is an object attribute with "binding\nbehavior", one whose attribute access has been overridden by methods\nin the descriptor protocol:  ``__get__()``, ``__set__()``, and\n``__delete__()``. If any of those methods are defined for an object,\nit is said to be a descriptor.\n\nThe default behavior for attribute access is to get, set, or delete\nthe attribute from an object\'s dictionary. For instance, ``a.x`` has a\nlookup chain starting with ``a.__dict__[\'x\']``, then\n``type(a).__dict__[\'x\']``, and continuing through the base classes of\n``type(a)`` excluding metaclasses.\n\nHowever, if the looked-up value is an object defining one of the\ndescriptor methods, then Python may override the default behavior and\ninvoke the descriptor method instead.  Where this occurs in the\nprecedence chain depends on which descriptor methods were defined and\nhow they were called.\n\nThe starting point for descriptor invocation is a binding, ``a.x``.\nHow the arguments are assembled depends on ``a``:\n\nDirect Call\n   The simplest and least common call is when user code directly\n   invokes a descriptor method:    ``x.__get__(a)``.\n\nInstance Binding\n   If binding to an object instance, ``a.x`` is transformed into the\n   call: ``type(a).__dict__[\'x\'].__get__(a, type(a))``.\n\nClass Binding\n   If binding to a class, ``A.x`` is transformed into the call:\n   ``A.__dict__[\'x\'].__get__(None, A)``.\n\nSuper Binding\n   If ``a`` is an instance of ``super``, then the binding ``super(B,\n   obj).m()`` searches ``obj.__class__.__mro__`` for the base class\n   ``A`` immediately preceding ``B`` and then invokes the descriptor\n   with the call: ``A.__dict__[\'m\'].__get__(obj, A)``.\n\nFor instance bindings, the precedence of descriptor invocation depends\non the which descriptor methods are defined.  A descriptor can define\nany combination of ``__get__()``, ``__set__()`` and ``__delete__()``.\nIf it does not define ``__get__()``, then accessing the attribute will\nreturn the descriptor object itself unless there is a value in the\nobject\'s instance dictionary.  If the descriptor defines ``__set__()``\nand/or ``__delete__()``, it is a data descriptor; if it defines\nneither, it is a non-data descriptor.  Normally, data descriptors\ndefine both ``__get__()`` and ``__set__()``, while non-data\ndescriptors have just the ``__get__()`` method.  Data descriptors with\n``__set__()`` and ``__get__()`` defined always override a redefinition\nin an instance dictionary.  In contrast, non-data descriptors can be\noverridden by instances.\n\nPython methods (including ``staticmethod()`` and ``classmethod()``)\nare implemented as non-data descriptors.  Accordingly, instances can\nredefine and override methods.  This allows individual instances to\nacquire behaviors that differ from other instances of the same class.\n\nThe ``property()`` function is implemented as a data descriptor.\nAccordingly, instances cannot override the behavior of a property.\n\n\n__slots__\n---------\n\nBy default, instances of classes have a dictionary for attribute\nstorage.  This wastes space for objects having very few instance\nvariables.  The space consumption can become acute when creating large\nnumbers of instances.\n\nThe default can be overridden by defining *__slots__* in a class\ndefinition. The *__slots__* declaration takes a sequence of instance\nvariables and reserves just enough space in each instance to hold a\nvalue for each variable.  Space is saved because *__dict__* is not\ncreated for each instance.\n\nobject.__slots__\n\n   This class variable can be assigned a string, iterable, or sequence\n   of strings with variable names used by instances.  If defined in a\n   class, *__slots__* reserves space for the declared variables and\n   prevents the automatic creation of *__dict__* and *__weakref__* for\n   each instance.\n\n\nNotes on using *__slots__*\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n* When inheriting from a class without *__slots__*, the *__dict__*\n  attribute of that class will always be accessible, so a *__slots__*\n  definition in the subclass is meaningless.\n\n* Without a *__dict__* variable, instances cannot be assigned new\n  variables not listed in the *__slots__* definition.  Attempts to\n  assign to an unlisted variable name raises ``AttributeError``. If\n  dynamic assignment of new variables is desired, then add\n  ``\'__dict__\'`` to the sequence of strings in the *__slots__*\n  declaration.\n\n* Without a *__weakref__* variable for each instance, classes defining\n  *__slots__* do not support weak references to its instances. If weak\n  reference support is needed, then add ``\'__weakref__\'`` to the\n  sequence of strings in the *__slots__* declaration.\n\n* *__slots__* are implemented at the class level by creating\n  descriptors (*Implementing Descriptors*) for each variable name.  As\n  a result, class attributes cannot be used to set default values for\n  instance variables defined by *__slots__*; otherwise, the class\n  attribute would overwrite the descriptor assignment.\n\n* The action of a *__slots__* declaration is limited to the class\n  where it is defined.  As a result, subclasses will have a *__dict__*\n  unless they also define *__slots__* (which must only contain names\n  of any *additional* slots).\n\n* If a class defines a slot also defined in a base class, the instance\n  variable defined by the base class slot is inaccessible (except by\n  retrieving its descriptor directly from the base class). This\n  renders the meaning of the program undefined.  In the future, a\n  check may be added to prevent this.\n\n* Nonempty *__slots__* does not work for classes derived from\n  "variable-length" built-in types such as ``int``, ``str`` and\n  ``tuple``.\n\n* Any non-string iterable may be assigned to *__slots__*. Mappings may\n  also be used; however, in the future, special meaning may be\n  assigned to the values corresponding to each key.\n\n* *__class__* assignment works only if both classes have the same\n  *__slots__*.\n\n\nCustomizing class creation\n==========================\n\nBy default, classes are constructed using ``type()``. A class\ndefinition is read into a separate namespace and the value of class\nname is bound to the result of ``type(name, bases, dict)``.\n\nWhen the class definition is read, if a callable ``metaclass`` keyword\nargument is passed after the bases in the class definition, the\ncallable given will be called instead of ``type()``.  If other keyword\narguments are passed, they will also be passed to the metaclass.  This\nallows classes or functions to be written which monitor or alter the\nclass creation process:\n\n* Modifying the class dictionary prior to the class being created.\n\n* Returning an instance of another class -- essentially performing the\n  role of a factory function.\n\nThese steps will have to be performed in the metaclass\'s ``__new__()``\nmethod -- ``type.__new__()`` can then be called from this method to\ncreate a class with different properties.  This example adds a new\nelement to the class dictionary before creating the class:\n\n   class metacls(type):\n       def __new__(mcs, name, bases, dict):\n           dict[\'foo\'] = \'metacls was here\'\n           return type.__new__(mcs, name, bases, dict)\n\nYou can of course also override other class methods (or add new\nmethods); for example defining a custom ``__call__()`` method in the\nmetaclass allows custom behavior when the class is called, e.g. not\nalways creating a new instance.\n\nIf the metaclass has a ``__prepare__()`` attribute (usually\nimplemented as a class or static method), it is called before the\nclass body is evaluated with the name of the class and a tuple of its\nbases for arguments.  It should return an object that supports the\nmapping interface that will be used to store the namespace of the\nclass.  The default is a plain dictionary.  This could be used, for\nexample, to keep track of the order that class attributes are declared\nin by returning an ordered dictionary.\n\nThe appropriate metaclass is determined by the following precedence\nrules:\n\n* If the ``metaclass`` keyword argument is passed with the bases, it\n  is used.\n\n* Otherwise, if there is at least one base class, its metaclass is\n  used.\n\n* Otherwise, the default metaclass (``type``) is used.\n\nThe potential uses for metaclasses are boundless. Some ideas that have\nbeen explored including logging, interface checking, automatic\ndelegation, automatic property creation, proxies, frameworks, and\nautomatic resource locking/synchronization.\n\nHere is an example of a metaclass that uses an\n``collections.OrderedDict`` to remember the order that class members\nwere defined:\n\n   class OrderedClass(type):\n\n        @classmethod\n        def __prepare__(metacls, name, bases, **kwds):\n           return collections.OrderedDict()\n\n        def __new__(cls, name, bases, classdict):\n           result = type.__new__(cls, name, bases, dict(classdict))\n           result.members = tuple(classdict)\n           return result\n\n   class A(metaclass=OrderedClass):\n       def one(self): pass\n       def two(self): pass\n       def three(self): pass\n       def four(self): pass\n\n   >>> A.members\n   (\'__module__\', \'one\', \'two\', \'three\', \'four\')\n\nWhen the class definition for *A* gets executed, the process begins\nwith calling the metaclass\'s ``__prepare__()`` method which returns an\nempty ``collections.OrderedDict``.  That mapping records the methods\nand attributes of *A* as they are defined within the body of the class\nstatement. Once those definitions are executed, the ordered dictionary\nis fully populated and the metaclass\'s ``__new__()`` method gets\ninvoked.  That method builds the new type and it saves the ordered\ndictionary keys in an attribute called ``members``.\n\n\nCustomizing instance and subclass checks\n========================================\n\nThe following methods are used to override the default behavior of the\n``isinstance()`` and ``issubclass()`` built-in functions.\n\nIn particular, the metaclass ``abc.ABCMeta`` implements these methods\nin order to allow the addition of Abstract Base Classes (ABCs) as\n"virtual base classes" to any class or type (including built-in\ntypes), including other ABCs.\n\nclass.__instancecheck__(self, instance)\n\n   Return true if *instance* should be considered a (direct or\n   indirect) instance of *class*. If defined, called to implement\n   ``isinstance(instance, class)``.\n\nclass.__subclasscheck__(self, subclass)\n\n   Return true if *subclass* should be considered a (direct or\n   indirect) subclass of *class*.  If defined, called to implement\n   ``issubclass(subclass, class)``.\n\nNote that these methods are looked up on the type (metaclass) of a\nclass.  They cannot be defined as class methods in the actual class.\nThis is consistent with the lookup of special methods that are called\non instances, only in this case the instance is itself a class.\n\nSee also:\n\n   **PEP 3119** - Introducing Abstract Base Classes\n      Includes the specification for customizing ``isinstance()`` and\n      ``issubclass()`` behavior through ``__instancecheck__()`` and\n      ``__subclasscheck__()``, with motivation for this functionality\n      in the context of adding Abstract Base Classes (see the ``abc``\n      module) to the language.\n\n\nEmulating callable objects\n==========================\n\nobject.__call__(self[, args...])\n\n   Called when the instance is "called" as a function; if this method\n   is defined, ``x(arg1, arg2, ...)`` is a shorthand for\n   ``x.__call__(arg1, arg2, ...)``.\n\n\nEmulating container types\n=========================\n\nThe following methods can be defined to implement container objects.\nContainers usually are sequences (such as lists or tuples) or mappings\n(like dictionaries), but can represent other containers as well.  The\nfirst set of methods is used either to emulate a sequence or to\nemulate a mapping; the difference is that for a sequence, the\nallowable keys should be the integers *k* for which ``0 <= k < N``\nwhere *N* is the length of the sequence, or slice objects, which\ndefine a range of items.  It is also recommended that mappings provide\nthe methods ``keys()``, ``values()``, ``items()``, ``get()``,\n``clear()``, ``setdefault()``, ``pop()``, ``popitem()``, ``copy()``,\nand ``update()`` behaving similar to those for Python\'s standard\ndictionary objects.  The ``collections`` module provides a\n``MutableMapping`` abstract base class to help create those methods\nfrom a base set of ``__getitem__()``, ``__setitem__()``,\n``__delitem__()``, and ``keys()``. Mutable sequences should provide\nmethods ``append()``, ``count()``, ``index()``, ``extend()``,\n``insert()``, ``pop()``, ``remove()``, ``reverse()`` and ``sort()``,\nlike Python standard list objects.  Finally, sequence types should\nimplement addition (meaning concatenation) and multiplication (meaning\nrepetition) by defining the methods ``__add__()``, ``__radd__()``,\n``__iadd__()``, ``__mul__()``, ``__rmul__()`` and ``__imul__()``\ndescribed below; they should not define other numerical operators.  It\nis recommended that both mappings and sequences implement the\n``__contains__()`` method to allow efficient use of the ``in``\noperator; for mappings, ``in`` should search the mapping\'s keys; for\nsequences, it should search through the values.  It is further\nrecommended that both mappings and sequences implement the\n``__iter__()`` method to allow efficient iteration through the\ncontainer; for mappings, ``__iter__()`` should be the same as\n``keys()``; for sequences, it should iterate through the values.\n\nobject.__len__(self)\n\n   Called to implement the built-in function ``len()``.  Should return\n   the length of the object, an integer ``>=`` 0.  Also, an object\n   that doesn\'t define a ``__bool__()`` method and whose ``__len__()``\n   method returns zero is considered to be false in a Boolean context.\n\nNote: Slicing is done exclusively with the following three methods.  A\n  call like\n\n     a[1:2] = b\n\n  is translated to\n\n     a[slice(1, 2, None)] = b\n\n  and so forth.  Missing slice items are always filled in with\n  ``None``.\n\nobject.__getitem__(self, key)\n\n   Called to implement evaluation of ``self[key]``. For sequence\n   types, the accepted keys should be integers and slice objects.\n   Note that the special interpretation of negative indexes (if the\n   class wishes to emulate a sequence type) is up to the\n   ``__getitem__()`` method. If *key* is of an inappropriate type,\n   ``TypeError`` may be raised; if of a value outside the set of\n   indexes for the sequence (after any special interpretation of\n   negative values), ``IndexError`` should be raised. For mapping\n   types, if *key* is missing (not in the container), ``KeyError``\n   should be raised.\n\n   Note: ``for`` loops expect that an ``IndexError`` will be raised for\n     illegal indexes to allow proper detection of the end of the\n     sequence.\n\nobject.__setitem__(self, key, value)\n\n   Called to implement assignment to ``self[key]``.  Same note as for\n   ``__getitem__()``.  This should only be implemented for mappings if\n   the objects support changes to the values for keys, or if new keys\n   can be added, or for sequences if elements can be replaced.  The\n   same exceptions should be raised for improper *key* values as for\n   the ``__getitem__()`` method.\n\nobject.__delitem__(self, key)\n\n   Called to implement deletion of ``self[key]``.  Same note as for\n   ``__getitem__()``.  This should only be implemented for mappings if\n   the objects support removal of keys, or for sequences if elements\n   can be removed from the sequence.  The same exceptions should be\n   raised for improper *key* values as for the ``__getitem__()``\n   method.\n\nobject.__iter__(self)\n\n   This method is called when an iterator is required for a container.\n   This method should return a new iterator object that can iterate\n   over all the objects in the container.  For mappings, it should\n   iterate over the keys of the container, and should also be made\n   available as the method ``keys()``.\n\n   Iterator objects also need to implement this method; they are\n   required to return themselves.  For more information on iterator\n   objects, see *Iterator Types*.\n\nobject.__reversed__(self)\n\n   Called (if present) by the ``reversed()`` built-in to implement\n   reverse iteration.  It should return a new iterator object that\n   iterates over all the objects in the container in reverse order.\n\n   If the ``__reversed__()`` method is not provided, the\n   ``reversed()`` built-in will fall back to using the sequence\n   protocol (``__len__()`` and ``__getitem__()``).  Objects that\n   support the sequence protocol should only provide\n   ``__reversed__()`` if they can provide an implementation that is\n   more efficient than the one provided by ``reversed()``.\n\nThe membership test operators (``in`` and ``not in``) are normally\nimplemented as an iteration through a sequence.  However, container\nobjects can supply the following special method with a more efficient\nimplementation, which also does not require the object be a sequence.\n\nobject.__contains__(self, item)\n\n   Called to implement membership test operators.  Should return true\n   if *item* is in *self*, false otherwise.  For mapping objects, this\n   should consider the keys of the mapping rather than the values or\n   the key-item pairs.\n\n   For objects that don\'t define ``__contains__()``, the membership\n   test first tries iteration via ``__iter__()``, then the old\n   sequence iteration protocol via ``__getitem__()``, see *this\n   section in the language reference*.\n\n\nEmulating numeric types\n=======================\n\nThe following methods can be defined to emulate numeric objects.\nMethods corresponding to operations that are not supported by the\nparticular kind of number implemented (e.g., bitwise operations for\nnon-integral numbers) should be left undefined.\n\nobject.__add__(self, other)\nobject.__sub__(self, other)\nobject.__mul__(self, other)\nobject.__truediv__(self, other)\nobject.__floordiv__(self, other)\nobject.__mod__(self, other)\nobject.__divmod__(self, other)\nobject.__pow__(self, other[, modulo])\nobject.__lshift__(self, other)\nobject.__rshift__(self, other)\nobject.__and__(self, other)\nobject.__xor__(self, other)\nobject.__or__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``).  For instance, to evaluate the expression ``x + y``, where\n   *x* is an instance of a class that has an ``__add__()`` method,\n   ``x.__add__(y)`` is called.  The ``__divmod__()`` method should be\n   the equivalent to using ``__floordiv__()`` and ``__mod__()``; it\n   should not be related to ``__truediv__()``.  Note that\n   ``__pow__()`` should be defined to accept an optional third\n   argument if the ternary version of the built-in ``pow()`` function\n   is to be supported.\n\n   If one of those methods does not support the operation with the\n   supplied arguments, it should return ``NotImplemented``.\n\nobject.__radd__(self, other)\nobject.__rsub__(self, other)\nobject.__rmul__(self, other)\nobject.__rtruediv__(self, other)\nobject.__rfloordiv__(self, other)\nobject.__rmod__(self, other)\nobject.__rdivmod__(self, other)\nobject.__rpow__(self, other)\nobject.__rlshift__(self, other)\nobject.__rrshift__(self, other)\nobject.__rand__(self, other)\nobject.__rxor__(self, other)\nobject.__ror__(self, other)\n\n   These methods are called to implement the binary arithmetic\n   operations (``+``, ``-``, ``*``, ``/``, ``//``, ``%``,\n   ``divmod()``, ``pow()``, ``**``, ``<<``, ``>>``, ``&``, ``^``,\n   ``|``) with reflected (swapped) operands. These functions are only\n   called if the left operand does not support the corresponding\n   operation and the operands are of different types. [2]  For\n   instance, to evaluate the expression ``x - y``, where *y* is an\n   instance of a class that has an ``__rsub__()`` method,\n   ``y.__rsub__(x)`` is called if ``x.__sub__(y)`` returns\n   *NotImplemented*.\n\n   Note that ternary ``pow()`` will not try calling ``__rpow__()``\n   (the coercion rules would become too complicated).\n\n   Note: If the right operand\'s type is a subclass of the left operand\'s\n     type and that subclass provides the reflected method for the\n     operation, this method will be called before the left operand\'s\n     non-reflected method.  This behavior allows subclasses to\n     override their ancestors\' operations.\n\nobject.__iadd__(self, other)\nobject.__isub__(self, other)\nobject.__imul__(self, other)\nobject.__itruediv__(self, other)\nobject.__ifloordiv__(self, other)\nobject.__imod__(self, other)\nobject.__ipow__(self, other[, modulo])\nobject.__ilshift__(self, other)\nobject.__irshift__(self, other)\nobject.__iand__(self, other)\nobject.__ixor__(self, other)\nobject.__ior__(self, other)\n\n   These methods are called to implement the augmented arithmetic\n   assignments (``+=``, ``-=``, ``*=``, ``/=``, ``//=``, ``%=``,\n   ``**=``, ``<<=``, ``>>=``, ``&=``, ``^=``, ``|=``).  These methods\n   should attempt to do the operation in-place (modifying *self*) and\n   return the result (which could be, but does not have to be,\n   *self*).  If a specific method is not defined, the augmented\n   assignment falls back to the normal methods.  For instance, to\n   execute the statement ``x += y``, where *x* is an instance of a\n   class that has an ``__iadd__()`` method, ``x.__iadd__(y)`` is\n   called.  If *x* is an instance of a class that does not define a\n   ``__iadd__()`` method, ``x.__add__(y)`` and ``y.__radd__(x)`` are\n   considered, as with the evaluation of ``x + y``.\n\nobject.__neg__(self)\nobject.__pos__(self)\nobject.__abs__(self)\nobject.__invert__(self)\n\n   Called to implement the unary arithmetic operations (``-``, ``+``,\n   ``abs()`` and ``~``).\n\nobject.__complex__(self)\nobject.__int__(self)\nobject.__float__(self)\nobject.__round__(self[, n])\n\n   Called to implement the built-in functions ``complex()``,\n   ``int()``, ``float()`` and ``round()``.  Should return a value of\n   the appropriate type.\n\nobject.__index__(self)\n\n   Called to implement ``operator.index()``.  Also called whenever\n   Python needs an integer object (such as in slicing, or in the\n   built-in ``bin()``, ``hex()`` and ``oct()`` functions). Must return\n   an integer.\n\n\nWith Statement Context Managers\n===============================\n\nA *context manager* is an object that defines the runtime context to\nbe established when executing a ``with`` statement. The context\nmanager handles the entry into, and the exit from, the desired runtime\ncontext for the execution of the block of code.  Context managers are\nnormally invoked using the ``with`` statement (described in section\n*The with statement*), but can also be used by directly invoking their\nmethods.\n\nTypical uses of context managers include saving and restoring various\nkinds of global state, locking and unlocking resources, closing opened\nfiles, etc.\n\nFor more information on context managers, see *Context Manager Types*.\n\nobject.__enter__(self)\n\n   Enter the runtime context related to this object. The ``with``\n   statement will bind this method\'s return value to the target(s)\n   specified in the ``as`` clause of the statement, if any.\n\nobject.__exit__(self, exc_type, exc_value, traceback)\n\n   Exit the runtime context related to this object. The parameters\n   describe the exception that caused the context to be exited. If the\n   context was exited without an exception, all three arguments will\n   be ``None``.\n\n   If an exception is supplied, and the method wishes to suppress the\n   exception (i.e., prevent it from being propagated), it should\n   return a true value. Otherwise, the exception will be processed\n   normally upon exit from this method.\n\n   Note that ``__exit__()`` methods should not reraise the passed-in\n   exception; this is the caller\'s responsibility.\n\nSee also:\n\n   **PEP 0343** - The "with" statement\n      The specification, background, and examples for the Python\n      ``with`` statement.\n\n\nSpecial method lookup\n=====================\n\nFor custom classes, implicit invocations of special methods are only\nguaranteed to work correctly if defined on an object\'s type, not in\nthe object\'s instance dictionary.  That behaviour is the reason why\nthe following code raises an exception:\n\n   >>> class C:\n   ...     pass\n   ...\n   >>> c = C()\n   >>> c.__len__ = lambda: 5\n   >>> len(c)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: object of type \'C\' has no len()\n\nThe rationale behind this behaviour lies with a number of special\nmethods such as ``__hash__()`` and ``__repr__()`` that are implemented\nby all objects, including type objects. If the implicit lookup of\nthese methods used the conventional lookup process, they would fail\nwhen invoked on the type object itself:\n\n   >>> 1 .__hash__() == hash(1)\n   True\n   >>> int.__hash__() == hash(int)\n   Traceback (most recent call last):\n     File "<stdin>", line 1, in <module>\n   TypeError: descriptor \'__hash__\' of \'int\' object needs an argument\n\nIncorrectly attempting to invoke an unbound method of a class in this\nway is sometimes referred to as \'metaclass confusion\', and is avoided\nby bypassing the instance when looking up special methods:\n\n   >>> type(1).__hash__(1) == hash(1)\n   True\n   >>> type(int).__hash__(int) == hash(int)\n   True\n\nIn addition to bypassing any instance attributes in the interest of\ncorrectness, implicit special method lookup generally also bypasses\nthe ``__getattribute__()`` method even of the object\'s metaclass:\n\n   >>> class Meta(type):\n   ...    def __getattribute__(*args):\n   ...       print("Metaclass getattribute invoked")\n   ...       return type.__getattribute__(*args)\n   ...\n   >>> class C(object, metaclass=Meta):\n   ...     def __len__(self):\n   ...         return 10\n   ...     def __getattribute__(*args):\n   ...         print("Class getattribute invoked")\n   ...         return object.__getattribute__(*args)\n   ...\n   >>> c = C()\n   >>> c.__len__()                 # Explicit lookup via instance\n   Class getattribute invoked\n   10\n   >>> type(c).__len__(c)          # Explicit lookup via type\n   Metaclass getattribute invoked\n   10\n   >>> len(c)                      # Implicit lookup\n   10\n\nBypassing the ``__getattribute__()`` machinery in this fashion\nprovides significant scope for speed optimisations within the\ninterpreter, at the cost of some flexibility in the handling of\nspecial methods (the special method *must* be set on the class object\nitself in order to be consistently invoked by the interpreter).\n\n-[ Footnotes ]-\n\n[1] It *is* possible in some cases to change an object\'s type, under\n    certain controlled conditions. It generally isn\'t a good idea\n    though, since it can lead to some very strange behaviour if it is\n    handled incorrectly.\n\n[2] For operands of the same type, it is assumed that if the non-\n    reflected method (such as ``__add__()``) fails the operation is\n    not supported, which is why the reflected method is not called.\n',
+ 'string-methods': '\nString Methods\n**************\n\nString objects support the methods listed below.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, bytes, bytearray, list,\ntuple, range* section. To output formatted strings, see the *String\nFormatting* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n   Return a copy of the string with its first character capitalized\n   and the rest lowercased.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\n   Return the number of non-overlapping occurrences of substring *sub*\n   in the range [*start*, *end*].  Optional arguments *start* and\n   *end* are interpreted as in slice notation.\n\nstr.encode(encoding="utf-8", errors="strict")\n\n   Return an encoded version of the string as a bytes object. Default\n   encoding is ``\'utf-8\'``. *errors* may be given to set a different\n   error handling scheme. The default for *errors* is ``\'strict\'``,\n   meaning that encoding errors raise a ``UnicodeError``. Other\n   possible values are ``\'ignore\'``, ``\'replace\'``,\n   ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and any other name\n   registered via ``codecs.register_error()``, see section *Codec Base\n   Classes*. For a list of possible encodings, see section *Standard\n   Encodings*.\n\n   Changed in version 3.1: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return ``True`` if the string ends with the specified *suffix*,\n   otherwise return ``False``.  *suffix* can also be a tuple of\n   suffixes to look for.  With optional *start*, test beginning at\n   that position.  With optional *end*, stop comparing at that\n   position.\n\nstr.expandtabs([tabsize])\n\n   Return a copy of the string where all tab characters are replaced\n   by one or more spaces, depending on the current column and the\n   given tab size.  The column number is reset to zero after each\n   newline occurring in the string. If *tabsize* is not given, a tab\n   size of ``8`` characters is assumed.  This doesn\'t understand other\n   non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n   Return the lowest index in the string where substring *sub* is\n   found, such that *sub* is contained in the slice ``s[start:end]``.\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The string on which this\n   method is called can contain literal text or replacement fields\n   delimited by braces ``{}``.  Each replacement field contains either\n   the numeric index of a positional argument, or the name of a\n   keyword argument.  Returns a copy of the string where each\n   replacement field is replaced with the string value of the\n   corresponding argument.\n\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\n   \'The sum of 1 + 2 is 3\'\n\n   See *Format String Syntax* for a description of the various\n   formatting options that can be specified in format strings.\n\nstr.format_map(mapping)\n\n   Similar to ``str.format(**mapping)``, except that ``mapping`` is\n   used directly and not copied to a ``dict`` .  This is useful if for\n   example ``mapping`` is a dict subclass:\n\n   >>> class Default(dict):\n   ...     def __missing__(self, key):\n   ...         return key\n   ...\n   >>> \'{name} was born in {country}\'.format_map(Default(name=\'Guido\'))\n   \'Guido was born in country\'\n\n   New in version 3.2.\n\nstr.index(sub[, start[, end]])\n\n   Like ``find()``, but raise ``ValueError`` when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.  A character\n   ``c`` is alphanumeric if one of the following returns ``True``:\n   ``c.isalpha()``, ``c.isdecimal()``, ``c.isdigit()``, or\n   ``c.isnumeric()``.\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.  Alphabetic\n   characters are those characters defined in the Unicode character\n   database as "Letter", i.e., those with general category property\n   being one of "Lm", "Lt", "Lu", "Ll", or "Lo".  Note that this is\n   different from the "Alphabetic" property defined in the Unicode\n   Standard.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters are those from general category "Nd". This category\n   includes digit characters, and all characters that that can be used\n   to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT\n   ZERO.\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.  Digits include decimal\n   characters and digits that need special handling, such as the\n   compatibility superscript digits.  Formally, a digit is a character\n   that has the property value Numeric_Type=Digit or\n   Numeric_Type=Decimal.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n   Return true if all cased characters in the string are lowercase and\n   there is at least one cased character, false otherwise.  Cased\n   characters are those with general category property being one of\n   "Lu", "Ll", or "Lt" and lowercase characters are those with general\n   category property "Ll".\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.  Formally, numeric characters are those with the\n   property value Numeric_Type=Digit, Numeric_Type=Decimal or\n   Numeric_Type=Numeric.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when ``repr()`` is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.isspace()\n\n   Return true if there are only whitespace characters in the string\n   and there is at least one character, false otherwise.  Whitespace\n   characters  are those characters defined in the Unicode character\n   database as "Other" or "Separator" and those with bidirectional\n   property being one of "WS", "B", or "S".\n\nstr.istitle()\n\n   Return true if the string is a titlecased string and there is at\n   least one character, for example uppercase characters may only\n   follow uncased characters and lowercase characters only cased ones.\n   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters in the string are uppercase and\n   there is at least one cased character, false otherwise. Cased\n   characters are those with general category property being one of\n   "Lu", "Ll", or "Lt" and uppercase characters are those with general\n   category property "Lu".\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  A ``TypeError`` will be raised if there are\n   any non-string values in *seq*, including ``bytes`` objects.  The\n   separator between elements is the string providing this method.\n\nstr.ljust(width[, fillchar])\n\n   Return the string left justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is a\n   space).  The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.lower()\n\n   Return a copy of the string converted to lowercase.\n\nstr.lstrip([chars])\n\n   Return a copy of the string with leading characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or ``None``, the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.lstrip()\n   \'spacious   \'\n   >>> \'www.example.com\'.lstrip(\'cmowz.\')\n   \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   ``str.translate()``.\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or None.\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   None in the result.\n\nstr.partition(sep)\n\n   Split the string at the first occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\n\n   Return a copy of the string with all occurrences of substring *old*\n   replaced by *new*.  If the optional argument *count* is given, only\n   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n   Return the highest index in the string where substring *sub* is\n   found, such that *sub* is contained within ``s[start:end]``.\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n   is not found.\n\nstr.rjust(width[, fillchar])\n\n   Return the string right justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is a\n   space). The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.rpartition(sep)\n\n   Split the string at the last occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.rsplit([sep[, maxsplit]])\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n   are done, the *rightmost* ones.  If *sep* is not specified or\n   ``None``, any whitespace string is a separator.  Except for\n   splitting from the right, ``rsplit()`` behaves like ``split()``\n   which is described in detail below.\n\nstr.rstrip([chars])\n\n   Return a copy of the string with trailing characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or ``None``, the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.rstrip()\n   \'   spacious\'\n   >>> \'mississippi\'.rstrip(\'ipz\')\n   \'mississ\'\n\nstr.split([sep[, maxsplit]])\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string.  If *maxsplit* is given, at most *maxsplit*\n   splits are done (thus, the list will have at most ``maxsplit+1``\n   elements).  If *maxsplit* is not specified, then there is no limit\n   on the number of splits (all possible splits are made).\n\n   If *sep* is given, consecutive delimiters are not grouped together\n   and are deemed to delimit empty strings (for example,\n   ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``).  The *sep*\n   argument may consist of multiple characters (for example,\n   ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n   an empty string with a specified separator returns ``[\'\']``.\n\n   If *sep* is not specified or is ``None``, a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no empty strings\n   at the start or end if the string has leading or trailing\n   whitespace.  Consequently, splitting an empty string or a string\n   consisting of just whitespace with a ``None`` separator returns\n   ``[]``.\n\n   For example, ``\' 1  2   3  \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n   and ``\'  1  2   3  \'.split(None, 1)`` returns ``[\'1\', \'2   3  \']``.\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return ``True`` if string starts with the *prefix*, otherwise\n   return ``False``. *prefix* can also be a tuple of prefixes to look\n   for.  With optional *start*, test string beginning at that\n   position.  With optional *end*, stop comparing string at that\n   position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or ``None``, the\n   *chars* argument defaults to removing whitespace. The *chars*\n   argument is not a prefix or suffix; rather, all combinations of its\n   values are stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\nstr.title()\n\n   Return a titlecased version of the string where words start with an\n   uppercase character and the remaining characters are lowercase.\n\n   The algorithm uses a simple language-independent definition of a\n   word as groups of consecutive letters.  The definition works in\n   many contexts but it means that apostrophes in contractions and\n   possessives form word boundaries, which may not be the desired\n   result:\n\n      >>> "they\'re bill\'s friends from the UK".title()\n      "They\'Re Bill\'S Friends From The Uk"\n\n   A workaround for apostrophes can be constructed using regular\n   expressions:\n\n      >>> import re\n      >>> def titlecase(s):\n              return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n                            lambda mo: mo.group(0)[0].upper() +\n                                       mo.group(0)[1:].lower(),\n                            s)\n\n      >>> titlecase("they\'re bill\'s friends.")\n      "They\'re Bill\'s Friends."\n\nstr.translate(map)\n\n   Return a copy of the *s* where all characters have been mapped\n   through the *map* which must be a dictionary of Unicode ordinals\n   (integers) to Unicode ordinals, strings or ``None``.  Unmapped\n   characters are left untouched. Characters mapped to ``None`` are\n   deleted.\n\n   You can use ``str.maketrans()`` to create a translation map from\n   character-to-character mappings in different formats.\n\n   Note: An even more flexible approach is to create a custom character\n     mapping codec using the ``codecs`` module (see\n     ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n   Return a copy of the string converted to uppercase.\n\nstr.zfill(width)\n\n   Return the numeric string left filled with zeros in a string of\n   length *width*.  A sign prefix is handled correctly.  The original\n   string is returned if *width* is less than ``len(s)``.\n',
  'strings': '\nString and Bytes literals\n*************************\n\nString literals are described by the following lexical definitions:\n\n   stringliteral   ::= [stringprefix](shortstring | longstring)\n   stringprefix    ::= "r" | "R"\n   shortstring     ::= "\'" shortstringitem* "\'" | \'"\' shortstringitem* \'"\'\n   longstring      ::= "\'\'\'" longstringitem* "\'\'\'" | \'"""\' longstringitem* \'"""\'\n   shortstringitem ::= shortstringchar | stringescapeseq\n   longstringitem  ::= longstringchar | stringescapeseq\n   shortstringchar ::= <any source character except "\\" or newline or the quote>\n   longstringchar  ::= <any source character except "\\">\n   stringescapeseq ::= "\\" <any source character>\n\n   bytesliteral   ::= bytesprefix(shortbytes | longbytes)\n   bytesprefix    ::= "b" | "B" | "br" | "Br" | "bR" | "BR"\n   shortbytes     ::= "\'" shortbytesitem* "\'" | \'"\' shortbytesitem* \'"\'\n   longbytes      ::= "\'\'\'" longbytesitem* "\'\'\'" | \'"""\' longbytesitem* \'"""\'\n   shortbytesitem ::= shortbyteschar | bytesescapeseq\n   longbytesitem  ::= longbyteschar | bytesescapeseq\n   shortbyteschar ::= <any ASCII character except "\\" or newline or the quote>\n   longbyteschar  ::= <any ASCII character except "\\">\n   bytesescapeseq ::= "\\" <any ASCII character>\n\nOne syntactic restriction not indicated by these productions is that\nwhitespace is not allowed between the ``stringprefix`` or\n``bytesprefix`` and the rest of the literal. The source character set\nis defined by the encoding declaration; it is UTF-8 if no encoding\ndeclaration is given in the source file; see section *Encoding\ndeclarations*.\n\nIn plain English: Both types of literals can be enclosed in matching\nsingle quotes (``\'``) or double quotes (``"``).  They can also be\nenclosed in matching groups of three single or double quotes (these\nare generally referred to as *triple-quoted strings*).  The backslash\n(``\\``) character is used to escape characters that otherwise have a\nspecial meaning, such as newline, backslash itself, or the quote\ncharacter.\n\nBytes literals are always prefixed with ``\'b\'`` or ``\'B\'``; they\nproduce an instance of the ``bytes`` type instead of the ``str`` type.\nThey may only contain ASCII characters; bytes with a numeric value of\n128 or greater must be expressed with escapes.\n\nBoth string and bytes literals may optionally be prefixed with a\nletter ``\'r\'`` or ``\'R\'``; such strings are called *raw strings* and\ntreat backslashes as literal characters.  As a result, in string\nliterals, ``\'\\U\'`` and ``\'\\u\'`` escapes in raw strings are not treated\nspecially.\n\nIn triple-quoted strings, unescaped newlines and quotes are allowed\n(and are retained), except that three unescaped quotes in a row\nterminate the string.  (A "quote" is the character used to open the\nstring, i.e. either ``\'`` or ``"``.)\n\nUnless an ``\'r\'`` or ``\'R\'`` prefix is present, escape sequences in\nstrings are interpreted according to rules similar to those used by\nStandard C.  The recognized escape sequences are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence   | Meaning                           | Notes   |\n+===================+===================================+=========+\n| ``\\newline``      | Backslash and newline ignored     |         |\n+-------------------+-----------------------------------+---------+\n| ``\\\\``            | Backslash (``\\``)                 |         |\n+-------------------+-----------------------------------+---------+\n| ``\\\'``            | Single quote (``\'``)              |         |\n+-------------------+-----------------------------------+---------+\n| ``\\"``            | Double quote (``"``)              |         |\n+-------------------+-----------------------------------+---------+\n| ``\\a``            | ASCII Bell (BEL)                  |         |\n+-------------------+-----------------------------------+---------+\n| ``\\b``            | ASCII Backspace (BS)              |         |\n+-------------------+-----------------------------------+---------+\n| ``\\f``            | ASCII Formfeed (FF)               |         |\n+-------------------+-----------------------------------+---------+\n| ``\\n``            | ASCII Linefeed (LF)               |         |\n+-------------------+-----------------------------------+---------+\n| ``\\r``            | ASCII Carriage Return (CR)        |         |\n+-------------------+-----------------------------------+---------+\n| ``\\t``            | ASCII Horizontal Tab (TAB)        |         |\n+-------------------+-----------------------------------+---------+\n| ``\\v``            | ASCII Vertical Tab (VT)           |         |\n+-------------------+-----------------------------------+---------+\n| ``\\ooo``          | Character with octal value *ooo*  | (1,3)   |\n+-------------------+-----------------------------------+---------+\n| ``\\xhh``          | Character with hex value *hh*     | (2,3)   |\n+-------------------+-----------------------------------+---------+\n\nEscape sequences only recognized in string literals are:\n\n+-------------------+-----------------------------------+---------+\n| Escape Sequence   | Meaning                           | Notes   |\n+===================+===================================+=========+\n| ``\\N{name}``      | Character named *name* in the     |         |\n|                   | Unicode database                  |         |\n+-------------------+-----------------------------------+---------+\n| ``\\uxxxx``        | Character with 16-bit hex value   | (4)     |\n|                   | *xxxx*                            |         |\n+-------------------+-----------------------------------+---------+\n| ``\\Uxxxxxxxx``    | Character with 32-bit hex value   | (5)     |\n|                   | *xxxxxxxx*                        |         |\n+-------------------+-----------------------------------+---------+\n\nNotes:\n\n1. As in Standard C, up to three octal digits are accepted.\n\n2. Unlike in Standard C, exactly two hex digits are required.\n\n3. In a bytes literal, hexadecimal and octal escapes denote the byte\n   with the given value. In a string literal, these escapes denote a\n   Unicode character with the given value.\n\n4. Individual code units which form parts of a surrogate pair can be\n   encoded using this escape sequence.  Exactly four hex digits are\n   required.\n\n5. Any Unicode character can be encoded this way, but characters\n   outside the Basic Multilingual Plane (BMP) will be encoded using a\n   surrogate pair if Python is compiled to use 16-bit code units (the\n   default).  Exactly eight hex digits are required.\n\nUnlike Standard C, all unrecognized escape sequences are left in the\nstring unchanged, i.e., *the backslash is left in the string*.  (This\nbehavior is useful when debugging: if an escape sequence is mistyped,\nthe resulting output is more easily recognized as broken.)  It is also\nimportant to note that the escape sequences only recognized in string\nliterals fall into the category of unrecognized escapes for bytes\nliterals.\n\nEven in a raw string, string quotes can be escaped with a backslash,\nbut the backslash remains in the string; for example, ``r"\\""`` is a\nvalid string literal consisting of two characters: a backslash and a\ndouble quote; ``r"\\"`` is not a valid string literal (even a raw\nstring cannot end in an odd number of backslashes).  Specifically, *a\nraw string cannot end in a single backslash* (since the backslash\nwould escape the following quote character).  Note also that a single\nbackslash followed by a newline is interpreted as those two characters\nas part of the string, *not* as a line continuation.\n',
  'subscriptions': '\nSubscriptions\n*************\n\nA subscription selects an item of a sequence (string, tuple or list)\nor mapping (dictionary) object:\n\n   subscription ::= primary "[" expression_list "]"\n\nThe primary must evaluate to an object that supports subscription,\ne.g. a list or dictionary.  User-defined objects can support\nsubscription by defining a ``__getitem__()`` method.\n\nFor built-in objects, there are two types of objects that support\nsubscription:\n\nIf the primary is a mapping, the expression list must evaluate to an\nobject whose value is one of the keys of the mapping, and the\nsubscription selects the value in the mapping that corresponds to that\nkey.  (The expression list is a tuple except if it has exactly one\nitem.)\n\nIf the primary is a sequence, the expression (list) must evaluate to\nan integer or a slice (as discussed in the following section).\n\nThe formal syntax makes no special provision for negative indices in\nsequences; however, built-in sequences all provide a ``__getitem__()``\nmethod that interprets negative indices by adding the length of the\nsequence to the index (so that ``x[-1]`` selects the last item of\n``x``).  The resulting value must be a nonnegative integer less than\nthe number of items in the sequence, and the subscription selects the\nitem whose index is that value (counting from zero). Since the support\nfor negative indices and slicing occurs in the object\'s\n``__getitem__()`` method, subclasses overriding this method will need\nto explicitly add that support.\n\nA string\'s items are characters.  A character is not a separate data\ntype but a string of exactly one character.\n',
  'truth': "\nTruth Value Testing\n*******************\n\nAny object can be tested for truth value, for use in an ``if`` or\n``while`` condition or as operand of the Boolean operations below. The\nfollowing values are considered false:\n\n* ``None``\n\n* ``False``\n\n* zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.\n\n* any empty sequence, for example, ``''``, ``()``, ``[]``.\n\n* any empty mapping, for example, ``{}``.\n\n* instances of user-defined classes, if the class defines a\n  ``__bool__()`` or ``__len__()`` method, when that method returns the\n  integer zero or ``bool`` value ``False``. [1]\n\nAll other values are considered true --- so objects of many types are\nalways true.\n\nOperations and built-in functions that have a Boolean result always\nreturn ``0`` or ``False`` for false and ``1`` or ``True`` for true,\nunless otherwise stated. (Important exception: the Boolean operations\n``or`` and ``and`` always return one of their operands.)\n",
- 'try': '\nThe ``try`` statement\n*********************\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" target]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started.  This search inspects the except\nclauses in turn until one is found that matches the exception.  An\nexpression-less except clause, if present, must be last; it matches\nany exception.  For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception.  An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause.  Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting\nof: ``exc_type``, the exception class; ``exc_value``, the exception\ninstance; ``exc_traceback``, a traceback object (see section *The\nstandard type hierarchy*) identifying the point in the program where\nthe exception occurred. ``sys.exc_info()`` values are restored to\ntheir previous values (before the call) when returning from a function\nthat handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler.  The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses.  If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted.  If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost.  The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n',
- 'types': '\nThe standard type hierarchy\n***************************\n\nBelow is a list of the types that are built into Python.  Extension\nmodules (written in C, Java, or other languages, depending on the\nimplementation) can define additional types.  Future versions of\nPython may add types to the type hierarchy (e.g., rational numbers,\nefficiently stored arrays of integers, etc.), although such additions\nwill often be provided via the standard library instead.\n\nSome of the type descriptions below contain a paragraph listing\n\'special attributes.\'  These are attributes that provide access to the\nimplementation and are not intended for general use.  Their definition\nmay change in the future.\n\nNone\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the built-in name ``None``.\n   It is used to signify the absence of a value in many situations,\n   e.g., it is returned from functions that don\'t explicitly return\n   anything. Its truth value is false.\n\nNotImplemented\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the built-in name\n   ``NotImplemented``. Numeric methods and rich comparison methods may\n   return this value if they do not implement the operation for the\n   operands provided.  (The interpreter will then try the reflected\n   operation, or some other fallback, depending on the operator.)  Its\n   truth value is true.\n\nEllipsis\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the literal ``...`` or the\n   built-in name ``Ellipsis``.  Its truth value is true.\n\n``numbers.Number``\n   These are created by numeric literals and returned as results by\n   arithmetic operators and arithmetic built-in functions.  Numeric\n   objects are immutable; once created their value never changes.\n   Python numbers are of course strongly related to mathematical\n   numbers, but subject to the limitations of numerical representation\n   in computers.\n\n   Python distinguishes between integers, floating point numbers, and\n   complex numbers:\n\n   ``numbers.Integral``\n      These represent elements from the mathematical set of integers\n      (positive and negative).\n\n      There are two types of integers:\n\n      Integers (``int``)\n\n         These represent numbers in an unlimited range, subject to\n         available (virtual) memory only.  For the purpose of shift\n         and mask operations, a binary representation is assumed, and\n         negative numbers are represented in a variant of 2\'s\n         complement which gives the illusion of an infinite string of\n         sign bits extending to the left.\n\n      Booleans (``bool``)\n         These represent the truth values False and True.  The two\n         objects representing the values False and True are the only\n         Boolean objects. The Boolean type is a subtype of the integer\n         type, and Boolean values behave like the values 0 and 1,\n         respectively, in almost all contexts, the exception being\n         that when converted to a string, the strings ``"False"`` or\n         ``"True"`` are returned, respectively.\n\n      The rules for integer representation are intended to give the\n      most meaningful interpretation of shift and mask operations\n      involving negative integers.\n\n   ``numbers.Real`` (``float``)\n      These represent machine-level double precision floating point\n      numbers. You are at the mercy of the underlying machine\n      architecture (and C or Java implementation) for the accepted\n      range and handling of overflow. Python does not support single-\n      precision floating point numbers; the savings in processor and\n      memory usage that are usually the reason for using these is\n      dwarfed by the overhead of using objects in Python, so there is\n      no reason to complicate the language with two kinds of floating\n      point numbers.\n\n   ``numbers.Complex`` (``complex``)\n      These represent complex numbers as a pair of machine-level\n      double precision floating point numbers.  The same caveats apply\n      as for floating point numbers. The real and imaginary parts of a\n      complex number ``z`` can be retrieved through the read-only\n      attributes ``z.real`` and ``z.imag``.\n\nSequences\n   These represent finite ordered sets indexed by non-negative\n   numbers. The built-in function ``len()`` returns the number of\n   items of a sequence. When the length of a sequence is *n*, the\n   index set contains the numbers 0, 1, ..., *n*-1.  Item *i* of\n   sequence *a* is selected by ``a[i]``.\n\n   Sequences also support slicing: ``a[i:j]`` selects all items with\n   index *k* such that *i* ``<=`` *k* ``<`` *j*.  When used as an\n   expression, a slice is a sequence of the same type.  This implies\n   that the index set is renumbered so that it starts at 0.\n\n   Some sequences also support "extended slicing" with a third "step"\n   parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\n   where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\n   *j*.\n\n   Sequences are distinguished according to their mutability:\n\n   Immutable sequences\n      An object of an immutable sequence type cannot change once it is\n      created.  (If the object contains references to other objects,\n      these other objects may be mutable and may be changed; however,\n      the collection of objects directly referenced by an immutable\n      object cannot change.)\n\n      The following types are immutable sequences:\n\n      Strings\n         The items of a string object are Unicode code units.  A\n         Unicode code unit is represented by a string object of one\n         item and can hold either a 16-bit or 32-bit value\n         representing a Unicode ordinal (the maximum value for the\n         ordinal is given in ``sys.maxunicode``, and depends on how\n         Python is configured at compile time).  Surrogate pairs may\n         be present in the Unicode object, and will be reported as two\n         separate items.  The built-in functions ``chr()`` and\n         ``ord()`` convert between code units and nonnegative integers\n         representing the Unicode ordinals as defined in the Unicode\n         Standard 3.0. Conversion from and to other encodings are\n         possible through the string method ``encode()``.\n\n      Tuples\n         The items of a tuple are arbitrary Python objects. Tuples of\n         two or more items are formed by comma-separated lists of\n         expressions.  A tuple of one item (a \'singleton\') can be\n         formed by affixing a comma to an expression (an expression by\n         itself does not create a tuple, since parentheses must be\n         usable for grouping of expressions).  An empty tuple can be\n         formed by an empty pair of parentheses.\n\n      Bytes\n         A bytes object is an immutable array.  The items are 8-bit\n         bytes, represented by integers in the range 0 <= x < 256.\n         Bytes literals (like ``b\'abc\'`` and the built-in function\n         ``bytes()`` can be used to construct bytes objects.  Also,\n         bytes objects can be decoded to strings via the ``decode()``\n         method.\n\n   Mutable sequences\n      Mutable sequences can be changed after they are created.  The\n      subscription and slicing notations can be used as the target of\n      assignment and ``del`` (delete) statements.\n\n      There are currently two intrinsic mutable sequence types:\n\n      Lists\n         The items of a list are arbitrary Python objects.  Lists are\n         formed by placing a comma-separated list of expressions in\n         square brackets. (Note that there are no special cases needed\n         to form lists of length 0 or 1.)\n\n      Byte Arrays\n         A bytearray object is a mutable array. They are created by\n         the built-in ``bytearray()`` constructor.  Aside from being\n         mutable (and hence unhashable), byte arrays otherwise provide\n         the same interface and functionality as immutable bytes\n         objects.\n\n      The extension module ``array`` provides an additional example of\n      a mutable sequence type, as does the ``collections`` module.\n\nSet types\n   These represent unordered, finite sets of unique, immutable\n   objects. As such, they cannot be indexed by any subscript. However,\n   they can be iterated over, and the built-in function ``len()``\n   returns the number of items in a set. Common uses for sets are fast\n   membership testing, removing duplicates from a sequence, and\n   computing mathematical operations such as intersection, union,\n   difference, and symmetric difference.\n\n   For set elements, the same immutability rules apply as for\n   dictionary keys. Note that numeric types obey the normal rules for\n   numeric comparison: if two numbers compare equal (e.g., ``1`` and\n   ``1.0``), only one of them can be contained in a set.\n\n   There are currently two intrinsic set types:\n\n   Sets\n      These represent a mutable set. They are created by the built-in\n      ``set()`` constructor and can be modified afterwards by several\n      methods, such as ``add()``.\n\n   Frozen sets\n      These represent an immutable set.  They are created by the\n      built-in ``frozenset()`` constructor.  As a frozenset is\n      immutable and *hashable*, it can be used again as an element of\n      another set, or as a dictionary key.\n\nMappings\n   These represent finite sets of objects indexed by arbitrary index\n   sets. The subscript notation ``a[k]`` selects the item indexed by\n   ``k`` from the mapping ``a``; this can be used in expressions and\n   as the target of assignments or ``del`` statements. The built-in\n   function ``len()`` returns the number of items in a mapping.\n\n   There is currently a single intrinsic mapping type:\n\n   Dictionaries\n      These represent finite sets of objects indexed by nearly\n      arbitrary values.  The only types of values not acceptable as\n      keys are values containing lists or dictionaries or other\n      mutable types that are compared by value rather than by object\n      identity, the reason being that the efficient implementation of\n      dictionaries requires a key\'s hash value to remain constant.\n      Numeric types used for keys obey the normal rules for numeric\n      comparison: if two numbers compare equal (e.g., ``1`` and\n      ``1.0``) then they can be used interchangeably to index the same\n      dictionary entry.\n\n      Dictionaries are mutable; they can be created by the ``{...}``\n      notation (see section *Dictionary displays*).\n\n      The extension modules ``dbm.ndbm`` and ``dbm.gnu`` provide\n      additional examples of mapping types, as does the\n      ``collections`` module.\n\nCallable types\n   These are the types to which the function call operation (see\n   section *Calls*) can be applied:\n\n   User-defined functions\n      A user-defined function object is created by a function\n      definition (see section *Function definitions*).  It should be\n      called with an argument list containing the same number of items\n      as the function\'s formal parameter list.\n\n      Special attributes:\n\n      +---------------------------+---------------------------------+-------------+\n      | Attribute                 | Meaning                         |             |\n      +===========================+=================================+=============+\n      | ``__doc__``               | The function\'s documentation    | Writable    |\n      |                           | string, or ``None`` if          |             |\n      |                           | unavailable                     |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__name__``              | The function\'s name             | Writable    |\n      +---------------------------+---------------------------------+-------------+\n      | ``__module__``            | The name of the module the      | Writable    |\n      |                           | function was defined in, or     |             |\n      |                           | ``None`` if unavailable.        |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__defaults__``          | A tuple containing default      | Writable    |\n      |                           | argument values for those       |             |\n      |                           | arguments that have defaults,   |             |\n      |                           | or ``None`` if no arguments     |             |\n      |                           | have a default value            |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__code__``              | The code object representing    | Writable    |\n      |                           | the compiled function body.     |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__globals__``           | A reference to the dictionary   | Read-only   |\n      |                           | that holds the function\'s       |             |\n      |                           | global variables --- the global |             |\n      |                           | namespace of the module in      |             |\n      |                           | which the function was defined. |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__dict__``              | The namespace supporting        | Writable    |\n      |                           | arbitrary function attributes.  |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__closure__``           | ``None`` or a tuple of cells    | Read-only   |\n      |                           | that contain bindings for the   |             |\n      |                           | function\'s free variables.      |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__annotations__``       | A dict containing annotations   | Writable    |\n      |                           | of parameters.  The keys of the |             |\n      |                           | dict are the parameter names,   |             |\n      |                           | or ``\'return\'`` for the return  |             |\n      |                           | annotation, if provided.        |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__kwdefaults__``        | A dict containing defaults for  | Writable    |\n      |                           | keyword-only parameters.        |             |\n      +---------------------------+---------------------------------+-------------+\n\n      Most of the attributes labelled "Writable" check the type of the\n      assigned value.\n\n      Function objects also support getting and setting arbitrary\n      attributes, which can be used, for example, to attach metadata\n      to functions.  Regular attribute dot-notation is used to get and\n      set such attributes. *Note that the current implementation only\n      supports function attributes on user-defined functions. Function\n      attributes on built-in functions may be supported in the\n      future.*\n\n      Additional information about a function\'s definition can be\n      retrieved from its code object; see the description of internal\n      types below.\n\n   Instance methods\n      An instance method object combines a class, a class instance and\n      any callable object (normally a user-defined function).\n\n      Special read-only attributes: ``__self__`` is the class instance\n      object, ``__func__`` is the function object; ``__doc__`` is the\n      method\'s documentation (same as ``__func__.__doc__``);\n      ``__name__`` is the method name (same as ``__func__.__name__``);\n      ``__module__`` is the name of the module the method was defined\n      in, or ``None`` if unavailable.\n\n      Methods also support accessing (but not setting) the arbitrary\n      function attributes on the underlying function object.\n\n      User-defined method objects may be created when getting an\n      attribute of a class (perhaps via an instance of that class), if\n      that attribute is a user-defined function object or a class\n      method object.\n\n      When an instance method object is created by retrieving a user-\n      defined function object from a class via one of its instances,\n      its ``__self__`` attribute is the instance, and the method\n      object is said to be bound.  The new method\'s ``__func__``\n      attribute is the original function object.\n\n      When a user-defined method object is created by retrieving\n      another method object from a class or instance, the behaviour is\n      the same as for a function object, except that the ``__func__``\n      attribute of the new instance is not the original method object\n      but its ``__func__`` attribute.\n\n      When an instance method object is created by retrieving a class\n      method object from a class or instance, its ``__self__``\n      attribute is the class itself, and its ``__func__`` attribute is\n      the function object underlying the class method.\n\n      When an instance method object is called, the underlying\n      function (``__func__``) is called, inserting the class instance\n      (``__self__``) in front of the argument list.  For instance,\n      when ``C`` is a class which contains a definition for a function\n      ``f()``, and ``x`` is an instance of ``C``, calling ``x.f(1)``\n      is equivalent to calling ``C.f(x, 1)``.\n\n      When an instance method object is derived from a class method\n      object, the "class instance" stored in ``__self__`` will\n      actually be the class itself, so that calling either ``x.f(1)``\n      or ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\n      the underlying function.\n\n      Note that the transformation from function object to instance\n      method object happens each time the attribute is retrieved from\n      the instance.  In some cases, a fruitful optimization is to\n      assign the attribute to a local variable and call that local\n      variable. Also notice that this transformation only happens for\n      user-defined functions; other callable objects (and all non-\n      callable objects) are retrieved without transformation.  It is\n      also important to note that user-defined functions which are\n      attributes of a class instance are not converted to bound\n      methods; this *only* happens when the function is an attribute\n      of the class.\n\n   Generator functions\n      A function or method which uses the ``yield`` statement (see\n      section *The yield statement*) is called a *generator function*.\n      Such a function, when called, always returns an iterator object\n      which can be used to execute the body of the function:  calling\n      the iterator\'s ``__next__()`` method will cause the function to\n      execute until it provides a value using the ``yield`` statement.\n      When the function executes a ``return`` statement or falls off\n      the end, a ``StopIteration`` exception is raised and the\n      iterator will have reached the end of the set of values to be\n      returned.\n\n   Built-in functions\n      A built-in function object is a wrapper around a C function.\n      Examples of built-in functions are ``len()`` and ``math.sin()``\n      (``math`` is a standard built-in module). The number and type of\n      the arguments are determined by the C function. Special read-\n      only attributes: ``__doc__`` is the function\'s documentation\n      string, or ``None`` if unavailable; ``__name__`` is the\n      function\'s name; ``__self__`` is set to ``None`` (but see the\n      next item); ``__module__`` is the name of the module the\n      function was defined in or ``None`` if unavailable.\n\n   Built-in methods\n      This is really a different disguise of a built-in function, this\n      time containing an object passed to the C function as an\n      implicit extra argument.  An example of a built-in method is\n      ``alist.append()``, assuming *alist* is a list object. In this\n      case, the special read-only attribute ``__self__`` is set to the\n      object denoted by *list*.\n\n   Classes\n      Classes are callable.  These objects normally act as factories\n      for new instances of themselves, but variations are possible for\n      class types that override ``__new__()``.  The arguments of the\n      call are passed to ``__new__()`` and, in the typical case, to\n      ``__init__()`` to initialize the new instance.\n\n   Class Instances\n      Instances of arbitrary classes can be made callable by defining\n      a ``__call__()`` method in their class.\n\nModules\n   Modules are imported by the ``import`` statement (see section *The\n   import statement*). A module object has a namespace implemented by\n   a dictionary object (this is the dictionary referenced by the\n   __globals__ attribute of functions defined in the module).\n   Attribute references are translated to lookups in this dictionary,\n   e.g., ``m.x`` is equivalent to ``m.__dict__["x"]``. A module object\n   does not contain the code object used to initialize the module\n   (since it isn\'t needed once the initialization is done).\n\n   Attribute assignment updates the module\'s namespace dictionary,\n   e.g., ``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``.\n\n   Special read-only attribute: ``__dict__`` is the module\'s namespace\n   as a dictionary object.\n\n   Predefined (writable) attributes: ``__name__`` is the module\'s\n   name; ``__doc__`` is the module\'s documentation string, or ``None``\n   if unavailable; ``__file__`` is the pathname of the file from which\n   the module was loaded, if it was loaded from a file. The\n   ``__file__`` attribute is not present for C modules that are\n   statically linked into the interpreter; for extension modules\n   loaded dynamically from a shared library, it is the pathname of the\n   shared library file.\n\nCustom classes\n   Custom class types are typically created by class definitions (see\n   section *Class definitions*).  A class has a namespace implemented\n   by a dictionary object. Class attribute references are translated\n   to lookups in this dictionary, e.g., ``C.x`` is translated to\n   ``C.__dict__["x"]`` (although there are a number of hooks which\n   allow for other means of locating attributes). When the attribute\n   name is not found there, the attribute search continues in the base\n   classes. This search of the base classes uses the C3 method\n   resolution order which behaves correctly even in the presence of\n   \'diamond\' inheritance structures where there are multiple\n   inheritance paths leading back to a common ancestor. Additional\n   details on the C3 MRO used by Python can be found in the\n   documentation accompanying the 2.3 release at\n   http://www.python.org/download/releases/2.3/mro/.\n\n   When a class attribute reference (for class ``C``, say) would yield\n   a class method object, it is transformed into an instance method\n   object whose ``__self__`` attributes is ``C``.  When it would yield\n   a static method object, it is transformed into the object wrapped\n   by the static method object. See section *Implementing Descriptors*\n   for another way in which attributes retrieved from a class may\n   differ from those actually contained in its ``__dict__``.\n\n   Class attribute assignments update the class\'s dictionary, never\n   the dictionary of a base class.\n\n   A class object can be called (see above) to yield a class instance\n   (see below).\n\n   Special attributes: ``__name__`` is the class name; ``__module__``\n   is the module name in which the class was defined; ``__dict__`` is\n   the dictionary containing the class\'s namespace; ``__bases__`` is a\n   tuple (possibly empty or a singleton) containing the base classes,\n   in the order of their occurrence in the base class list;\n   ``__doc__`` is the class\'s documentation string, or None if\n   undefined.\n\nClass instances\n   A class instance is created by calling a class object (see above).\n   A class instance has a namespace implemented as a dictionary which\n   is the first place in which attribute references are searched.\n   When an attribute is not found there, and the instance\'s class has\n   an attribute by that name, the search continues with the class\n   attributes.  If a class attribute is found that is a user-defined\n   function object, it is transformed into an instance method object\n   whose ``__self__`` attribute is the instance.  Static method and\n   class method objects are also transformed; see above under\n   "Classes".  See section *Implementing Descriptors* for another way\n   in which attributes of a class retrieved via its instances may\n   differ from the objects actually stored in the class\'s\n   ``__dict__``.  If no class attribute is found, and the object\'s\n   class has a ``__getattr__()`` method, that is called to satisfy the\n   lookup.\n\n   Attribute assignments and deletions update the instance\'s\n   dictionary, never a class\'s dictionary.  If the class has a\n   ``__setattr__()`` or ``__delattr__()`` method, this is called\n   instead of updating the instance dictionary directly.\n\n   Class instances can pretend to be numbers, sequences, or mappings\n   if they have methods with certain special names.  See section\n   *Special method names*.\n\n   Special attributes: ``__dict__`` is the attribute dictionary;\n   ``__class__`` is the instance\'s class.\n\nI/O objects (also known as file objects)\n   A *file object* represents an open file.  Various shortcuts are\n   available to create file objects: the ``open()`` built-in function,\n   and also ``os.popen()``, ``os.fdopen()``, and the ``makefile()``\n   method of socket objects (and perhaps by other functions or methods\n   provided by extension modules).\n\n   The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are\n   initialized to file objects corresponding to the interpreter\'s\n   standard input, output and error streams; they are all open in text\n   mode and therefore follow the interface defined by the\n   ``io.TextIOBase`` abstract class.\n\nInternal types\n   A few types used internally by the interpreter are exposed to the\n   user. Their definitions may change with future versions of the\n   interpreter, but they are mentioned here for completeness.\n\n   Code objects\n      Code objects represent *byte-compiled* executable Python code,\n      or *bytecode*. The difference between a code object and a\n      function object is that the function object contains an explicit\n      reference to the function\'s globals (the module in which it was\n      defined), while a code object contains no context; also the\n      default argument values are stored in the function object, not\n      in the code object (because they represent values calculated at\n      run-time).  Unlike function objects, code objects are immutable\n      and contain no references (directly or indirectly) to mutable\n      objects.\n\n      Special read-only attributes: ``co_name`` gives the function\n      name; ``co_argcount`` is the number of positional arguments\n      (including arguments with default values); ``co_nlocals`` is the\n      number of local variables used by the function (including\n      arguments); ``co_varnames`` is a tuple containing the names of\n      the local variables (starting with the argument names);\n      ``co_cellvars`` is a tuple containing the names of local\n      variables that are referenced by nested functions;\n      ``co_freevars`` is a tuple containing the names of free\n      variables; ``co_code`` is a string representing the sequence of\n      bytecode instructions; ``co_consts`` is a tuple containing the\n      literals used by the bytecode; ``co_names`` is a tuple\n      containing the names used by the bytecode; ``co_filename`` is\n      the filename from which the code was compiled;\n      ``co_firstlineno`` is the first line number of the function;\n      ``co_lnotab`` is a string encoding the mapping from bytecode\n      offsets to line numbers (for details see the source code of the\n      interpreter); ``co_stacksize`` is the required stack size\n      (including local variables); ``co_flags`` is an integer encoding\n      a number of flags for the interpreter.\n\n      The following flag bits are defined for ``co_flags``: bit\n      ``0x04`` is set if the function uses the ``*arguments`` syntax\n      to accept an arbitrary number of positional arguments; bit\n      ``0x08`` is set if the function uses the ``**keywords`` syntax\n      to accept arbitrary keyword arguments; bit ``0x20`` is set if\n      the function is a generator.\n\n      Future feature declarations (``from __future__ import\n      division``) also use bits in ``co_flags`` to indicate whether a\n      code object was compiled with a particular feature enabled: bit\n      ``0x2000`` is set if the function was compiled with future\n      division enabled; bits ``0x10`` and ``0x1000`` were used in\n      earlier versions of Python.\n\n      Other bits in ``co_flags`` are reserved for internal use.\n\n      If a code object represents a function, the first item in\n      ``co_consts`` is the documentation string of the function, or\n      ``None`` if undefined.\n\n   Frame objects\n      Frame objects represent execution frames.  They may occur in\n      traceback objects (see below).\n\n      Special read-only attributes: ``f_back`` is to the previous\n      stack frame (towards the caller), or ``None`` if this is the\n      bottom stack frame; ``f_code`` is the code object being executed\n      in this frame; ``f_locals`` is the dictionary used to look up\n      local variables; ``f_globals`` is used for global variables;\n      ``f_builtins`` is used for built-in (intrinsic) names;\n      ``f_lasti`` gives the precise instruction (this is an index into\n      the bytecode string of the code object).\n\n      Special writable attributes: ``f_trace``, if not ``None``, is a\n      function called at the start of each source code line (this is\n      used by the debugger); ``f_lineno`` is the current line number\n      of the frame --- writing to this from within a trace function\n      jumps to the given line (only for the bottom-most frame).  A\n      debugger can implement a Jump command (aka Set Next Statement)\n      by writing to f_lineno.\n\n   Traceback objects\n      Traceback objects represent a stack trace of an exception.  A\n      traceback object is created when an exception occurs.  When the\n      search for an exception handler unwinds the execution stack, at\n      each unwound level a traceback object is inserted in front of\n      the current traceback.  When an exception handler is entered,\n      the stack trace is made available to the program. (See section\n      *The try statement*.) It is accessible as the third item of the\n      tuple returned by ``sys.exc_info()``. When the program contains\n      no suitable handler, the stack trace is written (nicely\n      formatted) to the standard error stream; if the interpreter is\n      interactive, it is also made available to the user as\n      ``sys.last_traceback``.\n\n      Special read-only attributes: ``tb_next`` is the next level in\n      the stack trace (towards the frame where the exception\n      occurred), or ``None`` if there is no next level; ``tb_frame``\n      points to the execution frame of the current level;\n      ``tb_lineno`` gives the line number where the exception\n      occurred; ``tb_lasti`` indicates the precise instruction.  The\n      line number and last instruction in the traceback may differ\n      from the line number of its frame object if the exception\n      occurred in a ``try`` statement with no matching except clause\n      or with a finally clause.\n\n   Slice objects\n      Slice objects are used to represent slices for ``__getitem__()``\n      methods.  They are also created by the built-in ``slice()``\n      function.\n\n      Special read-only attributes: ``start`` is the lower bound;\n      ``stop`` is the upper bound; ``step`` is the step value; each is\n      ``None`` if omitted. These attributes can have any type.\n\n      Slice objects support one method:\n\n      slice.indices(self, length)\n\n         This method takes a single integer argument *length* and\n         computes information about the slice that the slice object\n         would describe if applied to a sequence of *length* items.\n         It returns a tuple of three integers; respectively these are\n         the *start* and *stop* indices and the *step* or stride\n         length of the slice. Missing or out-of-bounds indices are\n         handled in a manner consistent with regular slices.\n\n   Static method objects\n      Static method objects provide a way of defeating the\n      transformation of function objects to method objects described\n      above. A static method object is a wrapper around any other\n      object, usually a user-defined method object. When a static\n      method object is retrieved from a class or a class instance, the\n      object actually returned is the wrapped object, which is not\n      subject to any further transformation. Static method objects are\n      not themselves callable, although the objects they wrap usually\n      are. Static method objects are created by the built-in\n      ``staticmethod()`` constructor.\n\n   Class method objects\n      A class method object, like a static method object, is a wrapper\n      around another object that alters the way in which that object\n      is retrieved from classes and class instances. The behaviour of\n      class method objects upon such retrieval is described above,\n      under "User-defined methods". Class method objects are created\n      by the built-in ``classmethod()`` constructor.\n',
+ 'try': '\nThe ``try`` statement\n*********************\n\nThe ``try`` statement specifies exception handlers and/or cleanup code\nfor a group of statements:\n\n   try_stmt  ::= try1_stmt | try2_stmt\n   try1_stmt ::= "try" ":" suite\n                 ("except" [expression ["as" target]] ":" suite)+\n                 ["else" ":" suite]\n                 ["finally" ":" suite]\n   try2_stmt ::= "try" ":" suite\n                 "finally" ":" suite\n\nThe ``except`` clause(s) specify one or more exception handlers. When\nno exception occurs in the ``try`` clause, no exception handler is\nexecuted. When an exception occurs in the ``try`` suite, a search for\nan exception handler is started.  This search inspects the except\nclauses in turn until one is found that matches the exception.  An\nexpression-less except clause, if present, must be last; it matches\nany exception.  For an except clause with an expression, that\nexpression is evaluated, and the clause matches the exception if the\nresulting object is "compatible" with the exception.  An object is\ncompatible with an exception if it is the class or a base class of the\nexception object or a tuple containing an item compatible with the\nexception.\n\nIf no except clause matches the exception, the search for an exception\nhandler continues in the surrounding code and on the invocation stack.\n[1]\n\nIf the evaluation of an expression in the header of an except clause\nraises an exception, the original search for a handler is canceled and\na search starts for the new exception in the surrounding code and on\nthe call stack (it is treated as if the entire ``try`` statement\nraised the exception).\n\nWhen a matching except clause is found, the exception is assigned to\nthe target specified after the ``as`` keyword in that except clause,\nif present, and the except clause\'s suite is executed.  All except\nclauses must have an executable block.  When the end of this block is\nreached, execution continues normally after the entire try statement.\n(This means that if two nested handlers exist for the same exception,\nand the exception occurs in the try clause of the inner handler, the\nouter handler will not handle the exception.)\n\nWhen an exception has been assigned using ``as target``, it is cleared\nat the end of the except clause.  This is as if\n\n   except E as N:\n       foo\n\nwas translated to\n\n   except E as N:\n       try:\n           foo\n       finally:\n           del N\n\nThis means the exception must be assigned to a different name to be\nable to refer to it after the except clause.  Exceptions are cleared\nbecause with the traceback attached to them, they form a reference\ncycle with the stack frame, keeping all locals in that frame alive\nuntil the next garbage collection occurs.\n\nBefore an except clause\'s suite is executed, details about the\nexception are stored in the ``sys`` module and can be access via\n``sys.exc_info()``. ``sys.exc_info()`` returns a 3-tuple consisting of\nthe exception class, the exception instance and a traceback object\n(see section *The standard type hierarchy*) identifying the point in\nthe program where the exception occurred.  ``sys.exc_info()`` values\nare restored to their previous values (before the call) when returning\nfrom a function that handled an exception.\n\nThe optional ``else`` clause is executed if and when control flows off\nthe end of the ``try`` clause. [2] Exceptions in the ``else`` clause\nare not handled by the preceding ``except`` clauses.\n\nIf ``finally`` is present, it specifies a \'cleanup\' handler.  The\n``try`` clause is executed, including any ``except`` and ``else``\nclauses.  If an exception occurs in any of the clauses and is not\nhandled, the exception is temporarily saved. The ``finally`` clause is\nexecuted.  If there is a saved exception, it is re-raised at the end\nof the ``finally`` clause. If the ``finally`` clause raises another\nexception or executes a ``return`` or ``break`` statement, the saved\nexception is lost.  The exception information is not available to the\nprogram during execution of the ``finally`` clause.\n\nWhen a ``return``, ``break`` or ``continue`` statement is executed in\nthe ``try`` suite of a ``try``...``finally`` statement, the\n``finally`` clause is also executed \'on the way out.\' A ``continue``\nstatement is illegal in the ``finally`` clause. (The reason is a\nproblem with the current implementation --- this restriction may be\nlifted in the future).\n\nAdditional information on exceptions can be found in section\n*Exceptions*, and information on using the ``raise`` statement to\ngenerate exceptions may be found in section *The raise statement*.\n',
+ 'types': '\nThe standard type hierarchy\n***************************\n\nBelow is a list of the types that are built into Python.  Extension\nmodules (written in C, Java, or other languages, depending on the\nimplementation) can define additional types.  Future versions of\nPython may add types to the type hierarchy (e.g., rational numbers,\nefficiently stored arrays of integers, etc.), although such additions\nwill often be provided via the standard library instead.\n\nSome of the type descriptions below contain a paragraph listing\n\'special attributes.\'  These are attributes that provide access to the\nimplementation and are not intended for general use.  Their definition\nmay change in the future.\n\nNone\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the built-in name ``None``.\n   It is used to signify the absence of a value in many situations,\n   e.g., it is returned from functions that don\'t explicitly return\n   anything. Its truth value is false.\n\nNotImplemented\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the built-in name\n   ``NotImplemented``. Numeric methods and rich comparison methods may\n   return this value if they do not implement the operation for the\n   operands provided.  (The interpreter will then try the reflected\n   operation, or some other fallback, depending on the operator.)  Its\n   truth value is true.\n\nEllipsis\n   This type has a single value.  There is a single object with this\n   value. This object is accessed through the literal ``...`` or the\n   built-in name ``Ellipsis``.  Its truth value is true.\n\n``numbers.Number``\n   These are created by numeric literals and returned as results by\n   arithmetic operators and arithmetic built-in functions.  Numeric\n   objects are immutable; once created their value never changes.\n   Python numbers are of course strongly related to mathematical\n   numbers, but subject to the limitations of numerical representation\n   in computers.\n\n   Python distinguishes between integers, floating point numbers, and\n   complex numbers:\n\n   ``numbers.Integral``\n      These represent elements from the mathematical set of integers\n      (positive and negative).\n\n      There are two types of integers:\n\n      Integers (``int``)\n\n         These represent numbers in an unlimited range, subject to\n         available (virtual) memory only.  For the purpose of shift\n         and mask operations, a binary representation is assumed, and\n         negative numbers are represented in a variant of 2\'s\n         complement which gives the illusion of an infinite string of\n         sign bits extending to the left.\n\n      Booleans (``bool``)\n         These represent the truth values False and True.  The two\n         objects representing the values False and True are the only\n         Boolean objects. The Boolean type is a subtype of the integer\n         type, and Boolean values behave like the values 0 and 1,\n         respectively, in almost all contexts, the exception being\n         that when converted to a string, the strings ``"False"`` or\n         ``"True"`` are returned, respectively.\n\n      The rules for integer representation are intended to give the\n      most meaningful interpretation of shift and mask operations\n      involving negative integers.\n\n   ``numbers.Real`` (``float``)\n      These represent machine-level double precision floating point\n      numbers. You are at the mercy of the underlying machine\n      architecture (and C or Java implementation) for the accepted\n      range and handling of overflow. Python does not support single-\n      precision floating point numbers; the savings in processor and\n      memory usage that are usually the reason for using these is\n      dwarfed by the overhead of using objects in Python, so there is\n      no reason to complicate the language with two kinds of floating\n      point numbers.\n\n   ``numbers.Complex`` (``complex``)\n      These represent complex numbers as a pair of machine-level\n      double precision floating point numbers.  The same caveats apply\n      as for floating point numbers. The real and imaginary parts of a\n      complex number ``z`` can be retrieved through the read-only\n      attributes ``z.real`` and ``z.imag``.\n\nSequences\n   These represent finite ordered sets indexed by non-negative\n   numbers. The built-in function ``len()`` returns the number of\n   items of a sequence. When the length of a sequence is *n*, the\n   index set contains the numbers 0, 1, ..., *n*-1.  Item *i* of\n   sequence *a* is selected by ``a[i]``.\n\n   Sequences also support slicing: ``a[i:j]`` selects all items with\n   index *k* such that *i* ``<=`` *k* ``<`` *j*.  When used as an\n   expression, a slice is a sequence of the same type.  This implies\n   that the index set is renumbered so that it starts at 0.\n\n   Some sequences also support "extended slicing" with a third "step"\n   parameter: ``a[i:j:k]`` selects all items of *a* with index *x*\n   where ``x = i + n*k``, *n* ``>=`` ``0`` and *i* ``<=`` *x* ``<``\n   *j*.\n\n   Sequences are distinguished according to their mutability:\n\n   Immutable sequences\n      An object of an immutable sequence type cannot change once it is\n      created.  (If the object contains references to other objects,\n      these other objects may be mutable and may be changed; however,\n      the collection of objects directly referenced by an immutable\n      object cannot change.)\n\n      The following types are immutable sequences:\n\n      Strings\n         The items of a string object are Unicode code units.  A\n         Unicode code unit is represented by a string object of one\n         item and can hold either a 16-bit or 32-bit value\n         representing a Unicode ordinal (the maximum value for the\n         ordinal is given in ``sys.maxunicode``, and depends on how\n         Python is configured at compile time).  Surrogate pairs may\n         be present in the Unicode object, and will be reported as two\n         separate items.  The built-in functions ``chr()`` and\n         ``ord()`` convert between code units and nonnegative integers\n         representing the Unicode ordinals as defined in the Unicode\n         Standard 3.0. Conversion from and to other encodings are\n         possible through the string method ``encode()``.\n\n      Tuples\n         The items of a tuple are arbitrary Python objects. Tuples of\n         two or more items are formed by comma-separated lists of\n         expressions.  A tuple of one item (a \'singleton\') can be\n         formed by affixing a comma to an expression (an expression by\n         itself does not create a tuple, since parentheses must be\n         usable for grouping of expressions).  An empty tuple can be\n         formed by an empty pair of parentheses.\n\n      Bytes\n         A bytes object is an immutable array.  The items are 8-bit\n         bytes, represented by integers in the range 0 <= x < 256.\n         Bytes literals (like ``b\'abc\'`` and the built-in function\n         ``bytes()`` can be used to construct bytes objects.  Also,\n         bytes objects can be decoded to strings via the ``decode()``\n         method.\n\n   Mutable sequences\n      Mutable sequences can be changed after they are created.  The\n      subscription and slicing notations can be used as the target of\n      assignment and ``del`` (delete) statements.\n\n      There are currently two intrinsic mutable sequence types:\n\n      Lists\n         The items of a list are arbitrary Python objects.  Lists are\n         formed by placing a comma-separated list of expressions in\n         square brackets. (Note that there are no special cases needed\n         to form lists of length 0 or 1.)\n\n      Byte Arrays\n         A bytearray object is a mutable array. They are created by\n         the built-in ``bytearray()`` constructor.  Aside from being\n         mutable (and hence unhashable), byte arrays otherwise provide\n         the same interface and functionality as immutable bytes\n         objects.\n\n      The extension module ``array`` provides an additional example of\n      a mutable sequence type, as does the ``collections`` module.\n\nSet types\n   These represent unordered, finite sets of unique, immutable\n   objects. As such, they cannot be indexed by any subscript. However,\n   they can be iterated over, and the built-in function ``len()``\n   returns the number of items in a set. Common uses for sets are fast\n   membership testing, removing duplicates from a sequence, and\n   computing mathematical operations such as intersection, union,\n   difference, and symmetric difference.\n\n   For set elements, the same immutability rules apply as for\n   dictionary keys. Note that numeric types obey the normal rules for\n   numeric comparison: if two numbers compare equal (e.g., ``1`` and\n   ``1.0``), only one of them can be contained in a set.\n\n   There are currently two intrinsic set types:\n\n   Sets\n      These represent a mutable set. They are created by the built-in\n      ``set()`` constructor and can be modified afterwards by several\n      methods, such as ``add()``.\n\n   Frozen sets\n      These represent an immutable set.  They are created by the\n      built-in ``frozenset()`` constructor.  As a frozenset is\n      immutable and *hashable*, it can be used again as an element of\n      another set, or as a dictionary key.\n\nMappings\n   These represent finite sets of objects indexed by arbitrary index\n   sets. The subscript notation ``a[k]`` selects the item indexed by\n   ``k`` from the mapping ``a``; this can be used in expressions and\n   as the target of assignments or ``del`` statements. The built-in\n   function ``len()`` returns the number of items in a mapping.\n\n   There is currently a single intrinsic mapping type:\n\n   Dictionaries\n      These represent finite sets of objects indexed by nearly\n      arbitrary values.  The only types of values not acceptable as\n      keys are values containing lists or dictionaries or other\n      mutable types that are compared by value rather than by object\n      identity, the reason being that the efficient implementation of\n      dictionaries requires a key\'s hash value to remain constant.\n      Numeric types used for keys obey the normal rules for numeric\n      comparison: if two numbers compare equal (e.g., ``1`` and\n      ``1.0``) then they can be used interchangeably to index the same\n      dictionary entry.\n\n      Dictionaries are mutable; they can be created by the ``{...}``\n      notation (see section *Dictionary displays*).\n\n      The extension modules ``dbm.ndbm`` and ``dbm.gnu`` provide\n      additional examples of mapping types, as does the\n      ``collections`` module.\n\nCallable types\n   These are the types to which the function call operation (see\n   section *Calls*) can be applied:\n\n   User-defined functions\n      A user-defined function object is created by a function\n      definition (see section *Function definitions*).  It should be\n      called with an argument list containing the same number of items\n      as the function\'s formal parameter list.\n\n      Special attributes:\n\n      +---------------------------+---------------------------------+-------------+\n      | Attribute                 | Meaning                         |             |\n      +===========================+=================================+=============+\n      | ``__doc__``               | The function\'s documentation    | Writable    |\n      |                           | string, or ``None`` if          |             |\n      |                           | unavailable                     |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__name__``              | The function\'s name             | Writable    |\n      +---------------------------+---------------------------------+-------------+\n      | ``__module__``            | The name of the module the      | Writable    |\n      |                           | function was defined in, or     |             |\n      |                           | ``None`` if unavailable.        |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__defaults__``          | A tuple containing default      | Writable    |\n      |                           | argument values for those       |             |\n      |                           | arguments that have defaults,   |             |\n      |                           | or ``None`` if no arguments     |             |\n      |                           | have a default value            |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__code__``              | The code object representing    | Writable    |\n      |                           | the compiled function body.     |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__globals__``           | A reference to the dictionary   | Read-only   |\n      |                           | that holds the function\'s       |             |\n      |                           | global variables --- the global |             |\n      |                           | namespace of the module in      |             |\n      |                           | which the function was defined. |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__dict__``              | The namespace supporting        | Writable    |\n      |                           | arbitrary function attributes.  |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__closure__``           | ``None`` or a tuple of cells    | Read-only   |\n      |                           | that contain bindings for the   |             |\n      |                           | function\'s free variables.      |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__annotations__``       | A dict containing annotations   | Writable    |\n      |                           | of parameters.  The keys of the |             |\n      |                           | dict are the parameter names,   |             |\n      |                           | or ``\'return\'`` for the return  |             |\n      |                           | annotation, if provided.        |             |\n      +---------------------------+---------------------------------+-------------+\n      | ``__kwdefaults__``        | A dict containing defaults for  | Writable    |\n      |                           | keyword-only parameters.        |             |\n      +---------------------------+---------------------------------+-------------+\n\n      Most of the attributes labelled "Writable" check the type of the\n      assigned value.\n\n      Function objects also support getting and setting arbitrary\n      attributes, which can be used, for example, to attach metadata\n      to functions.  Regular attribute dot-notation is used to get and\n      set such attributes. *Note that the current implementation only\n      supports function attributes on user-defined functions. Function\n      attributes on built-in functions may be supported in the\n      future.*\n\n      Additional information about a function\'s definition can be\n      retrieved from its code object; see the description of internal\n      types below.\n\n   Instance methods\n      An instance method object combines a class, a class instance and\n      any callable object (normally a user-defined function).\n\n      Special read-only attributes: ``__self__`` is the class instance\n      object, ``__func__`` is the function object; ``__doc__`` is the\n      method\'s documentation (same as ``__func__.__doc__``);\n      ``__name__`` is the method name (same as ``__func__.__name__``);\n      ``__module__`` is the name of the module the method was defined\n      in, or ``None`` if unavailable.\n\n      Methods also support accessing (but not setting) the arbitrary\n      function attributes on the underlying function object.\n\n      User-defined method objects may be created when getting an\n      attribute of a class (perhaps via an instance of that class), if\n      that attribute is a user-defined function object or a class\n      method object.\n\n      When an instance method object is created by retrieving a user-\n      defined function object from a class via one of its instances,\n      its ``__self__`` attribute is the instance, and the method\n      object is said to be bound.  The new method\'s ``__func__``\n      attribute is the original function object.\n\n      When a user-defined method object is created by retrieving\n      another method object from a class or instance, the behaviour is\n      the same as for a function object, except that the ``__func__``\n      attribute of the new instance is not the original method object\n      but its ``__func__`` attribute.\n\n      When an instance method object is created by retrieving a class\n      method object from a class or instance, its ``__self__``\n      attribute is the class itself, and its ``__func__`` attribute is\n      the function object underlying the class method.\n\n      When an instance method object is called, the underlying\n      function (``__func__``) is called, inserting the class instance\n      (``__self__``) in front of the argument list.  For instance,\n      when ``C`` is a class which contains a definition for a function\n      ``f()``, and ``x`` is an instance of ``C``, calling ``x.f(1)``\n      is equivalent to calling ``C.f(x, 1)``.\n\n      When an instance method object is derived from a class method\n      object, the "class instance" stored in ``__self__`` will\n      actually be the class itself, so that calling either ``x.f(1)``\n      or ``C.f(1)`` is equivalent to calling ``f(C,1)`` where ``f`` is\n      the underlying function.\n\n      Note that the transformation from function object to instance\n      method object happens each time the attribute is retrieved from\n      the instance.  In some cases, a fruitful optimization is to\n      assign the attribute to a local variable and call that local\n      variable. Also notice that this transformation only happens for\n      user-defined functions; other callable objects (and all non-\n      callable objects) are retrieved without transformation.  It is\n      also important to note that user-defined functions which are\n      attributes of a class instance are not converted to bound\n      methods; this *only* happens when the function is an attribute\n      of the class.\n\n   Generator functions\n      A function or method which uses the ``yield`` statement (see\n      section *The yield statement*) is called a *generator function*.\n      Such a function, when called, always returns an iterator object\n      which can be used to execute the body of the function:  calling\n      the iterator\'s ``__next__()`` method will cause the function to\n      execute until it provides a value using the ``yield`` statement.\n      When the function executes a ``return`` statement or falls off\n      the end, a ``StopIteration`` exception is raised and the\n      iterator will have reached the end of the set of values to be\n      returned.\n\n   Built-in functions\n      A built-in function object is a wrapper around a C function.\n      Examples of built-in functions are ``len()`` and ``math.sin()``\n      (``math`` is a standard built-in module). The number and type of\n      the arguments are determined by the C function. Special read-\n      only attributes: ``__doc__`` is the function\'s documentation\n      string, or ``None`` if unavailable; ``__name__`` is the\n      function\'s name; ``__self__`` is set to ``None`` (but see the\n      next item); ``__module__`` is the name of the module the\n      function was defined in or ``None`` if unavailable.\n\n   Built-in methods\n      This is really a different disguise of a built-in function, this\n      time containing an object passed to the C function as an\n      implicit extra argument.  An example of a built-in method is\n      ``alist.append()``, assuming *alist* is a list object. In this\n      case, the special read-only attribute ``__self__`` is set to the\n      object denoted by *alist*.\n\n   Classes\n      Classes are callable.  These objects normally act as factories\n      for new instances of themselves, but variations are possible for\n      class types that override ``__new__()``.  The arguments of the\n      call are passed to ``__new__()`` and, in the typical case, to\n      ``__init__()`` to initialize the new instance.\n\n   Class Instances\n      Instances of arbitrary classes can be made callable by defining\n      a ``__call__()`` method in their class.\n\nModules\n   Modules are imported by the ``import`` statement (see section *The\n   import statement*). A module object has a namespace implemented by\n   a dictionary object (this is the dictionary referenced by the\n   __globals__ attribute of functions defined in the module).\n   Attribute references are translated to lookups in this dictionary,\n   e.g., ``m.x`` is equivalent to ``m.__dict__["x"]``. A module object\n   does not contain the code object used to initialize the module\n   (since it isn\'t needed once the initialization is done).\n\n   Attribute assignment updates the module\'s namespace dictionary,\n   e.g., ``m.x = 1`` is equivalent to ``m.__dict__["x"] = 1``.\n\n   Special read-only attribute: ``__dict__`` is the module\'s namespace\n   as a dictionary object.\n\n   **CPython implementation detail:** Because of the way CPython\n   clears module dictionaries, the module dictionary will be cleared\n   when the module falls out of scope even if the dictionary still has\n   live references.  To avoid this, copy the dictionary or keep the\n   module around while using its dictionary directly.\n\n   Predefined (writable) attributes: ``__name__`` is the module\'s\n   name; ``__doc__`` is the module\'s documentation string, or ``None``\n   if unavailable; ``__file__`` is the pathname of the file from which\n   the module was loaded, if it was loaded from a file. The\n   ``__file__`` attribute is not present for C modules that are\n   statically linked into the interpreter; for extension modules\n   loaded dynamically from a shared library, it is the pathname of the\n   shared library file.\n\nCustom classes\n   Custom class types are typically created by class definitions (see\n   section *Class definitions*).  A class has a namespace implemented\n   by a dictionary object. Class attribute references are translated\n   to lookups in this dictionary, e.g., ``C.x`` is translated to\n   ``C.__dict__["x"]`` (although there are a number of hooks which\n   allow for other means of locating attributes). When the attribute\n   name is not found there, the attribute search continues in the base\n   classes. This search of the base classes uses the C3 method\n   resolution order which behaves correctly even in the presence of\n   \'diamond\' inheritance structures where there are multiple\n   inheritance paths leading back to a common ancestor. Additional\n   details on the C3 MRO used by Python can be found in the\n   documentation accompanying the 2.3 release at\n   http://www.python.org/download/releases/2.3/mro/.\n\n   When a class attribute reference (for class ``C``, say) would yield\n   a class method object, it is transformed into an instance method\n   object whose ``__self__`` attributes is ``C``.  When it would yield\n   a static method object, it is transformed into the object wrapped\n   by the static method object. See section *Implementing Descriptors*\n   for another way in which attributes retrieved from a class may\n   differ from those actually contained in its ``__dict__``.\n\n   Class attribute assignments update the class\'s dictionary, never\n   the dictionary of a base class.\n\n   A class object can be called (see above) to yield a class instance\n   (see below).\n\n   Special attributes: ``__name__`` is the class name; ``__module__``\n   is the module name in which the class was defined; ``__dict__`` is\n   the dictionary containing the class\'s namespace; ``__bases__`` is a\n   tuple (possibly empty or a singleton) containing the base classes,\n   in the order of their occurrence in the base class list;\n   ``__doc__`` is the class\'s documentation string, or None if\n   undefined.\n\nClass instances\n   A class instance is created by calling a class object (see above).\n   A class instance has a namespace implemented as a dictionary which\n   is the first place in which attribute references are searched.\n   When an attribute is not found there, and the instance\'s class has\n   an attribute by that name, the search continues with the class\n   attributes.  If a class attribute is found that is a user-defined\n   function object, it is transformed into an instance method object\n   whose ``__self__`` attribute is the instance.  Static method and\n   class method objects are also transformed; see above under\n   "Classes".  See section *Implementing Descriptors* for another way\n   in which attributes of a class retrieved via its instances may\n   differ from the objects actually stored in the class\'s\n   ``__dict__``.  If no class attribute is found, and the object\'s\n   class has a ``__getattr__()`` method, that is called to satisfy the\n   lookup.\n\n   Attribute assignments and deletions update the instance\'s\n   dictionary, never a class\'s dictionary.  If the class has a\n   ``__setattr__()`` or ``__delattr__()`` method, this is called\n   instead of updating the instance dictionary directly.\n\n   Class instances can pretend to be numbers, sequences, or mappings\n   if they have methods with certain special names.  See section\n   *Special method names*.\n\n   Special attributes: ``__dict__`` is the attribute dictionary;\n   ``__class__`` is the instance\'s class.\n\nI/O objects (also known as file objects)\n   A *file object* represents an open file.  Various shortcuts are\n   available to create file objects: the ``open()`` built-in function,\n   and also ``os.popen()``, ``os.fdopen()``, and the ``makefile()``\n   method of socket objects (and perhaps by other functions or methods\n   provided by extension modules).\n\n   The objects ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are\n   initialized to file objects corresponding to the interpreter\'s\n   standard input, output and error streams; they are all open in text\n   mode and therefore follow the interface defined by the\n   ``io.TextIOBase`` abstract class.\n\nInternal types\n   A few types used internally by the interpreter are exposed to the\n   user. Their definitions may change with future versions of the\n   interpreter, but they are mentioned here for completeness.\n\n   Code objects\n      Code objects represent *byte-compiled* executable Python code,\n      or *bytecode*. The difference between a code object and a\n      function object is that the function object contains an explicit\n      reference to the function\'s globals (the module in which it was\n      defined), while a code object contains no context; also the\n      default argument values are stored in the function object, not\n      in the code object (because they represent values calculated at\n      run-time).  Unlike function objects, code objects are immutable\n      and contain no references (directly or indirectly) to mutable\n      objects.\n\n      Special read-only attributes: ``co_name`` gives the function\n      name; ``co_argcount`` is the number of positional arguments\n      (including arguments with default values); ``co_nlocals`` is the\n      number of local variables used by the function (including\n      arguments); ``co_varnames`` is a tuple containing the names of\n      the local variables (starting with the argument names);\n      ``co_cellvars`` is a tuple containing the names of local\n      variables that are referenced by nested functions;\n      ``co_freevars`` is a tuple containing the names of free\n      variables; ``co_code`` is a string representing the sequence of\n      bytecode instructions; ``co_consts`` is a tuple containing the\n      literals used by the bytecode; ``co_names`` is a tuple\n      containing the names used by the bytecode; ``co_filename`` is\n      the filename from which the code was compiled;\n      ``co_firstlineno`` is the first line number of the function;\n      ``co_lnotab`` is a string encoding the mapping from bytecode\n      offsets to line numbers (for details see the source code of the\n      interpreter); ``co_stacksize`` is the required stack size\n      (including local variables); ``co_flags`` is an integer encoding\n      a number of flags for the interpreter.\n\n      The following flag bits are defined for ``co_flags``: bit\n      ``0x04`` is set if the function uses the ``*arguments`` syntax\n      to accept an arbitrary number of positional arguments; bit\n      ``0x08`` is set if the function uses the ``**keywords`` syntax\n      to accept arbitrary keyword arguments; bit ``0x20`` is set if\n      the function is a generator.\n\n      Future feature declarations (``from __future__ import\n      division``) also use bits in ``co_flags`` to indicate whether a\n      code object was compiled with a particular feature enabled: bit\n      ``0x2000`` is set if the function was compiled with future\n      division enabled; bits ``0x10`` and ``0x1000`` were used in\n      earlier versions of Python.\n\n      Other bits in ``co_flags`` are reserved for internal use.\n\n      If a code object represents a function, the first item in\n      ``co_consts`` is the documentation string of the function, or\n      ``None`` if undefined.\n\n   Frame objects\n      Frame objects represent execution frames.  They may occur in\n      traceback objects (see below).\n\n      Special read-only attributes: ``f_back`` is to the previous\n      stack frame (towards the caller), or ``None`` if this is the\n      bottom stack frame; ``f_code`` is the code object being executed\n      in this frame; ``f_locals`` is the dictionary used to look up\n      local variables; ``f_globals`` is used for global variables;\n      ``f_builtins`` is used for built-in (intrinsic) names;\n      ``f_lasti`` gives the precise instruction (this is an index into\n      the bytecode string of the code object).\n\n      Special writable attributes: ``f_trace``, if not ``None``, is a\n      function called at the start of each source code line (this is\n      used by the debugger); ``f_lineno`` is the current line number\n      of the frame --- writing to this from within a trace function\n      jumps to the given line (only for the bottom-most frame).  A\n      debugger can implement a Jump command (aka Set Next Statement)\n      by writing to f_lineno.\n\n   Traceback objects\n      Traceback objects represent a stack trace of an exception.  A\n      traceback object is created when an exception occurs.  When the\n      search for an exception handler unwinds the execution stack, at\n      each unwound level a traceback object is inserted in front of\n      the current traceback.  When an exception handler is entered,\n      the stack trace is made available to the program. (See section\n      *The try statement*.) It is accessible as the third item of the\n      tuple returned by ``sys.exc_info()``. When the program contains\n      no suitable handler, the stack trace is written (nicely\n      formatted) to the standard error stream; if the interpreter is\n      interactive, it is also made available to the user as\n      ``sys.last_traceback``.\n\n      Special read-only attributes: ``tb_next`` is the next level in\n      the stack trace (towards the frame where the exception\n      occurred), or ``None`` if there is no next level; ``tb_frame``\n      points to the execution frame of the current level;\n      ``tb_lineno`` gives the line number where the exception\n      occurred; ``tb_lasti`` indicates the precise instruction.  The\n      line number and last instruction in the traceback may differ\n      from the line number of its frame object if the exception\n      occurred in a ``try`` statement with no matching except clause\n      or with a finally clause.\n\n   Slice objects\n      Slice objects are used to represent slices for ``__getitem__()``\n      methods.  They are also created by the built-in ``slice()``\n      function.\n\n      Special read-only attributes: ``start`` is the lower bound;\n      ``stop`` is the upper bound; ``step`` is the step value; each is\n      ``None`` if omitted. These attributes can have any type.\n\n      Slice objects support one method:\n\n      slice.indices(self, length)\n\n         This method takes a single integer argument *length* and\n         computes information about the slice that the slice object\n         would describe if applied to a sequence of *length* items.\n         It returns a tuple of three integers; respectively these are\n         the *start* and *stop* indices and the *step* or stride\n         length of the slice. Missing or out-of-bounds indices are\n         handled in a manner consistent with regular slices.\n\n   Static method objects\n      Static method objects provide a way of defeating the\n      transformation of function objects to method objects described\n      above. A static method object is a wrapper around any other\n      object, usually a user-defined method object. When a static\n      method object is retrieved from a class or a class instance, the\n      object actually returned is the wrapped object, which is not\n      subject to any further transformation. Static method objects are\n      not themselves callable, although the objects they wrap usually\n      are. Static method objects are created by the built-in\n      ``staticmethod()`` constructor.\n\n   Class method objects\n      A class method object, like a static method object, is a wrapper\n      around another object that alters the way in which that object\n      is retrieved from classes and class instances. The behaviour of\n      class method objects upon such retrieval is described above,\n      under "User-defined methods". Class method objects are created\n      by the built-in ``classmethod()`` constructor.\n',
  'typesfunctions': '\nFunctions\n*********\n\nFunction objects are created by function definitions.  The only\noperation on a function object is to call it: ``func(argument-list)``.\n\nThere are really two flavors of function objects: built-in functions\nand user-defined functions.  Both support the same operation (to call\nthe function), but the implementation is different, hence the\ndifferent object types.\n\nSee *Function definitions* for more information.\n',
- 'typesmapping': '\nMapping Types --- ``dict``\n**************************\n\nA *mapping* object maps *hashable* values to arbitrary objects.\nMappings are mutable objects.  There is currently only one standard\nmapping type, the *dictionary*.  (For other containers see the built\nin ``list``, ``set``, and ``tuple`` classes, and the ``collections``\nmodule.)\n\nA dictionary\'s keys are *almost* arbitrary values.  Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys.  Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\nindex the same dictionary entry.  (Note however, that since computers\nstore floating-point numbers as approximations it is usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of\n``key: value`` pairs within braces, for example: ``{\'jack\': 4098,\n\'sjoerd\': 4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or by the\n``dict`` constructor.\n\nclass class dict([arg])\n\n   Return a new dictionary initialized from an optional positional\n   argument or from a set of keyword arguments.  If no arguments are\n   given, return a new empty dictionary.  If the positional argument\n   *arg* is a mapping object, return a dictionary mapping the same\n   keys to the same values as does the mapping object.  Otherwise the\n   positional argument must be a sequence, a container that supports\n   iteration, or an iterator object.  The elements of the argument\n   must each also be of one of those kinds, and each must in turn\n   contain exactly two objects.  The first is used as a key in the new\n   dictionary, and the second as the key\'s value.  If a given key is\n   seen more than once, the last value associated with it is retained\n   in the new dictionary.\n\n   If keyword arguments are given, the keywords themselves with their\n   associated values are added as items to the dictionary.  If a key\n   is specified both in the positional argument and as a keyword\n   argument, the value associated with the keyword is retained in the\n   dictionary.  For example, these all return a dictionary equal to\n   ``{"one": 2, "two": 3}``:\n\n   * ``dict(one=2, two=3)``\n\n   * ``dict({\'one\': 2, \'two\': 3})``\n\n   * ``dict(zip((\'one\', \'two\'), (2, 3)))``\n\n   * ``dict([[\'two\', 3], [\'one\', 2]])``\n\n   The first example only works for keys that are valid Python\n   identifiers; the others work with any valid keys.\n\n   These are the operations that dictionaries support (and therefore,\n   custom mapping types should support too):\n\n   len(d)\n\n      Return the number of items in the dictionary *d*.\n\n   d[key]\n\n      Return the item of *d* with key *key*.  Raises a ``KeyError`` if\n      *key* is not in the map.\n\n      If a subclass of dict defines a method ``__missing__()``, if the\n      key *key* is not present, the ``d[key]`` operation calls that\n      method with the key *key* as argument.  The ``d[key]`` operation\n      then returns or raises whatever is returned or raised by the\n      ``__missing__(key)`` call if the key is not present. No other\n      operations or methods invoke ``__missing__()``. If\n      ``__missing__()`` is not defined, ``KeyError`` is raised.\n      ``__missing__()`` must be a method; it cannot be an instance\n      variable. For an example, see ``collections.defaultdict``.\n\n   d[key] = value\n\n      Set ``d[key]`` to *value*.\n\n   del d[key]\n\n      Remove ``d[key]`` from *d*.  Raises a ``KeyError`` if *key* is\n      not in the map.\n\n   key in d\n\n      Return ``True`` if *d* has a key *key*, else ``False``.\n\n   key not in d\n\n      Equivalent to ``not key in d``.\n\n   iter(d)\n\n      Return an iterator over the keys of the dictionary.  This is a\n      shortcut for ``iter(d.keys())``.\n\n   clear()\n\n      Remove all items from the dictionary.\n\n   copy()\n\n      Return a shallow copy of the dictionary.\n\n   classmethod fromkeys(seq[, value])\n\n      Create a new dictionary with keys from *seq* and values set to\n      *value*.\n\n      ``fromkeys()`` is a class method that returns a new dictionary.\n      *value* defaults to ``None``.\n\n   get(key[, default])\n\n      Return the value for *key* if *key* is in the dictionary, else\n      *default*. If *default* is not given, it defaults to ``None``,\n      so that this method never raises a ``KeyError``.\n\n   items()\n\n      Return a new view of the dictionary\'s items (``(key, value)``\n      pairs).  See below for documentation of view objects.\n\n   keys()\n\n      Return a new view of the dictionary\'s keys.  See below for\n      documentation of view objects.\n\n   pop(key[, default])\n\n      If *key* is in the dictionary, remove it and return its value,\n      else return *default*.  If *default* is not given and *key* is\n      not in the dictionary, a ``KeyError`` is raised.\n\n   popitem()\n\n      Remove and return an arbitrary ``(key, value)`` pair from the\n      dictionary.\n\n      ``popitem()`` is useful to destructively iterate over a\n      dictionary, as often used in set algorithms.  If the dictionary\n      is empty, calling ``popitem()`` raises a ``KeyError``.\n\n   setdefault(key[, default])\n\n      If *key* is in the dictionary, return its value.  If not, insert\n      *key* with a value of *default* and return *default*.  *default*\n      defaults to ``None``.\n\n   update([other])\n\n      Update the dictionary with the key/value pairs from *other*,\n      overwriting existing keys.  Return ``None``.\n\n      ``update()`` accepts either another dictionary object or an\n      iterable of key/value pairs (as tuples or other iterables of\n      length two).  If keyword arguments are specified, the dictionary\n      is then updated with those key/value pairs: ``d.update(red=1,\n      blue=2)``.\n\n   values()\n\n      Return a new view of the dictionary\'s values.  See below for\n      documentation of view objects.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by ``dict.keys()``, ``dict.values()`` and\n``dict.items()`` are *view objects*.  They provide a dynamic view on\nthe dictionary\'s entries, which means that when the dictionary\nchanges, the view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n   Return the number of entries in the dictionary.\n\niter(dictview)\n\n   Return an iterator over the keys, values or items (represented as\n   tuples of ``(key, value)``) in the dictionary.\n\n   Keys and values are iterated over in an arbitrary order which is\n   non-random, varies across Python implementations, and depends on\n   the dictionary\'s history of insertions and deletions. If keys,\n   values and items views are iterated over with no intervening\n   modifications to the dictionary, the order of items will directly\n   correspond.  This allows the creation of ``(value, key)`` pairs\n   using ``zip()``: ``pairs = zip(d.values(), d.keys())``.  Another\n   way to create the same list is ``pairs = [(v, k) for (k, v) in\n   d.items()]``.\n\n   Iterating views while adding or deleting entries in the dictionary\n   may raise a ``RuntimeError`` or fail to iterate over all entries.\n\nx in dictview\n\n   Return ``True`` if *x* is in the underlying dictionary\'s keys,\n   values or items (in the latter case, *x* should be a ``(key,\n   value)`` tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that (key, value) pairs are unique and\nhashable, then the items view is also set-like.  (Values views are not\ntreated as set-like since the entries are generally not unique.)  Then\nthese set operations are available ("other" refers either to another\nview or a set):\n\ndictview & other\n\n   Return the intersection of the dictview and the other object as a\n   new set.\n\ndictview | other\n\n   Return the union of the dictview and the other object as a new set.\n\ndictview - other\n\n   Return the difference between the dictview and the other object\n   (all elements in *dictview* that aren\'t in *other*) as a new set.\n\ndictview ^ other\n\n   Return the symmetric difference (all elements either in *dictview*\n   or *other*, but not in both) of the dictview and the other object\n   as a new set.\n\ndictview.isdisjoint(other)\n\n   Return True if the view has no elements in common with *other*.\n   Sets are disjoint if and only if their intersection is the empty\n   set.\n\nAn example of dictionary view usage:\n\n   >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n   >>> keys = dishes.keys()\n   >>> values = dishes.values()\n\n   >>> # iteration\n   >>> n = 0\n   >>> for val in values:\n   ...     n += val\n   >>> print(n)\n   504\n\n   >>> # keys and values are iterated over in the same order\n   >>> list(keys)\n   [\'eggs\', \'bacon\', \'sausage\', \'spam\']\n   >>> list(values)\n   [2, 1, 1, 500]\n\n   >>> # view objects are dynamic and reflect dict changes\n   >>> del dishes[\'eggs\']\n   >>> del dishes[\'sausage\']\n   >>> list(keys)\n   [\'spam\', \'bacon\']\n\n   >>> # set operations\n   >>> keys & {\'eggs\', \'bacon\', \'salad\'}\n   {\'bacon\'}\n',
+ 'typesmapping': '\nMapping Types --- ``dict``\n**************************\n\nA *mapping* object maps *hashable* values to arbitrary objects.\nMappings are mutable objects.  There is currently only one standard\nmapping type, the *dictionary*.  (For other containers see the built\nin ``list``, ``set``, and ``tuple`` classes, and the ``collections``\nmodule.)\n\nA dictionary\'s keys are *almost* arbitrary values.  Values that are\nnot *hashable*, that is, values containing lists, dictionaries or\nother mutable types (that are compared by value rather than by object\nidentity) may not be used as keys.  Numeric types used for keys obey\nthe normal rules for numeric comparison: if two numbers compare equal\n(such as ``1`` and ``1.0``) then they can be used interchangeably to\nindex the same dictionary entry.  (Note however, that since computers\nstore floating-point numbers as approximations it is usually unwise to\nuse them as dictionary keys.)\n\nDictionaries can be created by placing a comma-separated list of\n``key: value`` pairs within braces, for example: ``{\'jack\': 4098,\n\'sjoerd\': 4127}`` or ``{4098: \'jack\', 4127: \'sjoerd\'}``, or by the\n``dict`` constructor.\n\nclass class dict([arg])\n\n   Return a new dictionary initialized from an optional positional\n   argument or from a set of keyword arguments.  If no arguments are\n   given, return a new empty dictionary.  If the positional argument\n   *arg* is a mapping object, return a dictionary mapping the same\n   keys to the same values as does the mapping object.  Otherwise the\n   positional argument must be a sequence, a container that supports\n   iteration, or an iterator object.  The elements of the argument\n   must each also be of one of those kinds, and each must in turn\n   contain exactly two objects.  The first is used as a key in the new\n   dictionary, and the second as the key\'s value.  If a given key is\n   seen more than once, the last value associated with it is retained\n   in the new dictionary.\n\n   If keyword arguments are given, the keywords themselves with their\n   associated values are added as items to the dictionary.  If a key\n   is specified both in the positional argument and as a keyword\n   argument, the value associated with the keyword is retained in the\n   dictionary.  For example, these all return a dictionary equal to\n   ``{"one": 1, "two": 2}``:\n\n   * ``dict(one=1, two=2)``\n\n   * ``dict({\'one\': 1, \'two\': 2})``\n\n   * ``dict(zip((\'one\', \'two\'), (1, 2)))``\n\n   * ``dict([[\'two\', 2], [\'one\', 1]])``\n\n   The first example only works for keys that are valid Python\n   identifiers; the others work with any valid keys.\n\n   These are the operations that dictionaries support (and therefore,\n   custom mapping types should support too):\n\n   len(d)\n\n      Return the number of items in the dictionary *d*.\n\n   d[key]\n\n      Return the item of *d* with key *key*.  Raises a ``KeyError`` if\n      *key* is not in the map.\n\n      If a subclass of dict defines a method ``__missing__()``, if the\n      key *key* is not present, the ``d[key]`` operation calls that\n      method with the key *key* as argument.  The ``d[key]`` operation\n      then returns or raises whatever is returned or raised by the\n      ``__missing__(key)`` call if the key is not present. No other\n      operations or methods invoke ``__missing__()``. If\n      ``__missing__()`` is not defined, ``KeyError`` is raised.\n      ``__missing__()`` must be a method; it cannot be an instance\n      variable:\n\n         >>> class Counter(dict):\n         ...     def __missing__(self, key):\n         ...         return 0\n         >>> c = Counter()\n         >>> c[\'red\']\n         0\n         >>> c[\'red\'] += 1\n         >>> c[\'red\']\n         1\n\n      See ``collections.Counter`` for a complete implementation\n      including other methods helpful for accumulating and managing\n      tallies.\n\n   d[key] = value\n\n      Set ``d[key]`` to *value*.\n\n   del d[key]\n\n      Remove ``d[key]`` from *d*.  Raises a ``KeyError`` if *key* is\n      not in the map.\n\n   key in d\n\n      Return ``True`` if *d* has a key *key*, else ``False``.\n\n   key not in d\n\n      Equivalent to ``not key in d``.\n\n   iter(d)\n\n      Return an iterator over the keys of the dictionary.  This is a\n      shortcut for ``iter(d.keys())``.\n\n   clear()\n\n      Remove all items from the dictionary.\n\n   copy()\n\n      Return a shallow copy of the dictionary.\n\n   classmethod fromkeys(seq[, value])\n\n      Create a new dictionary with keys from *seq* and values set to\n      *value*.\n\n      ``fromkeys()`` is a class method that returns a new dictionary.\n      *value* defaults to ``None``.\n\n   get(key[, default])\n\n      Return the value for *key* if *key* is in the dictionary, else\n      *default*. If *default* is not given, it defaults to ``None``,\n      so that this method never raises a ``KeyError``.\n\n   items()\n\n      Return a new view of the dictionary\'s items (``(key, value)``\n      pairs).  See below for documentation of view objects.\n\n   keys()\n\n      Return a new view of the dictionary\'s keys.  See below for\n      documentation of view objects.\n\n   pop(key[, default])\n\n      If *key* is in the dictionary, remove it and return its value,\n      else return *default*.  If *default* is not given and *key* is\n      not in the dictionary, a ``KeyError`` is raised.\n\n   popitem()\n\n      Remove and return an arbitrary ``(key, value)`` pair from the\n      dictionary.\n\n      ``popitem()`` is useful to destructively iterate over a\n      dictionary, as often used in set algorithms.  If the dictionary\n      is empty, calling ``popitem()`` raises a ``KeyError``.\n\n   setdefault(key[, default])\n\n      If *key* is in the dictionary, return its value.  If not, insert\n      *key* with a value of *default* and return *default*.  *default*\n      defaults to ``None``.\n\n   update([other])\n\n      Update the dictionary with the key/value pairs from *other*,\n      overwriting existing keys.  Return ``None``.\n\n      ``update()`` accepts either another dictionary object or an\n      iterable of key/value pairs (as tuples or other iterables of\n      length two).  If keyword arguments are specified, the dictionary\n      is then updated with those key/value pairs: ``d.update(red=1,\n      blue=2)``.\n\n   values()\n\n      Return a new view of the dictionary\'s values.  See below for\n      documentation of view objects.\n\n\nDictionary view objects\n=======================\n\nThe objects returned by ``dict.keys()``, ``dict.values()`` and\n``dict.items()`` are *view objects*.  They provide a dynamic view on\nthe dictionary\'s entries, which means that when the dictionary\nchanges, the view reflects these changes.\n\nDictionary views can be iterated over to yield their respective data,\nand support membership tests:\n\nlen(dictview)\n\n   Return the number of entries in the dictionary.\n\niter(dictview)\n\n   Return an iterator over the keys, values or items (represented as\n   tuples of ``(key, value)``) in the dictionary.\n\n   Keys and values are iterated over in an arbitrary order which is\n   non-random, varies across Python implementations, and depends on\n   the dictionary\'s history of insertions and deletions. If keys,\n   values and items views are iterated over with no intervening\n   modifications to the dictionary, the order of items will directly\n   correspond.  This allows the creation of ``(value, key)`` pairs\n   using ``zip()``: ``pairs = zip(d.values(), d.keys())``.  Another\n   way to create the same list is ``pairs = [(v, k) for (k, v) in\n   d.items()]``.\n\n   Iterating views while adding or deleting entries in the dictionary\n   may raise a ``RuntimeError`` or fail to iterate over all entries.\n\nx in dictview\n\n   Return ``True`` if *x* is in the underlying dictionary\'s keys,\n   values or items (in the latter case, *x* should be a ``(key,\n   value)`` tuple).\n\nKeys views are set-like since their entries are unique and hashable.\nIf all values are hashable, so that ``(key, value)`` pairs are unique\nand hashable, then the items view is also set-like.  (Values views are\nnot treated as set-like since the entries are generally not unique.)\nFor set-like views, all of the operations defined for the abstract\nbase class ``collections.Set`` are available (for example, ``==``,\n``<``, or ``^``).\n\nAn example of dictionary view usage:\n\n   >>> dishes = {\'eggs\': 2, \'sausage\': 1, \'bacon\': 1, \'spam\': 500}\n   >>> keys = dishes.keys()\n   >>> values = dishes.values()\n\n   >>> # iteration\n   >>> n = 0\n   >>> for val in values:\n   ...     n += val\n   >>> print(n)\n   504\n\n   >>> # keys and values are iterated over in the same order\n   >>> list(keys)\n   [\'eggs\', \'bacon\', \'sausage\', \'spam\']\n   >>> list(values)\n   [2, 1, 1, 500]\n\n   >>> # view objects are dynamic and reflect dict changes\n   >>> del dishes[\'eggs\']\n   >>> del dishes[\'sausage\']\n   >>> list(keys)\n   [\'spam\', \'bacon\']\n\n   >>> # set operations\n   >>> keys & {\'eggs\', \'bacon\', \'salad\'}\n   {\'bacon\'}\n   >>> keys ^ {\'sausage\', \'juice\'}\n   {\'juice\', \'eggs\', \'bacon\', \'spam\'}\n',
  'typesmethods': "\nMethods\n*******\n\nMethods are functions that are called using the attribute notation.\nThere are two flavors: built-in methods (such as ``append()`` on\nlists) and class instance methods.  Built-in methods are described\nwith the types that support them.\n\nIf you access a method (a function defined in a class namespace)\nthrough an instance, you get a special object: a *bound method* (also\ncalled *instance method*) object. When called, it will add the\n``self`` argument to the argument list.  Bound methods have two\nspecial read-only attributes: ``m.__self__`` is the object on which\nthe method operates, and ``m.__func__`` is the function implementing\nthe method.  Calling ``m(arg-1, arg-2, ..., arg-n)`` is completely\nequivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,\narg-n)``.\n\nLike function objects, bound method objects support getting arbitrary\nattributes.  However, since method attributes are actually stored on\nthe underlying function object (``meth.__func__``), setting method\nattributes on bound methods is disallowed.  Attempting to set a method\nattribute results in a ``TypeError`` being raised.  In order to set a\nmethod attribute, you need to explicitly set it on the underlying\nfunction object:\n\n   class C:\n       def method(self):\n           pass\n\n   c = C()\n   c.method.__func__.whoami = 'my name is c'\n\nSee *The standard type hierarchy* for more information.\n",
  'typesmodules': "\nModules\n*******\n\nThe only special operation on a module is attribute access:\n``m.name``, where *m* is a module and *name* accesses a name defined\nin *m*'s symbol table. Module attributes can be assigned to.  (Note\nthat the ``import`` statement is not, strictly speaking, an operation\non a module object; ``import foo`` does not require a module object\nnamed *foo* to exist, rather it requires an (external) *definition*\nfor a module named *foo* somewhere.)\n\nA special member of every module is ``__dict__``. This is the\ndictionary containing the module's symbol table. Modifying this\ndictionary will actually change the module's symbol table, but direct\nassignment to the ``__dict__`` attribute is not possible (you can\nwrite ``m.__dict__['a'] = 1``, which defines ``m.a`` to be ``1``, but\nyou can't write ``m.__dict__ = {}``).  Modifying ``__dict__`` directly\nis not recommended.\n\nModules built into the interpreter are written like this: ``<module\n'sys' (built-in)>``.  If loaded from a file, they are written as\n``<module 'os' from '/usr/local/lib/pythonX.Y/os.pyc'>``.\n",
- 'typesseq': '\nSequence Types --- ``str``, ``bytes``, ``bytearray``, ``list``, ``tuple``, ``range``\n************************************************************************************\n\nThere are six sequence types: strings, byte sequences (``bytes``\nobjects), byte arrays (``bytearray`` objects), lists, tuples, and\nrange objects.  For other containers see the built in ``dict`` and\n``set`` classes, and the ``collections`` module.\n\nStrings contain Unicode characters.  Their literals are written in\nsingle or double quotes: ``\'xyzzy\'``, ``"frobozz"``.  See *String and\nBytes literals* for more about string literals.  In addition to the\nfunctionality described here, there are also string-specific methods\ndescribed in the *String Methods* section.\n\nBytes and bytearray objects contain single bytes -- the former is\nimmutable while the latter is a mutable sequence.  Bytes objects can\nbe constructed the constructor, ``bytes()``, and from literals; use a\n``b`` prefix with normal string syntax: ``b\'xyzzy\'``.  To construct\nbyte arrays, use the ``bytearray()`` function.\n\nWarning: While string objects are sequences of characters (represented by\n  strings of length 1), bytes and bytearray objects are sequences of\n  *integers* (between 0 and 255), representing the ASCII value of\n  single bytes.  That means that for a bytes or bytearray object *b*,\n  ``b[0]`` will be an integer, while ``b[0:1]`` will be a bytes or\n  bytearray object of length 1.  The representation of bytes objects\n  uses the literal format (``b\'...\'``) since it is generally more\n  useful than e.g. ``bytes([50, 19, 100])``.  You can always convert a\n  bytes object into a list of integers using ``list(b)``.Also, while\n  in previous Python versions, byte strings and Unicode strings could\n  be exchanged for each other rather freely (barring encoding issues),\n  strings and bytes are now completely separate concepts.  There\'s no\n  implicit en-/decoding if you pass an object of the wrong type.  A\n  string always compares unequal to a bytes or bytearray object.\n\nLists are constructed with square brackets, separating items with\ncommas: ``[a, b, c]``.  Tuples are constructed by the comma operator\n(not within square brackets), with or without enclosing parentheses,\nbut an empty tuple must have the enclosing parentheses, such as ``a,\nb, c`` or ``()``.  A single item tuple must have a trailing comma,\nsuch as ``(d,)``.\n\nObjects of type range are created using the ``range()`` function.\nThey don\'t support slicing, concatenation or repetition, and using\n``in``, ``not in``, ``min()`` or ``max()`` on them is inefficient.\n\nMost sequence types support the following operations.  The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations.  The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority).  In the table,\n*s* and *t* are sequences of the same type; *n*, *i* and *j* are\nintegers:\n\n+--------------------+----------------------------------+------------+\n| Operation          | Result                           | Notes      |\n+====================+==================================+============+\n| ``x in s``         | ``True`` if an item of *s* is    | (1)        |\n|                    | equal to *x*, else ``False``     |            |\n+--------------------+----------------------------------+------------+\n| ``x not in s``     | ``False`` if an item of *s* is   | (1)        |\n|                    | equal to *x*, else ``True``      |            |\n+--------------------+----------------------------------+------------+\n| ``s + t``          | the concatenation of *s* and *t* | (6)        |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s``   | *n* shallow copies of *s*        | (2)        |\n|                    | concatenated                     |            |\n+--------------------+----------------------------------+------------+\n| ``s[i]``           | *i*\'th item of *s*, origin 0     | (3)        |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]``         | slice of *s* from *i* to *j*     | (3)(4)     |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]``       | slice of *s* from *i* to *j*     | (3)(5)     |\n|                    | with step *k*                    |            |\n+--------------------+----------------------------------+------------+\n| ``len(s)``         | length of *s*                    |            |\n+--------------------+----------------------------------+------------+\n| ``min(s)``         | smallest item of *s*             |            |\n+--------------------+----------------------------------+------------+\n| ``max(s)``         | largest item of *s*              |            |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons.  In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements.  This means that to compare equal, every element must\ncompare equal and the two sequences must be of the same type and have\nthe same length.  (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string object, the ``in`` and ``not in`` operations\n   act like a substring test.\n\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\n   empty sequence of the same type as *s*).  Note also that the copies\n   are shallow; nested structures are not copied.  This often haunts\n   new Python programmers; consider:\n\n   >>> lists = [[]] * 3\n   >>> lists\n   [[], [], []]\n   >>> lists[0].append(3)\n   >>> lists\n   [[3], [3], [3]]\n\n   What has happened is that ``[[]]`` is a one-element list containing\n   an empty list, so all three elements of ``[[]] * 3`` are (pointers\n   to) this single empty list.  Modifying any of the elements of\n   ``lists`` modifies this single list. You can create a list of\n   different lists this way:\n\n   >>> lists = [[] for i in range(3)]\n   >>> lists[0].append(3)\n   >>> lists[1].append(5)\n   >>> lists[2].append(7)\n   >>> lists\n   [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is relative to the end of the\n   string: ``len(s) + i`` or ``len(s) + j`` is substituted.  But note\n   that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n   items with index *k* such that ``i <= k < j``.  If *i* or *j* is\n   greater than ``len(s)``, use ``len(s)``.  If *i* is omitted or\n   ``None``, use ``0``.  If *j* is omitted or ``None``, use\n   ``len(s)``.  If *i* is greater than or equal to *j*, the slice is\n   empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n   sequence of items with index  ``x = i + n*k`` such that ``0 <= n <\n   (j-i)/k``.  In other words, the indices are ``i``, ``i+k``,\n   ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n   never including *j*).  If *i* or *j* is greater than ``len(s)``,\n   use ``len(s)``.  If *i* or *j* are omitted or ``None``, they become\n   "end" values (which end depends on the sign of *k*).  Note, *k*\n   cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t* are both strings,\n   some Python implementations such as CPython can usually perform an\n   in-place optimization for assignments of the form ``s = s + t`` or\n   ``s += t``.  When applicable, this optimization makes quadratic\n   run-time much less likely.  This optimization is both version and\n   implementation dependent.  For performance sensitive code, it is\n   preferable to use the ``str.join()`` method which assures\n   consistent linear concatenation performance across versions and\n   implementations.\n\n\nString Methods\n==============\n\nString objects support the methods listed below.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, bytes, bytearray, list,\ntuple, range* section. To output formatted strings, see the *String\nFormatting* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n   Return a copy of the string with its first character capitalized\n   and the rest lowercased.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\n   Return the number of non-overlapping occurrences of substring *sub*\n   in the range [*start*, *end*].  Optional arguments *start* and\n   *end* are interpreted as in slice notation.\n\nstr.encode(encoding=sys.getdefaultencoding(), errors="strict")\n\n   Return an encoded version of the string as a bytes object.  Default\n   encoding is the current default string encoding.  *errors* may be\n   given to set a different error handling scheme.  The default for\n   *errors* is ``\'strict\'``, meaning that encoding errors raise a\n   ``UnicodeError``.  Other possible values are ``\'ignore\'``,\n   ``\'replace\'``, ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and\n   any other name registered via ``codecs.register_error()``, see\n   section *Codec Base Classes*. For a list of possible encodings, see\n   section *Standard Encodings*.\n\n   Changed in version 3.1: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return ``True`` if the string ends with the specified *suffix*,\n   otherwise return ``False``.  *suffix* can also be a tuple of\n   suffixes to look for.  With optional *start*, test beginning at\n   that position.  With optional *end*, stop comparing at that\n   position.\n\nstr.expandtabs([tabsize])\n\n   Return a copy of the string where all tab characters are replaced\n   by one or more spaces, depending on the current column and the\n   given tab size.  The column number is reset to zero after each\n   newline occurring in the string. If *tabsize* is not given, a tab\n   size of ``8`` characters is assumed.  This doesn\'t understand other\n   non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n   Return the lowest index in the string where substring *sub* is\n   found, such that *sub* is contained in the slice ``s[start:end]``.\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The string on which this\n   method is called can contain literal text or replacement fields\n   delimited by braces ``{}``.  Each replacement field contains either\n   the numeric index of a positional argument, or the name of a\n   keyword argument.  Returns a copy of the string where each\n   replacement field is replaced with the string value of the\n   corresponding argument.\n\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\n   \'The sum of 1 + 2 is 3\'\n\n   See *Format String Syntax* for a description of the various\n   formatting options that can be specified in format strings.\n\nstr.index(sub[, start[, end]])\n\n   Like ``find()``, but raise ``ValueError`` when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters include digit characters, and all characters that that\n   can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-\n   INDIC DIGIT ZERO.\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n   Return true if all cased characters in the string are lowercase and\n   there is at least one cased character, false otherwise.\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when ``repr()`` is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.isspace()\n\n   Return true if there are only whitespace characters in the string\n   and there is at least one character, false otherwise.\n\nstr.istitle()\n\n   Return true if the string is a titlecased string and there is at\n   least one character, for example uppercase characters may only\n   follow uncased characters and lowercase characters only cased ones.\n   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters in the string are uppercase and\n   there is at least one cased character, false otherwise.\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  A ``TypeError`` will be raised if there are\n   any non-string values in *seq*, including ``bytes`` objects.  The\n   separator between elements is the string providing this method.\n\nstr.ljust(width[, fillchar])\n\n   Return the string left justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is a\n   space).  The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.lower()\n\n   Return a copy of the string converted to lowercase.\n\nstr.lstrip([chars])\n\n   Return a copy of the string with leading characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or ``None``, the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.lstrip()\n   \'spacious   \'\n   >>> \'www.example.com\'.lstrip(\'cmowz.\')\n   \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   ``str.translate()``.\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or None.\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   None in the result.\n\nstr.partition(sep)\n\n   Split the string at the first occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\n\n   Return a copy of the string with all occurrences of substring *old*\n   replaced by *new*.  If the optional argument *count* is given, only\n   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n   Return the highest index in the string where substring *sub* is\n   found, such that *sub* is contained within ``s[start:end]``.\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n   is not found.\n\nstr.rjust(width[, fillchar])\n\n   Return the string right justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is a\n   space). The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.rpartition(sep)\n\n   Split the string at the last occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.rsplit([sep[, maxsplit]])\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n   are done, the *rightmost* ones.  If *sep* is not specified or\n   ``None``, any whitespace string is a separator.  Except for\n   splitting from the right, ``rsplit()`` behaves like ``split()``\n   which is described in detail below.\n\nstr.rstrip([chars])\n\n   Return a copy of the string with trailing characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or ``None``, the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.rstrip()\n   \'   spacious\'\n   >>> \'mississippi\'.rstrip(\'ipz\')\n   \'mississ\'\n\nstr.split([sep[, maxsplit]])\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string.  If *maxsplit* is given, at most *maxsplit*\n   splits are done (thus, the list will have at most ``maxsplit+1``\n   elements).  If *maxsplit* is not specified, then there is no limit\n   on the number of splits (all possible splits are made).\n\n   If *sep* is given, consecutive delimiters are not grouped together\n   and are deemed to delimit empty strings (for example,\n   ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``).  The *sep*\n   argument may consist of multiple characters (for example,\n   ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n   an empty string with a specified separator returns ``[\'\']``.\n\n   If *sep* is not specified or is ``None``, a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no empty strings\n   at the start or end if the string has leading or trailing\n   whitespace.  Consequently, splitting an empty string or a string\n   consisting of just whitespace with a ``None`` separator returns\n   ``[]``.\n\n   For example, ``\' 1  2   3  \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n   and ``\'  1  2   3  \'.split(None, 1)`` returns ``[\'1\', \'2   3  \']``.\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return ``True`` if string starts with the *prefix*, otherwise\n   return ``False``. *prefix* can also be a tuple of prefixes to look\n   for.  With optional *start*, test string beginning at that\n   position.  With optional *end*, stop comparing string at that\n   position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or ``None``, the\n   *chars* argument defaults to removing whitespace. The *chars*\n   argument is not a prefix or suffix; rather, all combinations of its\n   values are stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\nstr.title()\n\n   Return a titlecased version of the string where words start with an\n   uppercase character and the remaining characters are lowercase.\n\n   The algorithm uses a simple language-independent definition of a\n   word as groups of consecutive letters.  The definition works in\n   many contexts but it means that apostrophes in contractions and\n   possessives form word boundaries, which may not be the desired\n   result:\n\n      >>> "they\'re bill\'s friends from the UK".title()\n      "They\'Re Bill\'S Friends From The Uk"\n\n   A workaround for apostrophes can be constructed using regular\n   expressions:\n\n      >>> import re\n      >>> def titlecase(s):\n              return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n                            lambda mo: mo.group(0)[0].upper() +\n                                       mo.group(0)[1:].lower(),\n                            s)\n\n      >>> titlecase("they\'re bill\'s friends.")\n      "They\'re Bill\'s Friends."\n\nstr.translate(map)\n\n   Return a copy of the *s* where all characters have been mapped\n   through the *map* which must be a dictionary of Unicode ordinals\n   (integers) to Unicode ordinals, strings or ``None``.  Unmapped\n   characters are left untouched. Characters mapped to ``None`` are\n   deleted.\n\n   You can use ``str.maketrans()`` to create a translation map from\n   character-to-character mappings in different formats.\n\n   Note: An even more flexible approach is to create a custom character\n     mapping codec using the ``codecs`` module (see\n     ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n   Return a copy of the string converted to uppercase.\n\nstr.zfill(width)\n\n   Return the numeric string left filled with zeros in a string of\n   length *width*.  A sign prefix is handled correctly.  The original\n   string is returned if *width* is less than ``len(s)``.\n\n\nOld String Formatting Operations\n================================\n\nNote: The formatting operations described here are obsolete and may go\n  away in future versions of Python.  Use the new *String Formatting*\n  in new code.\n\nString objects have one unique built-in operation: the ``%`` operator\n(modulo). This is also known as the string *formatting* or\n*interpolation* operator. Given ``format % values`` (where *format* is\na string), ``%`` conversion specifications in *format* are replaced\nwith zero or more elements of *values*. The effect is similar to the\nusing ``sprintf()`` in the C language.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [4]  Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n   characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n   conversion types.\n\n4. Minimum field width (optional).  If specified as an ``\'*\'``\n   (asterisk), the actual width is read from the next element of the\n   tuple in *values*, and the object to convert comes after the\n   minimum field width and optional precision.\n\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\n   precision.  If specified as ``\'*\'`` (an asterisk), the actual width\n   is read from the next element of the tuple in *values*, and the\n   value to convert comes after the precision.\n\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print(\'%(language)s has %(#)03d quote types.\' % \\\n...       {\'language\': "Python", "#": 2})\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag      | Meaning                                                               |\n+===========+=======================================================================+\n| ``\'#\'``   | The value conversion will use the "alternate form" (where defined     |\n|           | below).                                                               |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'``   | The conversion will be zero padded for numeric values.                |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'``   | The converted value is left adjusted (overrides the ``\'0\'``           |\n|           | conversion if both are given).                                        |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'``   | (a space) A blank should be left before a positive number (or empty   |\n|           | string) produced by a signed conversion.                              |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'``   | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion     |\n|           | (overrides a "space" flag).                                           |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion   | Meaning                                               | Notes   |\n+==============+=======================================================+=========+\n| ``\'d\'``      | Signed integer decimal.                               |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'``      | Signed integer decimal.                               |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'``      | Signed octal value.                                   | (1)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'``      | Obsolete type -- it is identical to ``\'d\'``.          | (7)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'``      | Signed hexadecimal (lowercase).                       | (2)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'``      | Signed hexadecimal (uppercase).                       | (2)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'``      | Floating point exponential format (lowercase).        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'``      | Floating point exponential format (uppercase).        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'``      | Floating point decimal format.                        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'``      | Floating point decimal format.                        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'``      | Floating point format. Uses lowercase exponential     | (4)     |\n|              | format if exponent is less than -4 or not less than   |         |\n|              | precision, decimal format otherwise.                  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'G\'``      | Floating point format. Uses uppercase exponential     | (4)     |\n|              | format if exponent is less than -4 or not less than   |         |\n|              | precision, decimal format otherwise.                  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'``      | Single character (accepts integer or single character |         |\n|              | string).                                              |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'``      | String (converts any Python object using ``repr()``). | (5)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'``      | String (converts any Python object using ``str()``).  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'%\'``      | No argument is converted, results in a ``\'%\'``        |         |\n|              | character in the result.                              |         |\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1. The alternate form causes a leading zero (``\'0\'``) to be inserted\n   between left-hand padding and the formatting of the number if the\n   leading character of the result is not already a zero.\n\n2. The alternate form causes a leading ``\'0x\'`` or ``\'0X\'`` (depending\n   on whether the ``\'x\'`` or ``\'X\'`` format was used) to be inserted\n   between left-hand padding and the formatting of the number if the\n   leading character of the result is not already a zero.\n\n3. The alternate form causes the result to always contain a decimal\n   point, even if no digits follow it.\n\n   The precision determines the number of digits after the decimal\n   point and defaults to 6.\n\n4. The alternate form causes the result to always contain a decimal\n   point, and trailing zeroes are not removed as they would otherwise\n   be.\n\n   The precision determines the number of significant digits before\n   and after the decimal point and defaults to 6.\n\n5. The precision determines the maximal number of characters used.\n\n1. See **PEP 237**.\n\nSince Python strings have an explicit length, ``%s`` conversions do\nnot assume that ``\'\\0\'`` is the end of the string.\n\nChanged in version 3.1: ``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no longer replaced by ``%g`` conversions.\n\nAdditional string operations are defined in standard modules\n``string`` and ``re``.\n\n\nRange Type\n==========\n\nThe ``range`` type is an immutable sequence which is commonly used for\nlooping.  The advantage of the ``range`` type is that an ``range``\nobject will always take the same amount of memory, no matter the size\nof the range it represents.  There are no consistent performance\nadvantages.\n\nRange objects have relatively little behavior: they support indexing,\niteration, the ``len()`` function, and the following methods.\n\nrange.count(x)\n\n   Return the number of *i*\'s for which ``s[i] == x``.  Normally the\n   result will be 0 or 1, but it could be greater if *x* defines an\n   unusual equality function.\n\n      New in version 3.2.\n\nrange.index(x)\n\n   Return the smallest *i* such that ``s[i] == x``.  Raises\n   ``ValueError`` when *x* is not in the range.\n\n      New in version 3.2.\n\n\nMutable Sequence Types\n======================\n\nList and bytearray objects support additional operations that allow\nin-place modification of the object.  Other mutable sequence types\n(when added to the language) should also support these operations.\nStrings and tuples are immutable sequence types: such objects cannot\nbe modified once created. The following operations are defined on\nmutable sequence types (where *x* is an arbitrary object).\n\nNote that while lists allow their items to be of any type, bytearray\nobject "items" are all integers in the range 0 <= x < 256.\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| ``s[i] = x``                   | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t``                 | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]``                 | same as ``s[i:j] = []``          |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t``               | the elements of ``s[i:j:k]`` are | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]``               | removes the elements of          |                       |\n|                                | ``s[i:j:k]`` from the list       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)``                | same as ``s[len(s):len(s)] =     |                       |\n|                                | [x]``                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)``                | same as ``s[len(s):len(s)] = x`` | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)``                 | return number of *i*\'s for which |                       |\n|                                | ``s[i] == x``                    |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])``       | return smallest *k* such that    | (3)                   |\n|                                | ``s[k] == x`` and ``i <= k < j`` |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)``             | same as ``s[i:i] = [x]``         | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])``                 | same as ``x = s[i]; del s[i];    | (5)                   |\n|                                | return x``                       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)``                | same as ``del s[s.index(x)]``    | (3)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()``                | reverses the items of *s* in     | (6)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([key[, reverse]])``   | sort the items of *s* in place   | (6), (7), (8)         |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. *x* can be any iterable object.\n\n3. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n   index is passed as the second or third parameter to the ``index()``\n   method, the sequence length is added, as for slice indices.  If it\n   is still negative, it is truncated to zero, as for slice indices.\n\n4. When a negative index is passed as the first parameter to the\n   ``insert()`` method, the sequence length is added, as for slice\n   indices.  If it is still negative, it is truncated to zero, as for\n   slice indices.\n\n5. The optional argument *i* defaults to ``-1``, so that by default\n   the last item is removed and returned.\n\n6. The ``sort()`` and ``reverse()`` methods modify the sequence in\n   place for economy of space when sorting or reversing a large\n   sequence.  To remind you that they operate by side effect, they\n   don\'t return the sorted or reversed sequence.\n\n7. The ``sort()`` method takes optional arguments for controlling the\n   comparisons.  Each must be specified as a keyword argument.\n\n   *key* specifies a function of one argument that is used to extract\n   a comparison key from each list element: ``key=str.lower``.  The\n   default value is ``None``. Use ``functools.cmp_to_key()`` to\n   convert an old-style *cmp* function to a *key* function.\n\n   *reverse* is a boolean value.  If set to ``True``, then the list\n   elements are sorted as if each comparison were reversed.\n\n   The ``sort()`` method is guaranteed to be stable.  A sort is stable\n   if it guarantees not to change the relative order of elements that\n   compare equal --- this is helpful for sorting in multiple passes\n   (for example, sort by department, then by salary grade).\n\n   **CPython implementation detail:** While a list is being sorted,\n   the effect of attempting to mutate, or even inspect, the list is\n   undefined.  The C implementation of Python makes the list appear\n   empty for the duration, and raises ``ValueError`` if it can detect\n   that the list has been mutated during a sort.\n\n8. ``sort()`` is not supported by ``bytearray`` objects.\n\n\nBytes and Byte Array Methods\n============================\n\nBytes and bytearray objects, being "strings of bytes", have all\nmethods found on strings, with the exception of ``encode()``,\n``format()`` and ``isidentifier()``, which do not make sense with\nthese types.  For converting the objects to strings, they have a\n``decode()`` method.\n\nWherever one of these methods needs to interpret the bytes as\ncharacters (e.g. the ``is...()`` methods), the ASCII character set is\nassumed.\n\nNote: The methods on bytes and bytearray objects don\'t accept strings as\n  their arguments, just as the methods on strings don\'t accept bytes\n  as their arguments.  For example, you have to write\n\n     a = "abc"\n     b = a.replace("a", "f")\n\n  and\n\n     a = b"abc"\n     b = a.replace(b"a", b"f")\n\nbytes.decode(encoding=sys.getdefaultencoding(), errors="strict")\nbytearray.decode(encoding=sys.getdefaultencoding(), errors="strict")\n\n   Return a string decoded from the given bytes.  Default encoding is\n   the current default string encoding.  *errors* may be given to set\n   a different error handling scheme.  The default for *errors* is\n   ``\'strict\'``, meaning that encoding errors raise a\n   ``UnicodeError``.  Other possible values are ``\'ignore\'``,\n   ``\'replace\'`` and any other name registered via\n   ``codecs.register_error()``, see section *Codec Base Classes*. For\n   a list of possible encodings, see section *Standard Encodings*.\n\n   Changed in version 3.1: Added support for keyword arguments.\n\nThe bytes and bytearray types have an additional class method:\n\nclassmethod bytes.fromhex(string)\nclassmethod bytearray.fromhex(string)\n\n   This ``bytes`` class method returns a bytes or bytearray object,\n   decoding the given string object.  The string must contain two\n   hexadecimal digits per byte, spaces are ignored.\n\n   >>> bytes.fromhex(\'f0 f1f2  \')\n   b\'\\xf0\\xf1\\xf2\'\n\nThe maketrans and translate methods differ in semantics from the\nversions available on strings:\n\nbytes.translate(table[, delete])\nbytearray.translate(table[, delete])\n\n   Return a copy of the bytes or bytearray object where all bytes\n   occurring in the optional argument *delete* are removed, and the\n   remaining bytes have been mapped through the given translation\n   table, which must be a bytes object of length 256.\n\n   You can use the ``bytes.maketrans()`` method to create a\n   translation table.\n\n   Set the *table* argument to ``None`` for translations that only\n   delete characters:\n\n      >>> b\'read this short text\'.translate(None, b\'aeiou\')\n      b\'rd ths shrt txt\'\n\nstatic bytes.maketrans(from, to)\nstatic bytearray.maketrans(from, to)\n\n   This static method returns a translation table usable for\n   ``bytes.translate()`` that will map each character in *from* into\n   the character at the same position in *to*; *from* and *to* must be\n   bytes objects and have the same length.\n\n   New in version 3.1.\n',
+ 'typesseq': '\nSequence Types --- ``str``, ``bytes``, ``bytearray``, ``list``, ``tuple``, ``range``\n************************************************************************************\n\nThere are six sequence types: strings, byte sequences (``bytes``\nobjects), byte arrays (``bytearray`` objects), lists, tuples, and\nrange objects.  For other containers see the built in ``dict`` and\n``set`` classes, and the ``collections`` module.\n\nStrings contain Unicode characters.  Their literals are written in\nsingle or double quotes: ``\'xyzzy\'``, ``"frobozz"``.  See *String and\nBytes literals* for more about string literals.  In addition to the\nfunctionality described here, there are also string-specific methods\ndescribed in the *String Methods* section.\n\nBytes and bytearray objects contain single bytes -- the former is\nimmutable while the latter is a mutable sequence.  Bytes objects can\nbe constructed the constructor, ``bytes()``, and from literals; use a\n``b`` prefix with normal string syntax: ``b\'xyzzy\'``.  To construct\nbyte arrays, use the ``bytearray()`` function.\n\nWhile string objects are sequences of characters (represented by\nstrings of length 1), bytes and bytearray objects are sequences of\n*integers* (between 0 and 255), representing the ASCII value of single\nbytes.  That means that for a bytes or bytearray object *b*, ``b[0]``\nwill be an integer, while ``b[0:1]`` will be a bytes or bytearray\nobject of length 1.  The representation of bytes objects uses the\nliteral format (``b\'...\'``) since it is generally more useful than\ne.g. ``bytes([50, 19, 100])``.  You can always convert a bytes object\ninto a list of integers using ``list(b)``.\n\nAlso, while in previous Python versions, byte strings and Unicode\nstrings could be exchanged for each other rather freely (barring\nencoding issues), strings and bytes are now completely separate\nconcepts.  There\'s no implicit en-/decoding if you pass an object of\nthe wrong type.  A string always compares unequal to a bytes or\nbytearray object.\n\nLists are constructed with square brackets, separating items with\ncommas: ``[a, b, c]``.  Tuples are constructed by the comma operator\n(not within square brackets), with or without enclosing parentheses,\nbut an empty tuple must have the enclosing parentheses, such as ``a,\nb, c`` or ``()``.  A single item tuple must have a trailing comma,\nsuch as ``(d,)``.\n\nObjects of type range are created using the ``range()`` function.\nThey don\'t support concatenation or repetition, and using ``min()`` or\n``max()`` on them is inefficient.\n\nMost sequence types support the following operations.  The ``in`` and\n``not in`` operations have the same priorities as the comparison\noperations.  The ``+`` and ``*`` operations have the same priority as\nthe corresponding numeric operations. [3] Additional methods are\nprovided for *Mutable Sequence Types*.\n\nThis table lists the sequence operations sorted in ascending priority\n(operations in the same box have the same priority).  In the table,\n*s* and *t* are sequences of the same type; *n*, *i*, *j* and *k* are\nintegers.\n\n+--------------------+----------------------------------+------------+\n| Operation          | Result                           | Notes      |\n+====================+==================================+============+\n| ``x in s``         | ``True`` if an item of *s* is    | (1)        |\n|                    | equal to *x*, else ``False``     |            |\n+--------------------+----------------------------------+------------+\n| ``x not in s``     | ``False`` if an item of *s* is   | (1)        |\n|                    | equal to *x*, else ``True``      |            |\n+--------------------+----------------------------------+------------+\n| ``s + t``          | the concatenation of *s* and *t* | (6)        |\n+--------------------+----------------------------------+------------+\n| ``s * n, n * s``   | *n* shallow copies of *s*        | (2)        |\n|                    | concatenated                     |            |\n+--------------------+----------------------------------+------------+\n| ``s[i]``           | *i*\'th item of *s*, origin 0     | (3)        |\n+--------------------+----------------------------------+------------+\n| ``s[i:j]``         | slice of *s* from *i* to *j*     | (3)(4)     |\n+--------------------+----------------------------------+------------+\n| ``s[i:j:k]``       | slice of *s* from *i* to *j*     | (3)(5)     |\n|                    | with step *k*                    |            |\n+--------------------+----------------------------------+------------+\n| ``len(s)``         | length of *s*                    |            |\n+--------------------+----------------------------------+------------+\n| ``min(s)``         | smallest item of *s*             |            |\n+--------------------+----------------------------------+------------+\n| ``max(s)``         | largest item of *s*              |            |\n+--------------------+----------------------------------+------------+\n| ``s.index(i)``     | index of the first occurence of  |            |\n|                    | *i* in *s*                       |            |\n+--------------------+----------------------------------+------------+\n| ``s.count(i)``     | total number of occurences of    |            |\n|                    | *i* in *s*                       |            |\n+--------------------+----------------------------------+------------+\n\nSequence types also support comparisons.  In particular, tuples and\nlists are compared lexicographically by comparing corresponding\nelements.  This means that to compare equal, every element must\ncompare equal and the two sequences must be of the same type and have\nthe same length.  (For full details see *Comparisons* in the language\nreference.)\n\nNotes:\n\n1. When *s* is a string object, the ``in`` and ``not in`` operations\n   act like a substring test.\n\n2. Values of *n* less than ``0`` are treated as ``0`` (which yields an\n   empty sequence of the same type as *s*).  Note also that the copies\n   are shallow; nested structures are not copied.  This often haunts\n   new Python programmers; consider:\n\n   >>> lists = [[]] * 3\n   >>> lists\n   [[], [], []]\n   >>> lists[0].append(3)\n   >>> lists\n   [[3], [3], [3]]\n\n   What has happened is that ``[[]]`` is a one-element list containing\n   an empty list, so all three elements of ``[[]] * 3`` are (pointers\n   to) this single empty list.  Modifying any of the elements of\n   ``lists`` modifies this single list. You can create a list of\n   different lists this way:\n\n   >>> lists = [[] for i in range(3)]\n   >>> lists[0].append(3)\n   >>> lists[1].append(5)\n   >>> lists[2].append(7)\n   >>> lists\n   [[3], [5], [7]]\n\n3. If *i* or *j* is negative, the index is relative to the end of the\n   string: ``len(s) + i`` or ``len(s) + j`` is substituted.  But note\n   that ``-0`` is still ``0``.\n\n4. The slice of *s* from *i* to *j* is defined as the sequence of\n   items with index *k* such that ``i <= k < j``.  If *i* or *j* is\n   greater than ``len(s)``, use ``len(s)``.  If *i* is omitted or\n   ``None``, use ``0``.  If *j* is omitted or ``None``, use\n   ``len(s)``.  If *i* is greater than or equal to *j*, the slice is\n   empty.\n\n5. The slice of *s* from *i* to *j* with step *k* is defined as the\n   sequence of items with index  ``x = i + n*k`` such that ``0 <= n <\n   (j-i)/k``.  In other words, the indices are ``i``, ``i+k``,\n   ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but\n   never including *j*).  If *i* or *j* is greater than ``len(s)``,\n   use ``len(s)``.  If *i* or *j* are omitted or ``None``, they become\n   "end" values (which end depends on the sign of *k*).  Note, *k*\n   cannot be zero. If *k* is ``None``, it is treated like ``1``.\n\n6. **CPython implementation detail:** If *s* and *t* are both strings,\n   some Python implementations such as CPython can usually perform an\n   in-place optimization for assignments of the form ``s = s + t`` or\n   ``s += t``.  When applicable, this optimization makes quadratic\n   run-time much less likely.  This optimization is both version and\n   implementation dependent.  For performance sensitive code, it is\n   preferable to use the ``str.join()`` method which assures\n   consistent linear concatenation performance across versions and\n   implementations.\n\n\nString Methods\n==============\n\nString objects support the methods listed below.\n\nIn addition, Python\'s strings support the sequence type methods\ndescribed in the *Sequence Types --- str, bytes, bytearray, list,\ntuple, range* section. To output formatted strings, see the *String\nFormatting* section. Also, see the ``re`` module for string functions\nbased on regular expressions.\n\nstr.capitalize()\n\n   Return a copy of the string with its first character capitalized\n   and the rest lowercased.\n\nstr.center(width[, fillchar])\n\n   Return centered in a string of length *width*. Padding is done\n   using the specified *fillchar* (default is a space).\n\nstr.count(sub[, start[, end]])\n\n   Return the number of non-overlapping occurrences of substring *sub*\n   in the range [*start*, *end*].  Optional arguments *start* and\n   *end* are interpreted as in slice notation.\n\nstr.encode(encoding="utf-8", errors="strict")\n\n   Return an encoded version of the string as a bytes object. Default\n   encoding is ``\'utf-8\'``. *errors* may be given to set a different\n   error handling scheme. The default for *errors* is ``\'strict\'``,\n   meaning that encoding errors raise a ``UnicodeError``. Other\n   possible values are ``\'ignore\'``, ``\'replace\'``,\n   ``\'xmlcharrefreplace\'``, ``\'backslashreplace\'`` and any other name\n   registered via ``codecs.register_error()``, see section *Codec Base\n   Classes*. For a list of possible encodings, see section *Standard\n   Encodings*.\n\n   Changed in version 3.1: Support for keyword arguments added.\n\nstr.endswith(suffix[, start[, end]])\n\n   Return ``True`` if the string ends with the specified *suffix*,\n   otherwise return ``False``.  *suffix* can also be a tuple of\n   suffixes to look for.  With optional *start*, test beginning at\n   that position.  With optional *end*, stop comparing at that\n   position.\n\nstr.expandtabs([tabsize])\n\n   Return a copy of the string where all tab characters are replaced\n   by one or more spaces, depending on the current column and the\n   given tab size.  The column number is reset to zero after each\n   newline occurring in the string. If *tabsize* is not given, a tab\n   size of ``8`` characters is assumed.  This doesn\'t understand other\n   non-printing characters or escape sequences.\n\nstr.find(sub[, start[, end]])\n\n   Return the lowest index in the string where substring *sub* is\n   found, such that *sub* is contained in the slice ``s[start:end]``.\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` if *sub* is not found.\n\nstr.format(*args, **kwargs)\n\n   Perform a string formatting operation.  The string on which this\n   method is called can contain literal text or replacement fields\n   delimited by braces ``{}``.  Each replacement field contains either\n   the numeric index of a positional argument, or the name of a\n   keyword argument.  Returns a copy of the string where each\n   replacement field is replaced with the string value of the\n   corresponding argument.\n\n   >>> "The sum of 1 + 2 is {0}".format(1+2)\n   \'The sum of 1 + 2 is 3\'\n\n   See *Format String Syntax* for a description of the various\n   formatting options that can be specified in format strings.\n\nstr.format_map(mapping)\n\n   Similar to ``str.format(**mapping)``, except that ``mapping`` is\n   used directly and not copied to a ``dict`` .  This is useful if for\n   example ``mapping`` is a dict subclass:\n\n   >>> class Default(dict):\n   ...     def __missing__(self, key):\n   ...         return key\n   ...\n   >>> \'{name} was born in {country}\'.format_map(Default(name=\'Guido\'))\n   \'Guido was born in country\'\n\n   New in version 3.2.\n\nstr.index(sub[, start[, end]])\n\n   Like ``find()``, but raise ``ValueError`` when the substring is not\n   found.\n\nstr.isalnum()\n\n   Return true if all characters in the string are alphanumeric and\n   there is at least one character, false otherwise.  A character\n   ``c`` is alphanumeric if one of the following returns ``True``:\n   ``c.isalpha()``, ``c.isdecimal()``, ``c.isdigit()``, or\n   ``c.isnumeric()``.\n\nstr.isalpha()\n\n   Return true if all characters in the string are alphabetic and\n   there is at least one character, false otherwise.  Alphabetic\n   characters are those characters defined in the Unicode character\n   database as "Letter", i.e., those with general category property\n   being one of "Lm", "Lt", "Lu", "Ll", or "Lo".  Note that this is\n   different from the "Alphabetic" property defined in the Unicode\n   Standard.\n\nstr.isdecimal()\n\n   Return true if all characters in the string are decimal characters\n   and there is at least one character, false otherwise. Decimal\n   characters are those from general category "Nd". This category\n   includes digit characters, and all characters that that can be used\n   to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT\n   ZERO.\n\nstr.isdigit()\n\n   Return true if all characters in the string are digits and there is\n   at least one character, false otherwise.  Digits include decimal\n   characters and digits that need special handling, such as the\n   compatibility superscript digits.  Formally, a digit is a character\n   that has the property value Numeric_Type=Digit or\n   Numeric_Type=Decimal.\n\nstr.isidentifier()\n\n   Return true if the string is a valid identifier according to the\n   language definition, section *Identifiers and keywords*.\n\nstr.islower()\n\n   Return true if all cased characters in the string are lowercase and\n   there is at least one cased character, false otherwise.  Cased\n   characters are those with general category property being one of\n   "Lu", "Ll", or "Lt" and lowercase characters are those with general\n   category property "Ll".\n\nstr.isnumeric()\n\n   Return true if all characters in the string are numeric characters,\n   and there is at least one character, false otherwise. Numeric\n   characters include digit characters, and all characters that have\n   the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION\n   ONE FIFTH.  Formally, numeric characters are those with the\n   property value Numeric_Type=Digit, Numeric_Type=Decimal or\n   Numeric_Type=Numeric.\n\nstr.isprintable()\n\n   Return true if all characters in the string are printable or the\n   string is empty, false otherwise.  Nonprintable characters are\n   those characters defined in the Unicode character database as\n   "Other" or "Separator", excepting the ASCII space (0x20) which is\n   considered printable.  (Note that printable characters in this\n   context are those which should not be escaped when ``repr()`` is\n   invoked on a string.  It has no bearing on the handling of strings\n   written to ``sys.stdout`` or ``sys.stderr``.)\n\nstr.isspace()\n\n   Return true if there are only whitespace characters in the string\n   and there is at least one character, false otherwise.  Whitespace\n   characters  are those characters defined in the Unicode character\n   database as "Other" or "Separator" and those with bidirectional\n   property being one of "WS", "B", or "S".\n\nstr.istitle()\n\n   Return true if the string is a titlecased string and there is at\n   least one character, for example uppercase characters may only\n   follow uncased characters and lowercase characters only cased ones.\n   Return false otherwise.\n\nstr.isupper()\n\n   Return true if all cased characters in the string are uppercase and\n   there is at least one cased character, false otherwise. Cased\n   characters are those with general category property being one of\n   "Lu", "Ll", or "Lt" and uppercase characters are those with general\n   category property "Lu".\n\nstr.join(iterable)\n\n   Return a string which is the concatenation of the strings in the\n   *iterable* *iterable*.  A ``TypeError`` will be raised if there are\n   any non-string values in *seq*, including ``bytes`` objects.  The\n   separator between elements is the string providing this method.\n\nstr.ljust(width[, fillchar])\n\n   Return the string left justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is a\n   space).  The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.lower()\n\n   Return a copy of the string converted to lowercase.\n\nstr.lstrip([chars])\n\n   Return a copy of the string with leading characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or ``None``, the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a prefix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.lstrip()\n   \'spacious   \'\n   >>> \'www.example.com\'.lstrip(\'cmowz.\')\n   \'example.com\'\n\nstatic str.maketrans(x[, y[, z]])\n\n   This static method returns a translation table usable for\n   ``str.translate()``.\n\n   If there is only one argument, it must be a dictionary mapping\n   Unicode ordinals (integers) or characters (strings of length 1) to\n   Unicode ordinals, strings (of arbitrary lengths) or None.\n   Character keys will then be converted to ordinals.\n\n   If there are two arguments, they must be strings of equal length,\n   and in the resulting dictionary, each character in x will be mapped\n   to the character at the same position in y.  If there is a third\n   argument, it must be a string, whose characters will be mapped to\n   None in the result.\n\nstr.partition(sep)\n\n   Split the string at the first occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing the string itself, followed by\n   two empty strings.\n\nstr.replace(old, new[, count])\n\n   Return a copy of the string with all occurrences of substring *old*\n   replaced by *new*.  If the optional argument *count* is given, only\n   the first *count* occurrences are replaced.\n\nstr.rfind(sub[, start[, end]])\n\n   Return the highest index in the string where substring *sub* is\n   found, such that *sub* is contained within ``s[start:end]``.\n   Optional arguments *start* and *end* are interpreted as in slice\n   notation.  Return ``-1`` on failure.\n\nstr.rindex(sub[, start[, end]])\n\n   Like ``rfind()`` but raises ``ValueError`` when the substring *sub*\n   is not found.\n\nstr.rjust(width[, fillchar])\n\n   Return the string right justified in a string of length *width*.\n   Padding is done using the specified *fillchar* (default is a\n   space). The original string is returned if *width* is less than\n   ``len(s)``.\n\nstr.rpartition(sep)\n\n   Split the string at the last occurrence of *sep*, and return a\n   3-tuple containing the part before the separator, the separator\n   itself, and the part after the separator.  If the separator is not\n   found, return a 3-tuple containing two empty strings, followed by\n   the string itself.\n\nstr.rsplit([sep[, maxsplit]])\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string. If *maxsplit* is given, at most *maxsplit* splits\n   are done, the *rightmost* ones.  If *sep* is not specified or\n   ``None``, any whitespace string is a separator.  Except for\n   splitting from the right, ``rsplit()`` behaves like ``split()``\n   which is described in detail below.\n\nstr.rstrip([chars])\n\n   Return a copy of the string with trailing characters removed.  The\n   *chars* argument is a string specifying the set of characters to be\n   removed.  If omitted or ``None``, the *chars* argument defaults to\n   removing whitespace.  The *chars* argument is not a suffix; rather,\n   all combinations of its values are stripped:\n\n   >>> \'   spacious   \'.rstrip()\n   \'   spacious\'\n   >>> \'mississippi\'.rstrip(\'ipz\')\n   \'mississ\'\n\nstr.split([sep[, maxsplit]])\n\n   Return a list of the words in the string, using *sep* as the\n   delimiter string.  If *maxsplit* is given, at most *maxsplit*\n   splits are done (thus, the list will have at most ``maxsplit+1``\n   elements).  If *maxsplit* is not specified, then there is no limit\n   on the number of splits (all possible splits are made).\n\n   If *sep* is given, consecutive delimiters are not grouped together\n   and are deemed to delimit empty strings (for example,\n   ``\'1,,2\'.split(\',\')`` returns ``[\'1\', \'\', \'2\']``).  The *sep*\n   argument may consist of multiple characters (for example,\n   ``\'1<>2<>3\'.split(\'<>\')`` returns ``[\'1\', \'2\', \'3\']``). Splitting\n   an empty string with a specified separator returns ``[\'\']``.\n\n   If *sep* is not specified or is ``None``, a different splitting\n   algorithm is applied: runs of consecutive whitespace are regarded\n   as a single separator, and the result will contain no empty strings\n   at the start or end if the string has leading or trailing\n   whitespace.  Consequently, splitting an empty string or a string\n   consisting of just whitespace with a ``None`` separator returns\n   ``[]``.\n\n   For example, ``\' 1  2   3  \'.split()`` returns ``[\'1\', \'2\', \'3\']``,\n   and ``\'  1  2   3  \'.split(None, 1)`` returns ``[\'1\', \'2   3  \']``.\n\nstr.splitlines([keepends])\n\n   Return a list of the lines in the string, breaking at line\n   boundaries.  Line breaks are not included in the resulting list\n   unless *keepends* is given and true.\n\nstr.startswith(prefix[, start[, end]])\n\n   Return ``True`` if string starts with the *prefix*, otherwise\n   return ``False``. *prefix* can also be a tuple of prefixes to look\n   for.  With optional *start*, test string beginning at that\n   position.  With optional *end*, stop comparing string at that\n   position.\n\nstr.strip([chars])\n\n   Return a copy of the string with the leading and trailing\n   characters removed. The *chars* argument is a string specifying the\n   set of characters to be removed. If omitted or ``None``, the\n   *chars* argument defaults to removing whitespace. The *chars*\n   argument is not a prefix or suffix; rather, all combinations of its\n   values are stripped:\n\n   >>> \'   spacious   \'.strip()\n   \'spacious\'\n   >>> \'www.example.com\'.strip(\'cmowz.\')\n   \'example\'\n\nstr.swapcase()\n\n   Return a copy of the string with uppercase characters converted to\n   lowercase and vice versa.\n\nstr.title()\n\n   Return a titlecased version of the string where words start with an\n   uppercase character and the remaining characters are lowercase.\n\n   The algorithm uses a simple language-independent definition of a\n   word as groups of consecutive letters.  The definition works in\n   many contexts but it means that apostrophes in contractions and\n   possessives form word boundaries, which may not be the desired\n   result:\n\n      >>> "they\'re bill\'s friends from the UK".title()\n      "They\'Re Bill\'S Friends From The Uk"\n\n   A workaround for apostrophes can be constructed using regular\n   expressions:\n\n      >>> import re\n      >>> def titlecase(s):\n              return re.sub(r"[A-Za-z]+(\'[A-Za-z]+)?",\n                            lambda mo: mo.group(0)[0].upper() +\n                                       mo.group(0)[1:].lower(),\n                            s)\n\n      >>> titlecase("they\'re bill\'s friends.")\n      "They\'re Bill\'s Friends."\n\nstr.translate(map)\n\n   Return a copy of the *s* where all characters have been mapped\n   through the *map* which must be a dictionary of Unicode ordinals\n   (integers) to Unicode ordinals, strings or ``None``.  Unmapped\n   characters are left untouched. Characters mapped to ``None`` are\n   deleted.\n\n   You can use ``str.maketrans()`` to create a translation map from\n   character-to-character mappings in different formats.\n\n   Note: An even more flexible approach is to create a custom character\n     mapping codec using the ``codecs`` module (see\n     ``encodings.cp1251`` for an example).\n\nstr.upper()\n\n   Return a copy of the string converted to uppercase.\n\nstr.zfill(width)\n\n   Return the numeric string left filled with zeros in a string of\n   length *width*.  A sign prefix is handled correctly.  The original\n   string is returned if *width* is less than ``len(s)``.\n\n\nOld String Formatting Operations\n================================\n\nNote: The formatting operations described here are obsolete and may go\n  away in future versions of Python.  Use the new *String Formatting*\n  in new code.\n\nString objects have one unique built-in operation: the ``%`` operator\n(modulo). This is also known as the string *formatting* or\n*interpolation* operator. Given ``format % values`` (where *format* is\na string), ``%`` conversion specifications in *format* are replaced\nwith zero or more elements of *values*. The effect is similar to the\nusing ``sprintf()`` in the C language.\n\nIf *format* requires a single argument, *values* may be a single non-\ntuple object. [4]  Otherwise, *values* must be a tuple with exactly\nthe number of items specified by the format string, or a single\nmapping object (for example, a dictionary).\n\nA conversion specifier contains two or more characters and has the\nfollowing components, which must occur in this order:\n\n1. The ``\'%\'`` character, which marks the start of the specifier.\n\n2. Mapping key (optional), consisting of a parenthesised sequence of\n   characters (for example, ``(somename)``).\n\n3. Conversion flags (optional), which affect the result of some\n   conversion types.\n\n4. Minimum field width (optional).  If specified as an ``\'*\'``\n   (asterisk), the actual width is read from the next element of the\n   tuple in *values*, and the object to convert comes after the\n   minimum field width and optional precision.\n\n5. Precision (optional), given as a ``\'.\'`` (dot) followed by the\n   precision.  If specified as ``\'*\'`` (an asterisk), the actual width\n   is read from the next element of the tuple in *values*, and the\n   value to convert comes after the precision.\n\n6. Length modifier (optional).\n\n7. Conversion type.\n\nWhen the right argument is a dictionary (or other mapping type), then\nthe formats in the string *must* include a parenthesised mapping key\ninto that dictionary inserted immediately after the ``\'%\'`` character.\nThe mapping key selects the value to be formatted from the mapping.\nFor example:\n\n>>> print(\'%(language)s has %(number)03d quote types.\' %\n...       {\'language\': "Python", "number": 2})\nPython has 002 quote types.\n\nIn this case no ``*`` specifiers may occur in a format (since they\nrequire a sequential parameter list).\n\nThe conversion flag characters are:\n\n+-----------+-----------------------------------------------------------------------+\n| Flag      | Meaning                                                               |\n+===========+=======================================================================+\n| ``\'#\'``   | The value conversion will use the "alternate form" (where defined     |\n|           | below).                                                               |\n+-----------+-----------------------------------------------------------------------+\n| ``\'0\'``   | The conversion will be zero padded for numeric values.                |\n+-----------+-----------------------------------------------------------------------+\n| ``\'-\'``   | The converted value is left adjusted (overrides the ``\'0\'``           |\n|           | conversion if both are given).                                        |\n+-----------+-----------------------------------------------------------------------+\n| ``\' \'``   | (a space) A blank should be left before a positive number (or empty   |\n|           | string) produced by a signed conversion.                              |\n+-----------+-----------------------------------------------------------------------+\n| ``\'+\'``   | A sign character (``\'+\'`` or ``\'-\'``) will precede the conversion     |\n|           | (overrides a "space" flag).                                           |\n+-----------+-----------------------------------------------------------------------+\n\nA length modifier (``h``, ``l``, or ``L``) may be present, but is\nignored as it is not necessary for Python -- so e.g. ``%ld`` is\nidentical to ``%d``.\n\nThe conversion types are:\n\n+--------------+-------------------------------------------------------+---------+\n| Conversion   | Meaning                                               | Notes   |\n+==============+=======================================================+=========+\n| ``\'d\'``      | Signed integer decimal.                               |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'i\'``      | Signed integer decimal.                               |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'o\'``      | Signed octal value.                                   | (1)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'u\'``      | Obsolete type -- it is identical to ``\'d\'``.          | (7)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'x\'``      | Signed hexadecimal (lowercase).                       | (2)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'X\'``      | Signed hexadecimal (uppercase).                       | (2)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'e\'``      | Floating point exponential format (lowercase).        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'E\'``      | Floating point exponential format (uppercase).        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'f\'``      | Floating point decimal format.                        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'F\'``      | Floating point decimal format.                        | (3)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'g\'``      | Floating point format. Uses lowercase exponential     | (4)     |\n|              | format if exponent is less than -4 or not less than   |         |\n|              | precision, decimal format otherwise.                  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'G\'``      | Floating point format. Uses uppercase exponential     | (4)     |\n|              | format if exponent is less than -4 or not less than   |         |\n|              | precision, decimal format otherwise.                  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'c\'``      | Single character (accepts integer or single character |         |\n|              | string).                                              |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'r\'``      | String (converts any Python object using ``repr()``). | (5)     |\n+--------------+-------------------------------------------------------+---------+\n| ``\'s\'``      | String (converts any Python object using ``str()``).  |         |\n+--------------+-------------------------------------------------------+---------+\n| ``\'%\'``      | No argument is converted, results in a ``\'%\'``        |         |\n|              | character in the result.                              |         |\n+--------------+-------------------------------------------------------+---------+\n\nNotes:\n\n1. The alternate form causes a leading zero (``\'0\'``) to be inserted\n   between left-hand padding and the formatting of the number if the\n   leading character of the result is not already a zero.\n\n2. The alternate form causes a leading ``\'0x\'`` or ``\'0X\'`` (depending\n   on whether the ``\'x\'`` or ``\'X\'`` format was used) to be inserted\n   between left-hand padding and the formatting of the number if the\n   leading character of the result is not already a zero.\n\n3. The alternate form causes the result to always contain a decimal\n   point, even if no digits follow it.\n\n   The precision determines the number of digits after the decimal\n   point and defaults to 6.\n\n4. The alternate form causes the result to always contain a decimal\n   point, and trailing zeroes are not removed as they would otherwise\n   be.\n\n   The precision determines the number of significant digits before\n   and after the decimal point and defaults to 6.\n\n5. The precision determines the maximal number of characters used.\n\n1. See **PEP 237**.\n\nSince Python strings have an explicit length, ``%s`` conversions do\nnot assume that ``\'\\0\'`` is the end of the string.\n\nChanged in version 3.1: ``%f`` conversions for numbers whose absolute\nvalue is over 1e50 are no longer replaced by ``%g`` conversions.\n\nAdditional string operations are defined in standard modules\n``string`` and ``re``.\n\n\nRange Type\n==========\n\nThe ``range`` type is an immutable sequence which is commonly used for\nlooping.  The advantage of the ``range`` type is that an ``range``\nobject will always take the same amount of memory, no matter the size\nof the range it represents.\n\nRange objects have relatively little behavior: they support indexing,\ncontains, iteration, the ``len()`` function, and the following\nmethods:\n\nrange.count(x)\n\n   Return the number of *i*\'s for which ``s[i] == x``.\n\n      New in version 3.2.\n\nrange.index(x)\n\n   Return the smallest *i* such that ``s[i] == x``.  Raises\n   ``ValueError`` when *x* is not in the range.\n\n      New in version 3.2.\n\n\nMutable Sequence Types\n======================\n\nList and bytearray objects support additional operations that allow\nin-place modification of the object.  Other mutable sequence types\n(when added to the language) should also support these operations.\nStrings and tuples are immutable sequence types: such objects cannot\nbe modified once created. The following operations are defined on\nmutable sequence types (where *x* is an arbitrary object).\n\nNote that while lists allow their items to be of any type, bytearray\nobject "items" are all integers in the range 0 <= x < 256.\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| ``s[i] = x``                   | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t``                 | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]``                 | same as ``s[i:j] = []``          |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t``               | the elements of ``s[i:j:k]`` are | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]``               | removes the elements of          |                       |\n|                                | ``s[i:j:k]`` from the list       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)``                | same as ``s[len(s):len(s)] =     |                       |\n|                                | [x]``                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)``                | same as ``s[len(s):len(s)] = x`` | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)``                 | return number of *i*\'s for which |                       |\n|                                | ``s[i] == x``                    |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])``       | return smallest *k* such that    | (3)                   |\n|                                | ``s[k] == x`` and ``i <= k < j`` |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)``             | same as ``s[i:i] = [x]``         | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])``                 | same as ``x = s[i]; del s[i];    | (5)                   |\n|                                | return x``                       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)``                | same as ``del s[s.index(x)]``    | (3)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()``                | reverses the items of *s* in     | (6)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([key[, reverse]])``   | sort the items of *s* in place   | (6), (7), (8)         |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. *x* can be any iterable object.\n\n3. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n   index is passed as the second or third parameter to the ``index()``\n   method, the sequence length is added, as for slice indices.  If it\n   is still negative, it is truncated to zero, as for slice indices.\n\n4. When a negative index is passed as the first parameter to the\n   ``insert()`` method, the sequence length is added, as for slice\n   indices.  If it is still negative, it is truncated to zero, as for\n   slice indices.\n\n5. The optional argument *i* defaults to ``-1``, so that by default\n   the last item is removed and returned.\n\n6. The ``sort()`` and ``reverse()`` methods modify the sequence in\n   place for economy of space when sorting or reversing a large\n   sequence.  To remind you that they operate by side effect, they\n   don\'t return the sorted or reversed sequence.\n\n7. The ``sort()`` method takes optional arguments for controlling the\n   comparisons.  Each must be specified as a keyword argument.\n\n   *key* specifies a function of one argument that is used to extract\n   a comparison key from each list element: ``key=str.lower``.  The\n   default value is ``None``. Use ``functools.cmp_to_key()`` to\n   convert an old-style *cmp* function to a *key* function.\n\n   *reverse* is a boolean value.  If set to ``True``, then the list\n   elements are sorted as if each comparison were reversed.\n\n   The ``sort()`` method is guaranteed to be stable.  A sort is stable\n   if it guarantees not to change the relative order of elements that\n   compare equal --- this is helpful for sorting in multiple passes\n   (for example, sort by department, then by salary grade).\n\n   **CPython implementation detail:** While a list is being sorted,\n   the effect of attempting to mutate, or even inspect, the list is\n   undefined.  The C implementation of Python makes the list appear\n   empty for the duration, and raises ``ValueError`` if it can detect\n   that the list has been mutated during a sort.\n\n8. ``sort()`` is not supported by ``bytearray`` objects.\n\n\nBytes and Byte Array Methods\n============================\n\nBytes and bytearray objects, being "strings of bytes", have all\nmethods found on strings, with the exception of ``encode()``,\n``format()`` and ``isidentifier()``, which do not make sense with\nthese types.  For converting the objects to strings, they have a\n``decode()`` method.\n\nWherever one of these methods needs to interpret the bytes as\ncharacters (e.g. the ``is...()`` methods), the ASCII character set is\nassumed.\n\nNote: The methods on bytes and bytearray objects don\'t accept strings as\n  their arguments, just as the methods on strings don\'t accept bytes\n  as their arguments.  For example, you have to write\n\n     a = "abc"\n     b = a.replace("a", "f")\n\n  and\n\n     a = b"abc"\n     b = a.replace(b"a", b"f")\n\nbytes.decode(encoding="utf-8", errors="strict")\nbytearray.decode(encoding="utf-8", errors="strict")\n\n   Return a string decoded from the given bytes.  Default encoding is\n   ``\'utf-8\'``. *errors* may be given to set a different error\n   handling scheme.  The default for *errors* is ``\'strict\'``, meaning\n   that encoding errors raise a ``UnicodeError``.  Other possible\n   values are ``\'ignore\'``, ``\'replace\'`` and any other name\n   registered via ``codecs.register_error()``, see section *Codec Base\n   Classes*. For a list of possible encodings, see section *Standard\n   Encodings*.\n\n   Changed in version 3.1: Added support for keyword arguments.\n\nThe bytes and bytearray types have an additional class method:\n\nclassmethod bytes.fromhex(string)\nclassmethod bytearray.fromhex(string)\n\n   This ``bytes`` class method returns a bytes or bytearray object,\n   decoding the given string object.  The string must contain two\n   hexadecimal digits per byte, spaces are ignored.\n\n   >>> bytes.fromhex(\'f0 f1f2  \')\n   b\'\\xf0\\xf1\\xf2\'\n\nThe maketrans and translate methods differ in semantics from the\nversions available on strings:\n\nbytes.translate(table[, delete])\nbytearray.translate(table[, delete])\n\n   Return a copy of the bytes or bytearray object where all bytes\n   occurring in the optional argument *delete* are removed, and the\n   remaining bytes have been mapped through the given translation\n   table, which must be a bytes object of length 256.\n\n   You can use the ``bytes.maketrans()`` method to create a\n   translation table.\n\n   Set the *table* argument to ``None`` for translations that only\n   delete characters:\n\n      >>> b\'read this short text\'.translate(None, b\'aeiou\')\n      b\'rd ths shrt txt\'\n\nstatic bytes.maketrans(from, to)\nstatic bytearray.maketrans(from, to)\n\n   This static method returns a translation table usable for\n   ``bytes.translate()`` that will map each character in *from* into\n   the character at the same position in *to*; *from* and *to* must be\n   bytes objects and have the same length.\n\n   New in version 3.1.\n',
  'typesseq-mutable': '\nMutable Sequence Types\n**********************\n\nList and bytearray objects support additional operations that allow\nin-place modification of the object.  Other mutable sequence types\n(when added to the language) should also support these operations.\nStrings and tuples are immutable sequence types: such objects cannot\nbe modified once created. The following operations are defined on\nmutable sequence types (where *x* is an arbitrary object).\n\nNote that while lists allow their items to be of any type, bytearray\nobject "items" are all integers in the range 0 <= x < 256.\n\n+--------------------------------+----------------------------------+-----------------------+\n| Operation                      | Result                           | Notes                 |\n+================================+==================================+=======================+\n| ``s[i] = x``                   | item *i* of *s* is replaced by   |                       |\n|                                | *x*                              |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j] = t``                 | slice of *s* from *i* to *j* is  |                       |\n|                                | replaced by the contents of the  |                       |\n|                                | iterable *t*                     |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j]``                 | same as ``s[i:j] = []``          |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s[i:j:k] = t``               | the elements of ``s[i:j:k]`` are | (1)                   |\n|                                | replaced by those of *t*         |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``del s[i:j:k]``               | removes the elements of          |                       |\n|                                | ``s[i:j:k]`` from the list       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.append(x)``                | same as ``s[len(s):len(s)] =     |                       |\n|                                | [x]``                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.extend(x)``                | same as ``s[len(s):len(s)] = x`` | (2)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.count(x)``                 | return number of *i*\'s for which |                       |\n|                                | ``s[i] == x``                    |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.index(x[, i[, j]])``       | return smallest *k* such that    | (3)                   |\n|                                | ``s[k] == x`` and ``i <= k < j`` |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.insert(i, x)``             | same as ``s[i:i] = [x]``         | (4)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.pop([i])``                 | same as ``x = s[i]; del s[i];    | (5)                   |\n|                                | return x``                       |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.remove(x)``                | same as ``del s[s.index(x)]``    | (3)                   |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.reverse()``                | reverses the items of *s* in     | (6)                   |\n|                                | place                            |                       |\n+--------------------------------+----------------------------------+-----------------------+\n| ``s.sort([key[, reverse]])``   | sort the items of *s* in place   | (6), (7), (8)         |\n+--------------------------------+----------------------------------+-----------------------+\n\nNotes:\n\n1. *t* must have the same length as the slice it is replacing.\n\n2. *x* can be any iterable object.\n\n3. Raises ``ValueError`` when *x* is not found in *s*. When a negative\n   index is passed as the second or third parameter to the ``index()``\n   method, the sequence length is added, as for slice indices.  If it\n   is still negative, it is truncated to zero, as for slice indices.\n\n4. When a negative index is passed as the first parameter to the\n   ``insert()`` method, the sequence length is added, as for slice\n   indices.  If it is still negative, it is truncated to zero, as for\n   slice indices.\n\n5. The optional argument *i* defaults to ``-1``, so that by default\n   the last item is removed and returned.\n\n6. The ``sort()`` and ``reverse()`` methods modify the sequence in\n   place for economy of space when sorting or reversing a large\n   sequence.  To remind you that they operate by side effect, they\n   don\'t return the sorted or reversed sequence.\n\n7. The ``sort()`` method takes optional arguments for controlling the\n   comparisons.  Each must be specified as a keyword argument.\n\n   *key* specifies a function of one argument that is used to extract\n   a comparison key from each list element: ``key=str.lower``.  The\n   default value is ``None``. Use ``functools.cmp_to_key()`` to\n   convert an old-style *cmp* function to a *key* function.\n\n   *reverse* is a boolean value.  If set to ``True``, then the list\n   elements are sorted as if each comparison were reversed.\n\n   The ``sort()`` method is guaranteed to be stable.  A sort is stable\n   if it guarantees not to change the relative order of elements that\n   compare equal --- this is helpful for sorting in multiple passes\n   (for example, sort by department, then by salary grade).\n\n   **CPython implementation detail:** While a list is being sorted,\n   the effect of attempting to mutate, or even inspect, the list is\n   undefined.  The C implementation of Python makes the list appear\n   empty for the duration, and raises ``ValueError`` if it can detect\n   that the list has been mutated during a sort.\n\n8. ``sort()`` is not supported by ``bytearray`` objects.\n',
  'unary': '\nUnary arithmetic and bitwise operations\n***************************************\n\nAll unary arithmetic and bitwise operations have the same priority:\n\n   u_expr ::= power | "-" u_expr | "+" u_expr | "~" u_expr\n\nThe unary ``-`` (minus) operator yields the negation of its numeric\nargument.\n\nThe unary ``+`` (plus) operator yields its numeric argument unchanged.\n\nThe unary ``~`` (invert) operator yields the bitwise inversion of its\ninteger argument.  The bitwise inversion of ``x`` is defined as\n``-(x+1)``.  It only applies to integral numbers.\n\nIn all three cases, if the argument does not have the proper type, a\n``TypeError`` exception is raised.\n',
  'while': '\nThe ``while`` statement\n***********************\n\nThe ``while`` statement is used for repeated execution as long as an\nexpression is true:\n\n   while_stmt ::= "while" expression ":" suite\n                  ["else" ":" suite]\n\nThis repeatedly tests the expression and, if it is true, executes the\nfirst suite; if the expression is false (which may be the first time\nit is tested) the suite of the ``else`` clause, if present, is\nexecuted and the loop terminates.\n\nA ``break`` statement executed in the first suite terminates the loop\nwithout executing the ``else`` clause\'s suite.  A ``continue``\nstatement executed in the first suite skips the rest of the suite and\ngoes back to testing the expression.\n',

Modified: python/branches/pep-3151/Lib/random.py
==============================================================================
--- python/branches/pep-3151/Lib/random.py	(original)
+++ python/branches/pep-3151/Lib/random.py	Sat Feb 26 08:16:32 2011
@@ -42,7 +42,8 @@
 from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
 from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
 from os import urandom as _urandom
-import collections as _collections
+from collections.abc import Set as _Set, Sequence as _Sequence
+from hashlib import sha512 as _sha512
 
 __all__ = ["Random","seed","random","uniform","randint","choice","sample",
            "randrange","shuffle","normalvariate","lognormvariate",
@@ -110,10 +111,12 @@
                 import time
                 a = int(time.time() * 256) # use fractional seconds
 
-        if version == 2 and isinstance(a, (str, bytes, bytearray)):
-            if isinstance(a, str):
-                a = a.encode("utf8")
-            a = int.from_bytes(a, 'big')
+        if version == 2:
+            if isinstance(a, (str, bytes, bytearray)):
+                if isinstance(a, str):
+                    a = a.encode("utf-8")
+                a += _sha512(a).digest()
+                a = int.from_bytes(a, 'big')
 
         super().seed(a)
         self.gauss_next = None
@@ -290,10 +293,10 @@
         # preferred since the list takes less space than the
         # set and it doesn't suffer from frequent reselections.
 
-        if isinstance(population, _collections.Set):
+        if isinstance(population, _Set):
             population = tuple(population)
-        if not isinstance(population, _collections.Sequence):
-            raise TypeError("Population must be a sequence or Set.  For dicts, use list(d).")
+        if not isinstance(population, _Sequence):
+            raise TypeError("Population must be a sequence or set.  For dicts, use list(d).")
         randbelow = self._randbelow
         n = len(population)
         if not 0 <= k <= n:

Modified: python/branches/pep-3151/Lib/reprlib.py
==============================================================================
--- python/branches/pep-3151/Lib/reprlib.py	(original)
+++ python/branches/pep-3151/Lib/reprlib.py	Sat Feb 26 08:16:32 2011
@@ -30,6 +30,7 @@
         wrapper.__module__ = getattr(user_function, '__module__')
         wrapper.__doc__ = getattr(user_function, '__doc__')
         wrapper.__name__ = getattr(user_function, '__name__')
+        wrapper.__annotations__ = getattr(user_function, '__annotations__', {})
         return wrapper
 
     return decorating_function

Modified: python/branches/pep-3151/Lib/shelve.py
==============================================================================
--- python/branches/pep-3151/Lib/shelve.py	(original)
+++ python/branches/pep-3151/Lib/shelve.py	Sat Feb 26 08:16:32 2011
@@ -73,6 +73,7 @@
     def __repr__(self):
         return '<Closed Dictionary>'
 
+
 class Shelf(collections.MutableMapping):
     """Base class for shelf implementations.
 
@@ -88,7 +89,7 @@
         self._protocol = protocol
         self.writeback = writeback
         self.cache = {}
-        self.keyencoding = "utf-8"
+        self.keyencoding = keyencoding
 
     def __iter__(self):
         for k in self.dict.keys():

Modified: python/branches/pep-3151/Lib/shutil.py
==============================================================================
--- python/branches/pep-3151/Lib/shutil.py	(original)
+++ python/branches/pep-3151/Lib/shutil.py	Sat Feb 26 08:16:32 2011
@@ -370,7 +370,7 @@
     archive that is being built. If not provided, the current owner and group
     will be used.
 
-    The output tar file will be named 'base_dir' +  ".tar", possibly plus
+    The output tar file will be named 'base_name' +  ".tar", possibly plus
     the appropriate compression extension (".gz", or ".bz2").
 
     Returns the output filename.
@@ -391,7 +391,8 @@
     archive_dir = os.path.dirname(archive_name)
 
     if not os.path.exists(archive_dir):
-        logger.info("creating %s" % archive_dir)
+        if logger is not None:
+            logger.info("creating %s" % archive_dir)
         if not dry_run:
             os.makedirs(archive_dir)
 
@@ -440,7 +441,7 @@
 def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None):
     """Create a zip file from all the files under 'base_dir'.
 
-    The output zip file will be named 'base_dir' + ".zip".  Uses either the
+    The output zip file will be named 'base_name' + ".zip".  Uses either the
     "zipfile" Python module (if available) or the InfoZIP "zip" utility
     (if installed and found on the default search path).  If neither tool is
     available, raises ExecError.  Returns the name of the output zip

Modified: python/branches/pep-3151/Lib/site.py
==============================================================================
--- python/branches/pep-3151/Lib/site.py	(original)
+++ python/branches/pep-3151/Lib/site.py	Sat Feb 26 08:16:32 2011
@@ -55,6 +55,7 @@
 import sys
 import os
 import builtins
+import traceback
 
 # Prefixes for site-packages; add additional prefixes like /usr/local here
 PREFIXES = [sys.prefix, sys.exec_prefix]
@@ -141,17 +142,26 @@
     except IOError:
         return
     with f:
-        for line in f:
+        for n, line in enumerate(f):
             if line.startswith("#"):
                 continue
-            if line.startswith(("import ", "import\t")):
-                exec(line)
-                continue
-            line = line.rstrip()
-            dir, dircase = makepath(sitedir, line)
-            if not dircase in known_paths and os.path.exists(dir):
-                sys.path.append(dir)
-                known_paths.add(dircase)
+            try:
+                if line.startswith(("import ", "import\t")):
+                    exec(line)
+                    continue
+                line = line.rstrip()
+                dir, dircase = makepath(sitedir, line)
+                if not dircase in known_paths and os.path.exists(dir):
+                    sys.path.append(dir)
+                    known_paths.add(dircase)
+            except Exception as err:
+                print("Error processing line {:d} of {}:\n".format(n+1, fullname),
+                      file=sys.stderr)
+                for record in traceback.format_exception(*sys.exc_info()):
+                    for line in record.splitlines():
+                        print('  '+line, file=sys.stderr)
+                print("\nRemainder of file ignored", file=sys.stderr)
+                break
     if reset:
         known_paths = None
     return known_paths

Modified: python/branches/pep-3151/Lib/smtpd.py
==============================================================================
--- python/branches/pep-3151/Lib/smtpd.py	(original)
+++ python/branches/pep-3151/Lib/smtpd.py	Sat Feb 26 08:16:32 2011
@@ -109,6 +109,9 @@
     COMMAND = 0
     DATA = 1
 
+    data_size_limit = 33554432
+    command_size_limit = 512
+
     def __init__(self, server, conn, addr):
         asynchat.async_chat.__init__(self, conn)
         self.smtp_server = server
@@ -121,6 +124,7 @@
         self.rcpttos = []
         self.received_data = ''
         self.fqdn = socket.getfqdn()
+        self.num_bytes = 0
         try:
             self.peer = conn.getpeername()
         except socket.error as err:
@@ -262,7 +266,16 @@
 
     # Implementation of base class abstract method
     def collect_incoming_data(self, data):
-        self.received_lines.append(str(data, "utf8"))
+        limit = None
+        if self.smtp_state == self.COMMAND:
+            limit = self.command_size_limit
+        elif self.smtp_state == self.DATA:
+            limit = self.data_size_limit
+        if limit and self.num_bytes > limit:
+            return
+        elif limit:
+            self.num_bytes += len(data)
+        self.received_lines.append(str(data, "utf-8"))
 
     # Implementation of base class abstract method
     def found_terminator(self):
@@ -270,6 +283,11 @@
         print('Data:', repr(line), file=DEBUGSTREAM)
         self.received_lines = []
         if self.smtp_state == self.COMMAND:
+            if self.num_bytes > self.command_size_limit:
+                self.push('500 Error: line too long')
+                self.num_bytes = 0
+                return
+            self.num_bytes = 0
             if not line:
                 self.push('500 Error: bad syntax')
                 return
@@ -290,6 +308,11 @@
         else:
             if self.smtp_state != self.DATA:
                 self.push('451 Internal confusion')
+                self.num_bytes = 0
+                return
+            if self.num_bytes > self.data_size_limit:
+                self.push('552 Error: Too much mail data')
+                self.num_bytes = 0
                 return
             # Remove extraneous carriage returns and de-transparency according
             # to RFC 821, Section 4.5.2.
@@ -307,6 +330,7 @@
             self.rcpttos = []
             self.mailfrom = None
             self.smtp_state = self.COMMAND
+            self.num_bytes = 0
             self.set_terminator(b'\r\n')
             if not status:
                 self.push('250 Ok')

Modified: python/branches/pep-3151/Lib/smtplib.py
==============================================================================
--- python/branches/pep-3151/Lib/smtplib.py	(original)
+++ python/branches/pep-3151/Lib/smtplib.py	Sat Feb 26 08:16:32 2011
@@ -52,15 +52,15 @@
 from email.base64mime import body_encode as encode_base64
 from sys import stderr
 
-__all__ = ["SMTPException","SMTPServerDisconnected","SMTPResponseException",
-           "SMTPSenderRefused","SMTPRecipientsRefused","SMTPDataError",
-           "SMTPConnectError","SMTPHeloError","SMTPAuthenticationError",
-           "quoteaddr","quotedata","SMTP"]
+__all__ = ["SMTPException", "SMTPServerDisconnected", "SMTPResponseException",
+           "SMTPSenderRefused", "SMTPRecipientsRefused", "SMTPDataError",
+           "SMTPConnectError", "SMTPHeloError", "SMTPAuthenticationError",
+           "quoteaddr", "quotedata", "SMTP"]
 
 SMTP_PORT = 25
 SMTP_SSL_PORT = 465
-CRLF="\r\n"
-bCRLF=b"\r\n"
+CRLF = "\r\n"
+bCRLF = b"\r\n"
 
 OLDSTYLE_AUTH = re.compile(r"auth=(.*)", re.I)
 
@@ -113,7 +113,7 @@
 
     def __init__(self, recipients):
         self.recipients = recipients
-        self.args = ( recipients,)
+        self.args = (recipients,)
 
 
 class SMTPDataError(SMTPResponseException):
@@ -142,7 +142,7 @@
         m = email.utils.parseaddr(addr)[1]
     except AttributeError:
         pass
-    if m == (None, None): # Indicates parse failure or AttributeError
+    if m == (None, None):  # Indicates parse failure or AttributeError
         # something weird here.. punt -ddm
         return "<%s>" % addr
     elif m is None:
@@ -185,7 +185,8 @@
             chr = None
             while chr != b"\n":
                 chr = self.sslobj.read(1)
-                if not chr: break
+                if not chr:
+                    break
                 str += chr
             return str
 
@@ -280,10 +281,11 @@
     def _get_socket(self, host, port, timeout):
         # This makes it simpler for SMTP_SSL to use the SMTP connect code
         # and just alter the socket connection bit.
-        if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
+        if self.debuglevel > 0:
+            print('connect:', (host, port), file=stderr)
         return socket.create_connection((host, port), timeout)
 
-    def connect(self, host='localhost', port = 0):
+    def connect(self, host='localhost', port=0):
         """Connect to a host on a given port.
 
         If the hostname ends with a colon (`:') followed by a number, and
@@ -297,20 +299,25 @@
         if not port and (host.find(':') == host.rfind(':')):
             i = host.rfind(':')
             if i >= 0:
-                host, port = host[:i], host[i+1:]
-                try: port = int(port)
+                host, port = host[:i], host[i + 1:]
+                try:
+                    port = int(port)
                 except ValueError:
                     raise socket.error("nonnumeric port")
-        if not port: port = self.default_port
-        if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
+        if not port:
+            port = self.default_port
+        if self.debuglevel > 0:
+            print('connect:', (host, port), file=stderr)
         self.sock = self._get_socket(host, port, self.timeout)
         (code, msg) = self.getreply()
-        if self.debuglevel > 0: print("connect:", msg, file=stderr)
+        if self.debuglevel > 0:
+            print("connect:", msg, file=stderr)
         return (code, msg)
 
     def send(self, s):
         """Send `s' to the server."""
-        if self.debuglevel > 0: print('send:', repr(s), file=stderr)
+        if self.debuglevel > 0:
+            print('send:', repr(s), file=stderr)
         if hasattr(self, 'sock') and self.sock:
             if isinstance(s, str):
                 s = s.encode("ascii")
@@ -343,7 +350,7 @@
 
         Raises SMTPServerDisconnected if end-of-file is reached.
         """
-        resp=[]
+        resp = []
         if self.file is None:
             self.file = self.sock.makefile('rb')
         while 1:
@@ -354,9 +361,10 @@
             if not line:
                 self.close()
                 raise SMTPServerDisconnected("Connection unexpectedly closed")
-            if self.debuglevel > 0: print('reply:', repr(line), file=stderr)
+            if self.debuglevel > 0:
+                print('reply:', repr(line), file=stderr)
             resp.append(line[4:].strip(b' \t\r\n'))
-            code=line[:3]
+            code = line[:3]
             # Check that the error code is syntactically correct.
             # Don't attempt to read a continuation line if it is broken.
             try:
@@ -370,12 +378,12 @@
 
         errmsg = b"\n".join(resp)
         if self.debuglevel > 0:
-            print('reply: retcode (%s); Msg: %s' % (errcode,errmsg), file=stderr)
+            print('reply: retcode (%s); Msg: %s' % (errcode, errmsg), file=stderr)
         return errcode, errmsg
 
     def docmd(self, cmd, args=""):
         """Send a command, and return its response code."""
-        self.putcmd(cmd,args)
+        self.putcmd(cmd, args)
         return self.getreply()
 
     # std smtp commands
@@ -385,9 +393,9 @@
         host.
         """
         self.putcmd("helo", name or self.local_hostname)
-        (code,msg)=self.getreply()
-        self.helo_resp=msg
-        return (code,msg)
+        (code, msg) = self.getreply()
+        self.helo_resp = msg
+        return (code, msg)
 
     def ehlo(self, name=''):
         """ SMTP 'ehlo' command.
@@ -396,20 +404,20 @@
         """
         self.esmtp_features = {}
         self.putcmd(self.ehlo_msg, name or self.local_hostname)
-        (code,msg)=self.getreply()
+        (code, msg) = self.getreply()
         # According to RFC1869 some (badly written)
         # MTA's will disconnect on an ehlo. Toss an exception if
         # that happens -ddm
         if code == -1 and len(msg) == 0:
             self.close()
             raise SMTPServerDisconnected("Server not connected")
-        self.ehlo_resp=msg
+        self.ehlo_resp = msg
         if code != 250:
-            return (code,msg)
-        self.does_esmtp=1
+            return (code, msg)
+        self.does_esmtp = 1
         #parse the ehlo response -ddm
         assert isinstance(self.ehlo_resp, bytes), repr(self.ehlo_resp)
-        resp=self.ehlo_resp.decode("latin-1").split('\n')
+        resp = self.ehlo_resp.decode("latin-1").split('\n')
         del resp[0]
         for each in resp:
             # To be able to communicate with as many SMTP servers as possible,
@@ -429,16 +437,16 @@
             # It's actually stricter, in that only spaces are allowed between
             # parameters, but were not going to check for that here.  Note
             # that the space isn't present if there are no parameters.
-            m=re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?',each)
+            m = re.match(r'(?P<feature>[A-Za-z0-9][A-Za-z0-9\-]*) ?', each)
             if m:
-                feature=m.group("feature").lower()
-                params=m.string[m.end("feature"):].strip()
+                feature = m.group("feature").lower()
+                params = m.string[m.end("feature"):].strip()
                 if feature == "auth":
                     self.esmtp_features[feature] = self.esmtp_features.get(feature, "") \
                             + " " + params
                 else:
-                    self.esmtp_features[feature]=params
-        return (code,msg)
+                    self.esmtp_features[feature] = params
+        return (code, msg)
 
     def has_extn(self, opt):
         """Does the server support a given SMTP service extension?"""
@@ -458,23 +466,23 @@
         """SMTP 'noop' command -- doesn't do anything :>"""
         return self.docmd("noop")
 
-    def mail(self,sender,options=[]):
+    def mail(self, sender, options=[]):
         """SMTP 'mail' command -- begins mail xfer session."""
         optionlist = ''
         if options and self.does_esmtp:
             optionlist = ' ' + ' '.join(options)
-        self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender) ,optionlist))
+        self.putcmd("mail", "FROM:%s%s" % (quoteaddr(sender), optionlist))
         return self.getreply()
 
-    def rcpt(self,recip,options=[]):
+    def rcpt(self, recip, options=[]):
         """SMTP 'rcpt' command -- indicates 1 recipient for this mail."""
         optionlist = ''
         if options and self.does_esmtp:
             optionlist = ' ' + ' '.join(options)
-        self.putcmd("rcpt","TO:%s%s" % (quoteaddr(recip),optionlist))
+        self.putcmd("rcpt", "TO:%s%s" % (quoteaddr(recip), optionlist))
         return self.getreply()
 
-    def data(self,msg):
+    def data(self, msg):
         """SMTP 'DATA' command -- sends message data to server.
 
         Automatically quotes lines beginning with a period per rfc821.
@@ -485,10 +493,11 @@
         '\r\n' characters.  If msg is bytes, it is transmitted as is.
         """
         self.putcmd("data")
-        (code,repl)=self.getreply()
-        if self.debuglevel >0 : print("data:", (code,repl), file=stderr)
+        (code, repl) = self.getreply()
+        if self.debuglevel > 0:
+            print("data:", (code, repl), file=stderr)
         if code != 354:
-            raise SMTPDataError(code,repl)
+            raise SMTPDataError(code, repl)
         else:
             if isinstance(msg, str):
                 msg = _fix_eols(msg).encode('ascii')
@@ -497,16 +506,17 @@
                 q = q + bCRLF
             q = q + b"." + bCRLF
             self.send(q)
-            (code,msg)=self.getreply()
-            if self.debuglevel >0 : print("data:", (code,msg), file=stderr)
-            return (code,msg)
+            (code, msg) = self.getreply()
+            if self.debuglevel > 0:
+                print("data:", (code, msg), file=stderr)
+            return (code, msg)
 
     def verify(self, address):
         """SMTP 'verify' command -- checks for address validity."""
         self.putcmd("vrfy", quoteaddr(address))
         return self.getreply()
     # a.k.a.
-    vrfy=verify
+    vrfy = verify
 
     def expn(self, address):
         """SMTP 'expn' command -- expands a mailing list."""
@@ -564,7 +574,6 @@
             s = "\0%s\0%s" % (user, password)
             return encode_base64(s.encode('ascii'), eol='')
 
-
         AUTH_PLAIN = "PLAIN"
         AUTH_CRAM_MD5 = "CRAM-MD5"
         AUTH_LOGIN = "LOGIN"
@@ -613,7 +622,7 @@
         # We could not login sucessfully. Return result of last attempt.
         raise SMTPAuthenticationError(code, resp)
 
-    def starttls(self, keyfile = None, certfile = None):
+    def starttls(self, keyfile=None, certfile=None):
         """Puts the connection to the SMTP server into TLS mode.
 
         If there has been no previous EHLO or HELO command this session, this
@@ -721,22 +730,22 @@
                 esmtp_opts.append("size=%d" % len(msg))
             for option in mail_options:
                 esmtp_opts.append(option)
-        (code,resp) = self.mail(from_addr, esmtp_opts)
+        (code, resp) = self.mail(from_addr, esmtp_opts)
         if code != 250:
             self.rset()
             raise SMTPSenderRefused(code, resp, from_addr)
-        senderrs={}
+        senderrs = {}
         if isinstance(to_addrs, str):
             to_addrs = [to_addrs]
         for each in to_addrs:
-            (code,resp)=self.rcpt(each, rcpt_options)
+            (code, resp) = self.rcpt(each, rcpt_options)
             if (code != 250) and (code != 251):
-                senderrs[each]=(code,resp)
-        if len(senderrs)==len(to_addrs):
+                senderrs[each] = (code, resp)
+        if len(senderrs) == len(to_addrs):
             # the server refused all our recipients
             self.rset()
             raise SMTPRecipientsRefused(senderrs)
-        (code,resp) = self.data(msg)
+        (code, resp) = self.data(msg)
         if code != 250:
             self.rset()
             raise SMTPDataError(code, resp)
@@ -770,7 +779,6 @@
         return self.sendmail(from_addr, to_addrs, flatmsg, mail_options,
                              rcpt_options)
 
-
     def close(self):
         """Close the connection to the SMTP server."""
         if self.file:
@@ -780,7 +788,6 @@
             self.sock.close()
         self.sock = None
 
-
     def quit(self):
         """Terminate the SMTP session."""
         res = self.docmd("quit")
@@ -806,7 +813,8 @@
             self.default_port = SMTP_SSL_PORT
 
         def _get_socket(self, host, port, timeout):
-            if self.debuglevel > 0: print('connect:', (host, port), file=stderr)
+            if self.debuglevel > 0:
+                print('connect:', (host, port), file=stderr)
             new_socket = socket.create_connection((host, port), timeout)
             new_socket = ssl.wrap_socket(new_socket, self.keyfile, self.certfile)
             self.file = SSLFakeFile(new_socket)
@@ -834,11 +842,11 @@
 
     ehlo_msg = "lhlo"
 
-    def __init__(self, host = '', port = LMTP_PORT, local_hostname = None):
+    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):
+    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)
@@ -848,13 +856,15 @@
             self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
             self.sock.connect(host)
         except socket.error as msg:
-            if self.debuglevel > 0: print('connect fail:', host, file=stderr)
+            if self.debuglevel > 0:
+                print('connect fail:', host, file=stderr)
             if self.sock:
                 self.sock.close()
             self.sock = None
             raise socket.error(msg)
         (code, msg) = self.getreply()
-        if self.debuglevel > 0: print('connect:', msg, file=stderr)
+        if self.debuglevel > 0:
+            print('connect:', msg, file=stderr)
         return (code, msg)
 
 
@@ -868,7 +878,7 @@
         return sys.stdin.readline().strip()
 
     fromaddr = prompt("From")
-    toaddrs  = prompt("To").split(',')
+    toaddrs = prompt("To").split(',')
     print("Enter message, end with ^D:")
     msg = ''
     while 1:

Modified: python/branches/pep-3151/Lib/socket.py
==============================================================================
--- python/branches/pep-3151/Lib/socket.py	(original)
+++ python/branches/pep-3151/Lib/socket.py	Sat Feb 26 08:16:32 2011
@@ -130,7 +130,13 @@
         For IP sockets, the address info is a pair (hostaddr, port).
         """
         fd, addr = self._accept()
-        return socket(self.family, self.type, self.proto, fileno=fd), addr
+        sock = socket(self.family, self.type, self.proto, fileno=fd)
+        # Issue #7995: if no default timeout is set and the listening
+        # socket had a (non-zero) timeout, force the new socket in blocking
+        # mode to override platform-specific socket flags inheritance.
+        if getdefaulttimeout() is None and self.gettimeout():
+            sock.setblocking(True)
+        return sock, addr
 
     def makefile(self, mode="r", buffering=None, *,
                  encoding=None, errors=None, newline=None):
@@ -251,6 +257,7 @@
         self._mode = mode
         self._reading = "r" in mode
         self._writing = "w" in mode
+        self._timeout_occurred = False
 
     def readinto(self, b):
         """Read up to len(b) bytes into the writable buffer *b* and return
@@ -262,9 +269,14 @@
         """
         self._checkClosed()
         self._checkReadable()
+        if self._timeout_occurred:
+            raise IOError("cannot read from timed out object")
         while True:
             try:
                 return self._sock.recv_into(b)
+            except timeout:
+                self._timeout_occurred = True
+                raise
             except error as e:
                 n = e.args[0]
                 if n == EINTR:
@@ -307,7 +319,10 @@
 
     @property
     def name(self):
-        return self.fileno()
+        if not self.closed:
+            return self.fileno()
+        else:
+            return -1
 
     @property
     def mode(self):

Modified: python/branches/pep-3151/Lib/sqlite3/test/dbapi.py
==============================================================================
--- python/branches/pep-3151/Lib/sqlite3/test/dbapi.py	(original)
+++ python/branches/pep-3151/Lib/sqlite3/test/dbapi.py	Sat Feb 26 08:16:32 2011
@@ -43,7 +43,7 @@
                          sqlite.paramstyle)
 
     def CheckWarning(self):
-        self.assert_(issubclass(sqlite.Warning, Exception),
+        self.assertTrue(issubclass(sqlite.Warning, Exception),
                      "Warning is not a subclass of Exception")
 
     def CheckError(self):

Modified: python/branches/pep-3151/Lib/sqlite3/test/types.py
==============================================================================
--- python/branches/pep-3151/Lib/sqlite3/test/types.py	(original)
+++ python/branches/pep-3151/Lib/sqlite3/test/types.py	Sat Feb 26 08:16:32 2011
@@ -85,7 +85,7 @@
             if isinstance(_val, bytes):
                 # sqlite3 always calls __init__ with a bytes created from a
                 # UTF-8 string when __conform__ was used to store the object.
-                _val = _val.decode('utf8')
+                _val = _val.decode('utf-8')
             self.val = _val
 
         def __cmp__(self, other):
@@ -291,7 +291,7 @@
         no row returned.
         """
         self.cur.execute("select * from test where 0 = 1")
-        self.assert_(self.cur.description[0][0] == "x")
+        self.assertEqual(self.cur.description[0][0], "x")
 
 class ObjectAdaptationTests(unittest.TestCase):
     def cast(obj):

Modified: python/branches/pep-3151/Lib/sre_parse.py
==============================================================================
--- python/branches/pep-3151/Lib/sre_parse.py	(original)
+++ python/branches/pep-3151/Lib/sre_parse.py	Sat Feb 26 08:16:32 2011
@@ -791,7 +791,7 @@
     else:
         # The tokenizer implicitly decodes bytes objects as latin-1, we must
         # therefore re-encode the final representation.
-        encode = lambda x: x.encode('latin1')
+        encode = lambda x: x.encode('latin-1')
     for c, s in p:
         if c is MARK:
             groupsappend((i, s))

Modified: python/branches/pep-3151/Lib/string.py
==============================================================================
--- python/branches/pep-3151/Lib/string.py	(original)
+++ python/branches/pep-3151/Lib/string.py	Sat Feb 26 08:16:32 2011
@@ -46,23 +46,7 @@
 
 ####################################################################
 import re as _re
-
-class _multimap:
-    """Helper class for combining multiple mappings.
-
-    Used by .{safe_,}substitute() to combine the mapping and keyword
-    arguments.
-    """
-    def __init__(self, primary, secondary):
-        self._primary = primary
-        self._secondary = secondary
-
-    def __getitem__(self, key):
-        try:
-            return self._primary[key]
-        except KeyError:
-            return self._secondary[key]
-
+from collections import ChainMap
 
 class _TemplateMetaclass(type):
     pattern = r"""
@@ -116,7 +100,7 @@
         if not args:
             mapping = kws
         elif kws:
-            mapping = _multimap(kws, args[0])
+            mapping = ChainMap(kws, args[0])
         else:
             mapping = args[0]
         # Helper function for .sub()
@@ -142,7 +126,7 @@
         if not args:
             mapping = kws
         elif kws:
-            mapping = _multimap(kws, args[0])
+            mapping = ChainMap(kws, args[0])
         else:
             mapping = args[0]
         # Helper function for .sub()

Modified: python/branches/pep-3151/Lib/struct.py
==============================================================================
--- python/branches/pep-3151/Lib/struct.py	(original)
+++ python/branches/pep-3151/Lib/struct.py	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
 __all__ = [
     # Functions
-    'calcsize', 'pack', 'unpack', 'unpack', 'unpack_from',
+    'calcsize', 'pack', 'pack_into', 'unpack', 'unpack_from',
 
     # Classes
     'Struct',

Modified: python/branches/pep-3151/Lib/subprocess.py
==============================================================================
--- python/branches/pep-3151/Lib/subprocess.py	(original)
+++ python/branches/pep-3151/Lib/subprocess.py	Sat Feb 26 08:16:32 2011
@@ -27,10 +27,10 @@
 
 class Popen(args, bufsize=0, executable=None,
             stdin=None, stdout=None, stderr=None,
-            preexec_fn=None, close_fds=False, shell=False,
+            preexec_fn=None, close_fds=True, shell=False,
             cwd=None, env=None, universal_newlines=False,
             startupinfo=None, creationflags=0,
-            restore_signals=True, start_new_session=False):
+            restore_signals=True, start_new_session=False, pass_fds=()):
 
 
 Arguments are:
@@ -39,12 +39,12 @@
 program to execute is normally the first item in the args sequence or
 string, but can be explicitly set by using the executable argument.
 
-On UNIX, with shell=False (default): In this case, the Popen class
+On POSIX, with shell=False (default): In this case, the Popen class
 uses os.execvp() to execute the child program.  args should normally
 be a sequence.  A string will be treated as a sequence with the string
 as the only item (the program to execute).
 
-On UNIX, with shell=True: If args is a string, it specifies the
+On POSIX, with shell=True: If args is a string, it specifies the
 command string to execute through the shell.  If args is a sequence,
 the first item specifies the command string, and any additional items
 will be treated as additional shell arguments.
@@ -73,14 +73,19 @@
 stderr data from the applications should be captured into the same
 file handle as for stdout.
 
-On UNIX, if preexec_fn is set to a callable object, this object will be
+On POSIX, if preexec_fn is set to a callable object, this object will be
 called in the child process just before the child is executed.  The use
 of preexec_fn is not thread safe, using it in the presence of threads
 could lead to a deadlock in the child process before the new executable
 is executed.
 
 If close_fds is true, all file descriptors except 0, 1 and 2 will be
-closed before the child process is executed.
+closed before the child process is executed.  The default for close_fds
+varies by platform:  Always true on POSIX.  True when stdin/stdout/stderr
+are None on Windows, false otherwise.
+
+pass_fds is an optional sequence of file descriptors to keep open between the
+parent and child.  Providing any pass_fds implicitly sets close_fds to true.
 
 if shell is true, the specified command will be executed through the
 shell.
@@ -88,12 +93,12 @@
 If cwd is not None, the current directory will be changed to cwd
 before the child is executed.
 
-On UNIX, if restore_signals is True all signals that Python sets to
+On POSIX, if restore_signals is True all signals that Python sets to
 SIG_IGN are restored to SIG_DFL in the child process before the exec.
 Currently this includes the SIGPIPE, SIGXFZ and SIGXFSZ signals.  This
 parameter does nothing on Windows.
 
-On UNIX, if start_new_session is True, the setsid() system call will be made
+On POSIX, if start_new_session is True, the setsid() system call will be made
 in the child process prior to executing the command.
 
 If env is not None, it defines the environment variables for the new
@@ -101,7 +106,7 @@
 
 If universal_newlines is true, the file objects stdout and stderr are
 opened as a text files, but lines may be terminated by any of '\n',
-the Unix end-of-line convention, '\r', the Macintosh convention or
+the Unix end-of-line convention, '\r', the old Macintosh convention or
 '\r\n', the Windows convention.  All of these external representations
 are seen as '\n' by the Python program.  Note: This feature is only
 available if Python is built with universal newline support (the
@@ -242,7 +247,7 @@
 returncode
     The child return code.  A None value indicates that the process
     hasn't terminated yet.  A negative value -N indicates that the
-    child was terminated by signal N (UNIX only).
+    child was terminated by signal N (POSIX only).
 
 
 Replacing older functions with the subprocess module
@@ -339,6 +344,7 @@
 import gc
 import signal
 import builtins
+import warnings
 
 # Exception classes used by this module.
 class CalledProcessError(Exception):
@@ -378,7 +384,6 @@
         import _posixsubprocess
     except ImportError:
         _posixsubprocess = None
-        import warnings
         warnings.warn("The _posixsubprocess module is not being used. "
                       "Child process reliability may suffer if your "
                       "program uses threads.", RuntimeWarning)
@@ -388,6 +393,23 @@
     # POSIX defines PIPE_BUF as >= 512.
     _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
 
+    _FD_CLOEXEC = getattr(fcntl, 'FD_CLOEXEC', 1)
+
+    def _set_cloexec(fd, cloexec):
+        old = fcntl.fcntl(fd, fcntl.F_GETFD)
+        if cloexec:
+            fcntl.fcntl(fd, fcntl.F_SETFD, old | _FD_CLOEXEC)
+        else:
+            fcntl.fcntl(fd, fcntl.F_SETFD, old & ~_FD_CLOEXEC)
+
+    if _posixsubprocess:
+        _create_pipe = _posixsubprocess.cloexec_pipe
+    else:
+        def _create_pipe():
+            fds = os.pipe()
+            _set_cloexec(fds[0], True)
+            _set_cloexec(fds[1], True)
+            return fds
 
 __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "getstatusoutput",
            "getoutput", "check_output", "CalledProcessError"]
@@ -562,7 +584,7 @@
 
 # Various tools for executing commands and looking at their output and status.
 #
-# NB This only works (and is only relevant) for UNIX.
+# NB This only works (and is only relevant) for POSIX.
 
 def getstatusoutput(cmd):
     """Return (status, output) of executing cmd in a shell.
@@ -602,13 +624,17 @@
     return getstatusoutput(cmd)[1]
 
 
+_PLATFORM_DEFAULT_CLOSE_FDS = object()
+
+
 class Popen(object):
     def __init__(self, args, bufsize=0, executable=None,
                  stdin=None, stdout=None, stderr=None,
-                 preexec_fn=None, close_fds=False, shell=False,
-                 cwd=None, env=None, universal_newlines=False,
+                 preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS,
+                 shell=False, cwd=None, env=None, universal_newlines=False,
                  startupinfo=None, creationflags=0,
-                 restore_signals=True, start_new_session=False):
+                 restore_signals=True, start_new_session=False,
+                 pass_fds=()):
         """Create new Popen instance."""
         _cleanup()
 
@@ -622,12 +648,24 @@
             if preexec_fn is not None:
                 raise ValueError("preexec_fn is not supported on Windows "
                                  "platforms")
-            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 if you redirect stdin/stdout/stderr")
+            any_stdio_set = (stdin is not None or stdout is not None or
+                             stderr is not None)
+            if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
+                if any_stdio_set:
+                    close_fds = False
+                else:
+                    close_fds = True
+            elif close_fds and any_stdio_set:
+                raise ValueError(
+                        "close_fds is not supported on Windows platforms"
+                        " if you redirect stdin/stdout/stderr")
         else:
             # POSIX
+            if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
+                close_fds = True
+            if pass_fds and not close_fds:
+                warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
+                close_fds = True
             if startupinfo is not None:
                 raise ValueError("startupinfo is only supported on Windows "
                                  "platforms")
@@ -661,13 +699,9 @@
          c2pread, c2pwrite,
          errread, errwrite) = self._get_handles(stdin, stdout, stderr)
 
-        self._execute_child(args, executable, preexec_fn, close_fds,
-                            cwd, env, universal_newlines,
-                            startupinfo, creationflags, shell,
-                            p2cread, p2cwrite,
-                            c2pread, c2pwrite,
-                            errread, errwrite,
-                            restore_signals, start_new_session)
+        # We wrap OS handles *before* launching the child, otherwise a
+        # quickly terminating child could make our fds unwrappable
+        # (see #8458).
 
         if mswindows:
             if p2cwrite != -1:
@@ -692,11 +726,39 @@
             if universal_newlines:
                 self.stderr = io.TextIOWrapper(self.stderr)
 
+        try:
+            self._execute_child(args, executable, preexec_fn, close_fds,
+                                pass_fds, cwd, env, universal_newlines,
+                                startupinfo, creationflags, shell,
+                                p2cread, p2cwrite,
+                                c2pread, c2pwrite,
+                                errread, errwrite,
+                                restore_signals, start_new_session)
+        except:
+            # Cleanup if the child failed starting
+            for f in filter(None, [self.stdin, self.stdout, self.stderr]):
+                try:
+                    f.close()
+                except EnvironmentError:
+                    # Ignore EBADF or other errors
+                    pass
+            raise
+
 
     def _translate_newlines(self, data, encoding):
         data = data.replace(b"\r\n", b"\n").replace(b"\r", b"\n")
         return data.decode(encoding)
 
+    def __enter__(self):
+        return self
+
+    def __exit__(self, type, value, traceback):
+        if self.stdout:
+            self.stdout.close()
+        if self.stderr:
+            self.stderr.close()
+        if self.stdin:
+            self.stdin.close()
 
     def __del__(self, _maxsize=sys.maxsize, _active=_active):
         if not self._child_created:
@@ -829,7 +891,7 @@
 
 
         def _execute_child(self, args, executable, preexec_fn, close_fds,
-                           cwd, env, universal_newlines,
+                           pass_fds, cwd, env, universal_newlines,
                            startupinfo, creationflags, shell,
                            p2cread, p2cwrite,
                            c2pread, c2pwrite,
@@ -837,6 +899,8 @@
                            unused_restore_signals, unused_start_new_session):
             """Execute program (MS Windows version)"""
 
+            assert not pass_fds, "pass_fds not supported on Windows."
+
             if not isinstance(args, str):
                 args = list2cmdline(args)
 
@@ -935,6 +999,7 @@
 
         def _readerthread(self, fh, buffer):
             buffer.append(fh.read())
+            fh.close()
 
 
         def _communicate(self, input):
@@ -1007,7 +1072,7 @@
             if stdin is None:
                 pass
             elif stdin == PIPE:
-                p2cread, p2cwrite = os.pipe()
+                p2cread, p2cwrite = _create_pipe()
             elif isinstance(stdin, int):
                 p2cread = stdin
             else:
@@ -1017,7 +1082,7 @@
             if stdout is None:
                 pass
             elif stdout == PIPE:
-                c2pread, c2pwrite = os.pipe()
+                c2pread, c2pwrite = _create_pipe()
             elif isinstance(stdout, int):
                 c2pwrite = stdout
             else:
@@ -1027,7 +1092,7 @@
             if stderr is None:
                 pass
             elif stderr == PIPE:
-                errread, errwrite = os.pipe()
+                errread, errwrite = _create_pipe()
             elif stderr == STDOUT:
                 errwrite = c2pwrite
             elif isinstance(stderr, int):
@@ -1041,23 +1106,18 @@
                     errread, errwrite)
 
 
-        def _set_cloexec_flag(self, fd):
-            try:
-                cloexec_flag = fcntl.FD_CLOEXEC
-            except AttributeError:
-                cloexec_flag = 1
-
-            old = fcntl.fcntl(fd, fcntl.F_GETFD)
-            fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
-
-
-        def _close_fds(self, but):
-            os.closerange(3, but)
-            os.closerange(but + 1, MAXFD)
+        def _close_fds(self, fds_to_keep):
+            start_fd = 3
+            for fd in sorted(fds_to_keep):
+                if fd >= start_fd:
+                    os.closerange(start_fd, fd)
+                    start_fd = fd + 1
+            if start_fd <= MAXFD:
+                os.closerange(start_fd, MAXFD)
 
 
         def _execute_child(self, args, executable, preexec_fn, close_fds,
-                           cwd, env, universal_newlines,
+                           pass_fds, cwd, env, universal_newlines,
                            startupinfo, creationflags, shell,
                            p2cread, p2cwrite,
                            c2pread, c2pwrite,
@@ -1081,10 +1141,9 @@
             # For transferring possible exec failure from child to parent.
             # Data format: "exception name:hex errno:description"
             # Pickle is not used; it is complex and involves memory allocation.
-            errpipe_read, errpipe_write = os.pipe()
+            errpipe_read, errpipe_write = _create_pipe()
             try:
                 try:
-                    self._set_cloexec_flag(errpipe_write)
 
                     if _posixsubprocess:
                         # We must avoid complex work that could involve
@@ -1105,9 +1164,11 @@
                             executable_list = tuple(
                                 os.path.join(os.fsencode(dir), executable)
                                 for dir in os.get_exec_path(env))
+                        fds_to_keep = set(pass_fds)
+                        fds_to_keep.add(errpipe_write)
                         self.pid = _posixsubprocess.fork_exec(
                                 args, executable_list,
-                                close_fds, cwd, env_list,
+                                close_fds, sorted(fds_to_keep), cwd, env_list,
                                 p2cread, p2cwrite, c2pread, c2pwrite,
                                 errread, errwrite,
                                 errpipe_read, errpipe_write,
@@ -1141,27 +1202,32 @@
                                 os.close(errpipe_read)
 
                                 # Dup fds for child
-                                if p2cread != -1:
-                                    os.dup2(p2cread, 0)
-                                if c2pwrite != -1:
-                                    os.dup2(c2pwrite, 1)
-                                if errwrite != -1:
-                                    os.dup2(errwrite, 2)
+                                def _dup2(a, b):
+                                    # dup2() removes the CLOEXEC flag but
+                                    # we must do it ourselves if dup2()
+                                    # would be a no-op (issue #10806).
+                                    if a == b:
+                                        _set_cloexec(a, False)
+                                    elif a != -1:
+                                        os.dup2(a, b)
+                                _dup2(p2cread, 0)
+                                _dup2(c2pwrite, 1)
+                                _dup2(errwrite, 2)
 
                                 # Close pipe fds.  Make sure we don't close the
                                 # same fd more than once, or standard fds.
-                                if p2cread != -1 and p2cread not in (0,):
-                                    os.close(p2cread)
-                                if (c2pwrite != -1 and
-                                    c2pwrite not in (p2cread, 1)):
-                                    os.close(c2pwrite)
-                                if (errwrite != -1 and
-                                    errwrite not in (p2cread, c2pwrite, 2)):
-                                    os.close(errwrite)
+                                closed = set()
+                                for fd in [p2cread, c2pwrite, errwrite]:
+                                    if fd > 2 and fd not in closed:
+                                        os.close(fd)
+                                        closed.add(fd)
 
                                 # Close all other fds, if asked for
                                 if close_fds:
-                                    self._close_fds(but=errpipe_write)
+                                    fds_to_keep = set(pass_fds)
+                                    fds_to_keep.add(errpipe_write)
+                                    self._close_fds(fds_to_keep)
+
 
                                 if cwd is not None:
                                     os.chdir(cwd)
@@ -1193,11 +1259,11 @@
                                 try:
                                     exc_type, exc_value = sys.exc_info()[:2]
                                     if isinstance(exc_value, OSError):
-                                        errno = exc_value.errno
+                                        errno_num = exc_value.errno
                                     else:
-                                        errno = 0
+                                        errno_num = 0
                                     message = '%s:%x:%s' % (exc_type.__name__,
-                                                            errno, exc_value)
+                                                            errno_num, exc_value)
                                     message = message.encode(errors="surrogatepass")
                                     os.write(errpipe_write, message)
                                 except Exception:
@@ -1236,7 +1302,11 @@
                 os.close(errpipe_read)
 
             if data:
-                _eintr_retry_call(os.waitpid, self.pid, 0)
+                try:
+                    _eintr_retry_call(os.waitpid, self.pid, 0)
+                except OSError as e:
+                    if e.errno != errno.ECHILD:
+                        raise
                 try:
                     exception_name, hex_errno, err_msg = data.split(b':', 2)
                 except ValueError:
@@ -1252,10 +1322,12 @@
                         os.close(fd)
                 err_msg = err_msg.decode(errors="surrogatepass")
                 if issubclass(child_exception_type, OSError) and hex_errno:
-                    errno = int(hex_errno, 16)
-                    if errno != 0:
-                        err_msg = os.strerror(errno)
-                    raise child_exception_type(errno, err_msg)
+                    errno_num = int(hex_errno, 16)
+                    if errno_num != 0:
+                        err_msg = os.strerror(errno_num)
+                        if errno_num == errno.ENOENT:
+                            err_msg += ': ' + repr(args[0])
+                    raise child_exception_type(errno_num, err_msg)
                 raise child_exception_type(err_msg)
 
 
@@ -1297,7 +1369,15 @@
             """Wait for child process to terminate.  Returns returncode
             attribute."""
             if self.returncode is None:
-                pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
+                try:
+                    pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
+                except OSError as e:
+                    if e.errno != errno.ECHILD:
+                        raise
+                    # This happens if SIGCLD is set to be ignored or waiting
+                    # for child processes has otherwise been disabled for our
+                    # process.  This child is dead, we can't get the status.
+                    sts = 0
                 self._handle_exitstatus(sts)
             return self.returncode
 

Modified: python/branches/pep-3151/Lib/sysconfig.py
==============================================================================
--- python/branches/pep-3151/Lib/sysconfig.py	(original)
+++ python/branches/pep-3151/Lib/sysconfig.py	Sat Feb 26 08:16:32 2011
@@ -25,8 +25,10 @@
         'platstdlib': '{platbase}/lib/python{py_version_short}',
         'purelib': '{base}/lib/python{py_version_short}/site-packages',
         'platlib': '{platbase}/lib/python{py_version_short}/site-packages',
-        'include': '{base}/include/python{py_version_short}',
-        'platinclude': '{platbase}/include/python{py_version_short}',
+        'include':
+            '{base}/include/python{py_version_short}{abiflags}',
+        'platinclude':
+            '{platbase}/include/python{py_version_short}{abiflags}',
         'scripts': '{base}/bin',
         'data': '{base}',
         },
@@ -314,9 +316,12 @@
 
 
 def get_makefile_filename():
+    """Return the path of the Makefile."""
     if _PYTHON_BUILD:
         return os.path.join(_PROJECT_BASE, "Makefile")
-    return os.path.join(get_path('stdlib'), "config", "Makefile")
+    return os.path.join(get_path('stdlib'),
+                        'config-{}{}'.format(_PY_VERSION_SHORT, sys.abiflags),
+                        'Makefile')
 
 
 def _init_posix(vars):
@@ -407,7 +412,7 @@
     return vars
 
 def get_config_h_filename():
-    """Returns the path of pyconfig.h."""
+    """Return the path of pyconfig.h."""
     if _PYTHON_BUILD:
         if os.name == "nt":
             inc_dir = os.path.join(_PROJECT_BASE, "PC")
@@ -418,17 +423,17 @@
     return os.path.join(inc_dir, 'pyconfig.h')
 
 def get_scheme_names():
-    """Returns a tuple containing the schemes names."""
+    """Return a tuple containing the schemes names."""
     schemes = list(_INSTALL_SCHEMES.keys())
     schemes.sort()
     return tuple(schemes)
 
 def get_path_names():
-    """Returns a tuple containing the paths names."""
+    """Return a tuple containing the paths names."""
     return _SCHEME_KEYS
 
 def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
-    """Returns a mapping containing an install scheme.
+    """Return a mapping containing an install scheme.
 
     ``scheme`` is the install scheme name. If not provided, it will
     return the default scheme for the current platform.
@@ -439,7 +444,7 @@
         return _INSTALL_SCHEMES[scheme]
 
 def get_path(name, scheme=_get_default_scheme(), vars=None, expand=True):
-    """Returns a path corresponding to the scheme.
+    """Return a path corresponding to the scheme.
 
     ``scheme`` is the install scheme name.
     """
@@ -470,6 +475,11 @@
         _CONFIG_VARS['base'] = _PREFIX
         _CONFIG_VARS['platbase'] = _EXEC_PREFIX
         _CONFIG_VARS['projectbase'] = _PROJECT_BASE
+        try:
+            _CONFIG_VARS['abiflags'] = sys.abiflags
+        except AttributeError:
+            # sys.abiflags may not be defined on all platforms.
+            _CONFIG_VARS['abiflags'] = ''
 
         if os.name in ('nt', 'os2'):
             _init_non_posix(_CONFIG_VARS)
@@ -756,7 +766,7 @@
         print('\t{0} = "{1}"'.format(key, value))
 
 def _main():
-    """Displays all information sysconfig detains."""
+    """Display all information sysconfig detains."""
     print('Platform: "{0}"'.format(get_platform()))
     print('Python version: "{0}"'.format(get_python_version()))
     print('Current installation scheme: "{0}"'.format(_get_default_scheme()))

Modified: python/branches/pep-3151/Lib/tabnanny.py
==============================================================================
--- python/branches/pep-3151/Lib/tabnanny.py	(original)
+++ python/branches/pep-3151/Lib/tabnanny.py	Sat Feb 26 08:16:32 2011
@@ -264,7 +264,7 @@
         return a
 
 def format_witnesses(w):
-    firsts = map(lambda tup: str(tup[0]), w)
+    firsts = (str(tup[0]) for tup in w)
     prefix = "at tab size"
     if len(w) > 1:
         prefix = prefix + "s"

Modified: python/branches/pep-3151/Lib/tarfile.py
==============================================================================
--- python/branches/pep-3151/Lib/tarfile.py	(original)
+++ python/branches/pep-3151/Lib/tarfile.py	Sat Feb 26 08:16:32 2011
@@ -760,9 +760,8 @@
                         self.map_index = 0
             length = min(size, stop - self.position)
             if data:
-                self.fileobj.seek(offset)
-                block = self.fileobj.read(stop - start)
-                buf += block[self.position - start:self.position + length]
+                self.fileobj.seek(offset + (self.position - start))
+                buf += self.fileobj.read(length)
             else:
                 buf += NUL * length
             size -= length
@@ -1085,7 +1084,7 @@
     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, XGLTYPE, "utf8")
+        return cls._create_pax_generic_header(pax_headers, XGLTYPE, "utf-8")
 
     def _posix_split_name(self, name):
         """Split a name longer than 100 chars into a prefix
@@ -1168,7 +1167,7 @@
         binary = False
         for keyword, value in pax_headers.items():
             try:
-                value.encode("utf8", "strict")
+                value.encode("utf-8", "strict")
             except UnicodeEncodeError:
                 binary = True
                 break
@@ -1179,13 +1178,13 @@
             records += b"21 hdrcharset=BINARY\n"
 
         for keyword, value in pax_headers.items():
-            keyword = keyword.encode("utf8")
+            keyword = keyword.encode("utf-8")
             if binary:
                 # Try to restore the original byte representation of `value'.
                 # Needless to say, that the encoding must match the string.
                 value = value.encode(encoding, "surrogateescape")
             else:
-                value = value.encode("utf8")
+                value = value.encode("utf-8")
 
             l = len(keyword) + len(value) + 3   # ' ' + '=' + '\n'
             n = p = 0
@@ -1394,7 +1393,7 @@
         # the translation to UTF-8 fails.
         match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)
         if match is not None:
-            pax_headers["hdrcharset"] = match.group(1).decode("utf8")
+            pax_headers["hdrcharset"] = match.group(1).decode("utf-8")
 
         # For the time being, we don't care about anything other than "BINARY".
         # The only other value that is currently allowed by the standard is
@@ -1403,7 +1402,7 @@
         if hdrcharset == "BINARY":
             encoding = tarfile.encoding
         else:
-            encoding = "utf8"
+            encoding = "utf-8"
 
         # Parse pax header information. A record looks like that:
         # "%d %s=%s\n" % (length, keyword, value). length is the size
@@ -1420,20 +1419,20 @@
             length = int(length)
             value = buf[match.end(2) + 1:match.start(1) + length - 1]
 
-            # Normally, we could just use "utf8" as the encoding and "strict"
+            # Normally, we could just use "utf-8" as the encoding and "strict"
             # as the error handler, but we better not take the risk. For
             # example, GNU tar <= 1.23 is known to store filenames it cannot
             # translate to UTF-8 as raw strings (unfortunately without a
             # hdrcharset=BINARY header).
             # We first try the strict standard encoding, and if that fails we
             # fall back on the user's encoding and error handler.
-            keyword = self._decode_pax_field(keyword, "utf8", "utf8",
+            keyword = self._decode_pax_field(keyword, "utf-8", "utf-8",
                     tarfile.errors)
             if keyword in PAX_NAME_FIELDS:
                 value = self._decode_pax_field(value, encoding, tarfile.encoding,
                         tarfile.errors)
             else:
-                value = self._decode_pax_field(value, "utf8", "utf8",
+                value = self._decode_pax_field(value, "utf-8", "utf-8",
                         tarfile.errors)
 
             pax_headers[keyword] = value
@@ -2025,7 +2024,7 @@
                     print("link to", tarinfo.linkname, end=' ')
             print()
 
-    def add(self, name, arcname=None, recursive=True, exclude=None, filter=None):
+    def add(self, name, arcname=None, recursive=True, exclude=None, *, filter=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.
@@ -2082,7 +2081,7 @@
             if recursive:
                 for f in os.listdir(name):
                     self.add(os.path.join(name, f), os.path.join(arcname, f),
-                            recursive, exclude, filter)
+                            recursive, exclude, filter=filter)
 
         else:
             self.addfile(tarinfo)

Modified: python/branches/pep-3151/Lib/telnetlib.py
==============================================================================
--- python/branches/pep-3151/Lib/telnetlib.py	(original)
+++ python/branches/pep-3151/Lib/telnetlib.py	Sat Feb 26 08:16:32 2011
@@ -236,7 +236,7 @@
 
         """
         if self.debuglevel > 0:
-            print('Telnet(%s,%d):' % (self.host, self.port), end=' ')
+            print('Telnet(%s,%s):' % (self.host, self.port), end=' ')
             if args:
                 print(msg % args)
             else:

Modified: python/branches/pep-3151/Lib/tempfile.py
==============================================================================
--- python/branches/pep-3151/Lib/tempfile.py	(original)
+++ python/branches/pep-3151/Lib/tempfile.py	Sat Feb 26 08:16:32 2011
@@ -29,6 +29,8 @@
 
 # Imports.
 
+import warnings as _warnings
+import sys as _sys
 import io as _io
 import os as _os
 import errno as _errno
@@ -617,22 +619,40 @@
     """
 
     def __init__(self, suffix="", prefix=template, dir=None):
-        self.name = mkdtemp(suffix, prefix, dir)
         self._closed = False
+        self.name = None # Handle mkdtemp throwing an exception
+        self.name = mkdtemp(suffix, prefix, dir)
+
+    def __repr__(self):
+        return "<{} {!r}>".format(self.__class__.__name__, self.name)
 
     def __enter__(self):
         return self.name
 
-    def cleanup(self):
-        if not self._closed:
-            self._rmtree(self.name)
+    def cleanup(self, _warn=False):
+        if self.name and not self._closed:
+            try:
+                self._rmtree(self.name)
+            except (TypeError, AttributeError) as ex:
+                # Issue #10188: Emit a warning on stderr
+                # if the directory could not be cleaned
+                # up due to missing globals
+                if "None" not in str(ex):
+                    raise
+                print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
+                      file=_sys.stderr)
+                return
             self._closed = True
+            if _warn:
+                self._warn("Implicitly cleaning up {!r}".format(self),
+                           ResourceWarning)
 
     def __exit__(self, exc, value, tb):
         self.cleanup()
 
-    __del__ = cleanup
-
+    def __del__(self):
+        # Issue a ResourceWarning if implicit cleanup needed
+        self.cleanup(_warn=True)
 
     # XXX (ncoghlan): The following code attempts to make
     # this class tolerant of the module nulling out process
@@ -644,6 +664,7 @@
     _remove = staticmethod(_os.remove)
     _rmdir = staticmethod(_os.rmdir)
     _os_error = _os.error
+    _warn = _warnings.warn
 
     def _rmtree(self, path):
         # Essentially a stripped down version of shutil.rmtree.  We can't

Modified: python/branches/pep-3151/Lib/test/buffer_tests.py
==============================================================================
--- python/branches/pep-3151/Lib/test/buffer_tests.py	(original)
+++ python/branches/pep-3151/Lib/test/buffer_tests.py	Sat Feb 26 08:16:32 2011
@@ -15,32 +15,32 @@
 
     def test_islower(self):
         self.assertFalse(self.marshal(b'').islower())
-        self.assert_(self.marshal(b'a').islower())
+        self.assertTrue(self.marshal(b'a').islower())
         self.assertFalse(self.marshal(b'A').islower())
         self.assertFalse(self.marshal(b'\n').islower())
-        self.assert_(self.marshal(b'abc').islower())
+        self.assertTrue(self.marshal(b'abc').islower())
         self.assertFalse(self.marshal(b'aBc').islower())
-        self.assert_(self.marshal(b'abc\n').islower())
+        self.assertTrue(self.marshal(b'abc\n').islower())
         self.assertRaises(TypeError, self.marshal(b'abc').islower, 42)
 
     def test_isupper(self):
         self.assertFalse(self.marshal(b'').isupper())
         self.assertFalse(self.marshal(b'a').isupper())
-        self.assert_(self.marshal(b'A').isupper())
+        self.assertTrue(self.marshal(b'A').isupper())
         self.assertFalse(self.marshal(b'\n').isupper())
-        self.assert_(self.marshal(b'ABC').isupper())
+        self.assertTrue(self.marshal(b'ABC').isupper())
         self.assertFalse(self.marshal(b'AbC').isupper())
-        self.assert_(self.marshal(b'ABC\n').isupper())
+        self.assertTrue(self.marshal(b'ABC\n').isupper())
         self.assertRaises(TypeError, self.marshal(b'abc').isupper, 42)
 
     def test_istitle(self):
         self.assertFalse(self.marshal(b'').istitle())
         self.assertFalse(self.marshal(b'a').istitle())
-        self.assert_(self.marshal(b'A').istitle())
+        self.assertTrue(self.marshal(b'A').istitle())
         self.assertFalse(self.marshal(b'\n').istitle())
-        self.assert_(self.marshal(b'A Titlecased Line').istitle())
-        self.assert_(self.marshal(b'A\nTitlecased Line').istitle())
-        self.assert_(self.marshal(b'A Titlecased, Line').istitle())
+        self.assertTrue(self.marshal(b'A Titlecased Line').istitle())
+        self.assertTrue(self.marshal(b'A\nTitlecased Line').istitle())
+        self.assertTrue(self.marshal(b'A Titlecased, Line').istitle())
         self.assertFalse(self.marshal(b'Not a capitalized String').istitle())
         self.assertFalse(self.marshal(b'Not\ta Titlecase String').istitle())
         self.assertFalse(self.marshal(b'Not--a Titlecase String').istitle())
@@ -50,31 +50,31 @@
     def test_isspace(self):
         self.assertFalse(self.marshal(b'').isspace())
         self.assertFalse(self.marshal(b'a').isspace())
-        self.assert_(self.marshal(b' ').isspace())
-        self.assert_(self.marshal(b'\t').isspace())
-        self.assert_(self.marshal(b'\r').isspace())
-        self.assert_(self.marshal(b'\n').isspace())
-        self.assert_(self.marshal(b' \t\r\n').isspace())
+        self.assertTrue(self.marshal(b' ').isspace())
+        self.assertTrue(self.marshal(b'\t').isspace())
+        self.assertTrue(self.marshal(b'\r').isspace())
+        self.assertTrue(self.marshal(b'\n').isspace())
+        self.assertTrue(self.marshal(b' \t\r\n').isspace())
         self.assertFalse(self.marshal(b' \t\r\na').isspace())
         self.assertRaises(TypeError, self.marshal(b'abc').isspace, 42)
 
     def test_isalpha(self):
         self.assertFalse(self.marshal(b'').isalpha())
-        self.assert_(self.marshal(b'a').isalpha())
-        self.assert_(self.marshal(b'A').isalpha())
+        self.assertTrue(self.marshal(b'a').isalpha())
+        self.assertTrue(self.marshal(b'A').isalpha())
         self.assertFalse(self.marshal(b'\n').isalpha())
-        self.assert_(self.marshal(b'abc').isalpha())
+        self.assertTrue(self.marshal(b'abc').isalpha())
         self.assertFalse(self.marshal(b'aBc123').isalpha())
         self.assertFalse(self.marshal(b'abc\n').isalpha())
         self.assertRaises(TypeError, self.marshal(b'abc').isalpha, 42)
 
     def test_isalnum(self):
         self.assertFalse(self.marshal(b'').isalnum())
-        self.assert_(self.marshal(b'a').isalnum())
-        self.assert_(self.marshal(b'A').isalnum())
+        self.assertTrue(self.marshal(b'a').isalnum())
+        self.assertTrue(self.marshal(b'A').isalnum())
         self.assertFalse(self.marshal(b'\n').isalnum())
-        self.assert_(self.marshal(b'123abc456').isalnum())
-        self.assert_(self.marshal(b'a1b3c').isalnum())
+        self.assertTrue(self.marshal(b'123abc456').isalnum())
+        self.assertTrue(self.marshal(b'a1b3c').isalnum())
         self.assertFalse(self.marshal(b'aBc000 ').isalnum())
         self.assertFalse(self.marshal(b'abc\n').isalnum())
         self.assertRaises(TypeError, self.marshal(b'abc').isalnum, 42)
@@ -82,8 +82,8 @@
     def test_isdigit(self):
         self.assertFalse(self.marshal(b'').isdigit())
         self.assertFalse(self.marshal(b'a').isdigit())
-        self.assert_(self.marshal(b'0').isdigit())
-        self.assert_(self.marshal(b'0123456789').isdigit())
+        self.assertTrue(self.marshal(b'0').isdigit())
+        self.assertTrue(self.marshal(b'0123456789').isdigit())
         self.assertFalse(self.marshal(b'0123456789a').isdigit())
 
         self.assertRaises(TypeError, self.marshal(b'abc').isdigit, 42)

Modified: python/branches/pep-3151/Lib/test/cmath_testcases.txt
==============================================================================
--- python/branches/pep-3151/Lib/test/cmath_testcases.txt	(original)
+++ python/branches/pep-3151/Lib/test/cmath_testcases.txt	Sat Feb 26 08:16:32 2011
@@ -733,10 +733,11 @@
 ---------------------------
 
 -- zeros
-atan0000 atan 0.0 0.0 -> 0.0 0.0
-atan0001 atan 0.0 -0.0 -> 0.0 -0.0
-atan0002 atan -0.0 0.0 -> -0.0 0.0
-atan0003 atan -0.0 -0.0 -> -0.0 -0.0
+-- These are tested in testAtanSign in test_cmath.py
+-- atan0000 atan 0.0 0.0 -> 0.0 0.0
+-- atan0001 atan 0.0 -0.0 -> 0.0 -0.0
+-- atan0002 atan -0.0 0.0 -> -0.0 0.0
+-- atan0003 atan -0.0 -0.0 -> -0.0 -0.0
 
 -- values along both sides of imaginary axis
 atan0010 atan 0.0 -9.8813129168249309e-324 -> 0.0 -9.8813129168249309e-324
@@ -896,10 +897,11 @@
 ---------------------------------------
 
 -- zeros
-atanh0000 atanh 0.0 0.0 -> 0.0 0.0
-atanh0001 atanh 0.0 -0.0 -> 0.0 -0.0
-atanh0002 atanh -0.0 0.0 -> -0.0 0.0
-atanh0003 atanh -0.0 -0.0 -> -0.0 -0.0
+-- These are tested in testAtanhSign in test_cmath.py
+-- atanh0000 atanh 0.0 0.0 -> 0.0 0.0
+-- atanh0001 atanh 0.0 -0.0 -> 0.0 -0.0
+-- atanh0002 atanh -0.0 0.0 -> -0.0 0.0
+-- atanh0003 atanh -0.0 -0.0 -> -0.0 -0.0
 
 -- values along both sides of real axis
 atanh0010 atanh -9.8813129168249309e-324 0.0 -> -9.8813129168249309e-324 0.0

Modified: python/branches/pep-3151/Lib/test/crashers/README
==============================================================================
--- python/branches/pep-3151/Lib/test/crashers/README	(original)
+++ python/branches/pep-3151/Lib/test/crashers/README	Sat Feb 26 08:16:32 2011
@@ -1,20 +1,16 @@
-This directory only contains tests for outstanding bugs that cause
-the interpreter to segfault.  Ideally this directory should always
-be empty.  Sometimes it may not be easy to fix the underlying cause.
+This directory only contains tests for outstanding bugs that cause the
+interpreter to segfault.  Ideally this directory should always be empty, but
+sometimes it may not be easy to fix the underlying cause and the bug is deemed
+too obscure to invest the effort.
 
 Each test should fail when run from the command line:
 
 	./python Lib/test/crashers/weakref_in_del.py
 
-Each test should have a link to the bug report:
-
-	# http://python.org/sf/BUG#
-
-Put as much info into a docstring or comments to help determine
-the cause of the failure.  Particularly note if the cause is
-system or environment dependent and what the variables are.
-
-Once the crash is fixed, the test case should be moved into an appropriate
-test (even if it was originally from the test suite).  This ensures the
-regression doesn't happen again.  And if it does, it should be easier
-to track down.
+Put as much info into a docstring or comments to help determine the cause of the
+failure, as well as a bugs.python.org issue number if it exists.  Particularly
+note if the cause is system or environment dependent and what the variables are.
+
+Once the crash is fixed, the test case should be moved into an appropriate test
+(even if it was originally from the test suite).  This ensures the regression
+doesn't happen again.  And if it does, it should be easier to track down.

Modified: python/branches/pep-3151/Lib/test/datetimetester.py
==============================================================================
--- python/branches/pep-3151/Lib/test/datetimetester.py	(original)
+++ python/branches/pep-3151/Lib/test/datetimetester.py	Sat Feb 26 08:16:32 2011
@@ -38,11 +38,6 @@
 INF = float("inf")
 NAN = float("nan")
 
-# decorator for skipping tests on non-IEEE 754 platforms
-requires_IEEE_754 = unittest.skipUnless(
-    float.__getformat__("double").startswith("IEEE"),
-    "test requires IEEE 754 doubles")
-
 
 #############################################################################
 # module tests
@@ -207,7 +202,7 @@
 
 
     def test_dst(self):
-        self.assertEqual(None, timezone.utc.dst(self.DT))
+        self.assertIsNone(timezone.utc.dst(self.DT))
 
         with self.assertRaises(TypeError): self.EST.dst('')
         with self.assertRaises(TypeError): self.EST.dst(5)
@@ -407,7 +402,7 @@
         self.assertRaises(ZeroDivisionError, lambda: a / 0.0)
         self.assertRaises(TypeError, lambda: a / '')
 
-    @requires_IEEE_754
+    @support.requires_IEEE_754
     def test_disallowed_special(self):
         a = timedelta(42)
         self.assertRaises(ValueError, a.__mul__, NAN)
@@ -589,7 +584,7 @@
         self.assertRaises(OverflowError, day.__truediv__, 1e-10)
         self.assertRaises(OverflowError, day.__truediv__, 9e-10)
 
-    @requires_IEEE_754
+    @support.requires_IEEE_754
     def _test_overflow_special(self):
         day = timedelta(1)
         self.assertRaises(OverflowError, day.__mul__, INF)
@@ -1289,10 +1284,10 @@
         self.assertTrue(self.theclass.max)
 
     def test_strftime_out_of_range(self):
-        # For nasty technical reasons, we can't handle years before 1900.
+        # For nasty technical reasons, we can't handle years before 1000.
         cls = self.theclass
-        self.assertEqual(cls(1900, 1, 1).strftime("%Y"), "1900")
-        for y in 1, 49, 51, 99, 100, 1000, 1899:
+        self.assertEqual(cls(1000, 1, 1).strftime("%Y"), "1000")
+        for y in 1, 49, 51, 99, 100, 999:
             self.assertRaises(ValueError, cls(y, 1, 1).strftime, "%Y")
 
     def test_replace(self):
@@ -2513,11 +2508,17 @@
 
         # Check that an invalid tzname result raises an exception.
         class Badtzname(tzinfo):
-            def tzname(self, dt): return 42
+            tz = 42
+            def tzname(self, dt): return self.tz
         t = time(2, 3, 4, tzinfo=Badtzname())
         self.assertEqual(t.strftime("%H:%M:%S"), "02:03:04")
         self.assertRaises(TypeError, t.strftime, "%Z")
 
+        # Issue #6697:
+        if '_Fast' in str(type(self)):
+            Badtzname.tz = '\ud800'
+            self.assertRaises(ValueError, t.strftime, "%Z")
+
     def test_hash_edge_cases(self):
         # Offsets that overflow a basic time.
         t1 = self.theclass(0, 1, 2, 3, tzinfo=FixedOffset(1439, ""))

Modified: python/branches/pep-3151/Lib/test/fork_wait.py
==============================================================================
--- python/branches/pep-3151/Lib/test/fork_wait.py	(original)
+++ python/branches/pep-3151/Lib/test/fork_wait.py	Sat Feb 26 08:16:32 2011
@@ -40,8 +40,8 @@
                 break
             time.sleep(2 * SHORTSLEEP)
 
-        self.assertEquals(spid, cpid)
-        self.assertEquals(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
+        self.assertEqual(spid, cpid)
+        self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
 
     def test_wait(self):
         for i in range(NUM_THREADS):
@@ -50,7 +50,7 @@
         time.sleep(LONGSLEEP)
 
         a = sorted(self.alive.keys())
-        self.assertEquals(a, list(range(NUM_THREADS)))
+        self.assertEqual(a, list(range(NUM_THREADS)))
 
         prefork_lives = self.alive.copy()
 

Modified: python/branches/pep-3151/Lib/test/list_tests.py
==============================================================================
--- python/branches/pep-3151/Lib/test/list_tests.py	(original)
+++ python/branches/pep-3151/Lib/test/list_tests.py	Sat Feb 26 08:16:32 2011
@@ -337,7 +337,7 @@
         self.assertRaises(BadExc, d.remove, 'c')
         for x, y in zip(d, e):
             # verify that original order and values are retained.
-            self.assert_(x is y)
+            self.assertIs(x, y)
 
     def test_count(self):
         a = self.type2test([0, 1, 2])*3
@@ -425,6 +425,47 @@
 
         self.assertRaises(TypeError, u.reverse, 42)
 
+    def test_clear(self):
+        u = self.type2test([2, 3, 4])
+        u.clear()
+        self.assertEqual(u, [])
+
+        u = self.type2test([])
+        u.clear()
+        self.assertEqual(u, [])
+
+        u = self.type2test([])
+        u.append(1)
+        u.clear()
+        u.append(2)
+        self.assertEqual(u, [2])
+
+        self.assertRaises(TypeError, u.clear, None)
+
+    def test_copy(self):
+        u = self.type2test([1, 2, 3])
+        v = u.copy()
+        self.assertEqual(v, [1, 2, 3])
+
+        u = self.type2test([])
+        v = u.copy()
+        self.assertEqual(v, [])
+
+        # test that it's indeed a copy and not a reference
+        u = self.type2test(['a', 'b'])
+        v = u.copy()
+        v.append('i')
+        self.assertEqual(u, ['a', 'b'])
+        self.assertEqual(v, u + ['i'])
+
+        # test that it's a shallow, not a deep copy
+        u = self.type2test([1, 2, [3, 4], 5])
+        v = u.copy()
+        self.assertEqual(u, v)
+        self.assertIs(v[3], u[3])
+
+        self.assertRaises(TypeError, u.copy, None)
+
     def test_sort(self):
         u = self.type2test([1, 0])
         u.sort()
@@ -482,7 +523,7 @@
         u = self.type2test([0, 1])
         u2 = u
         u += [2, 3]
-        self.assert_(u is u2)
+        self.assertIs(u, u2)
 
         u = self.type2test("spam")
         u += "eggs"

Modified: python/branches/pep-3151/Lib/test/lock_tests.py
==============================================================================
--- python/branches/pep-3151/Lib/test/lock_tests.py	(original)
+++ python/branches/pep-3151/Lib/test/lock_tests.py	Sat Feb 26 08:16:32 2011
@@ -446,6 +446,46 @@
             # In practice, this implementation has no spurious wakeups.
             self.assertFalse(result)
 
+    def test_waitfor(self):
+        cond = self.condtype()
+        state = 0
+        def f():
+            with cond:
+                result = cond.wait_for(lambda : state==4)
+                self.assertTrue(result)
+                self.assertEqual(state, 4)
+        b = Bunch(f, 1)
+        b.wait_for_started()
+        for i in range(5):
+            time.sleep(0.01)
+            with cond:
+                state += 1
+                cond.notify()
+        b.wait_for_finished()
+
+    def test_waitfor_timeout(self):
+        cond = self.condtype()
+        state = 0
+        success = []
+        def f():
+            with cond:
+                dt = time.time()
+                result = cond.wait_for(lambda : state==4, timeout=0.1)
+                dt = time.time() - dt
+                self.assertFalse(result)
+                self.assertTimeout(dt, 0.1)
+                success.append(None)
+        b = Bunch(f, 1)
+        b.wait_for_started()
+        # Only increment 3 times, so state == 4 is never reached.
+        for i in range(3):
+            time.sleep(0.01)
+            with cond:
+                state += 1
+                cond.notify()
+        b.wait_for_finished()
+        self.assertEqual(len(success), 1)
+
 
 class BaseSemaphoreTests(BaseTestCase):
     """
@@ -604,7 +644,7 @@
     Tests for Barrier objects.
     """
     N = 5
-    defaultTimeout = 0.5
+    defaultTimeout = 2.0
 
     def setUp(self):
         self.barrier = self.barriertype(self.N, timeout=self.defaultTimeout)
@@ -766,10 +806,10 @@
             i = self.barrier.wait()
             if i == self.N // 2:
                 # One thread is late!
-                time.sleep(0.1)
-            # Default timeout is 0.1, so this is shorter.
+                time.sleep(1.0)
+            # Default timeout is 2.0, so this is shorter.
             self.assertRaises(threading.BrokenBarrierError,
-                              self.barrier.wait, 0.05)
+                              self.barrier.wait, 0.5)
         self.run_threads(f)
 
     def test_default_timeout(self):
@@ -782,7 +822,7 @@
             i = barrier.wait()
             if i == self.N // 2:
                 # One thread is later than the default timeout of 0.1s.
-                time.sleep(0.2)
+                time.sleep(1.0)
             self.assertRaises(threading.BrokenBarrierError, barrier.wait)
         self.run_threads(f)
 

Modified: python/branches/pep-3151/Lib/test/outstanding_bugs.py
==============================================================================
--- python/branches/pep-3151/Lib/test/outstanding_bugs.py	(original)
+++ python/branches/pep-3151/Lib/test/outstanding_bugs.py	Sat Feb 26 08:16:32 2011
@@ -35,7 +35,7 @@
             if not c:
                 break
             reads += c
-        self.assertEquals(reads, self.normalized)
+        self.assertEqual(reads, self.normalized)
 
     def test_issue1395_2(self):
         txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII")
@@ -47,7 +47,7 @@
             if not c:
                 break
             reads += c
-        self.assertEquals(reads, self.normalized)
+        self.assertEqual(reads, self.normalized)
 
     def test_issue1395_3(self):
         txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII")
@@ -58,7 +58,7 @@
         reads += txt.readline()
         reads += txt.readline()
         reads += txt.readline()
-        self.assertEquals(reads, self.normalized)
+        self.assertEqual(reads, self.normalized)
 
     def test_issue1395_4(self):
         txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII")
@@ -66,7 +66,7 @@
 
         reads = txt.read(4)
         reads += txt.read()
-        self.assertEquals(reads, self.normalized)
+        self.assertEqual(reads, self.normalized)
 
     def test_issue1395_5(self):
         txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII")
@@ -76,7 +76,7 @@
         pos = txt.tell()
         txt.seek(0)
         txt.seek(pos)
-        self.assertEquals(txt.read(4), "BBB\n")
+        self.assertEqual(txt.read(4), "BBB\n")
 
 
 

Modified: python/branches/pep-3151/Lib/test/pickletester.py
==============================================================================
--- python/branches/pep-3151/Lib/test/pickletester.py	(original)
+++ python/branches/pep-3151/Lib/test/pickletester.py	Sat Feb 26 08:16:32 2011
@@ -5,7 +5,7 @@
 import copyreg
 from http.cookies import SimpleCookie
 
-from test.support import TestFailed, TESTFN, run_with_locale
+from test.support import TestFailed, TESTFN, run_with_locale, no_tracing
 
 from pickle import bytes_types
 
@@ -579,7 +579,7 @@
 
     def test_get(self):
         self.assertRaises(KeyError, self.loads, b'g0\np0')
-        self.assertEquals(self.loads(b'((Kdtp0\nh\x00l.))'), [(100,), (100,)])
+        self.assertEqual(self.loads(b'((Kdtp0\nh\x00l.))'), [(100,), (100,)])
 
     def test_insecure_strings(self):
         # XXX Some of these tests are temporarily disabled
@@ -1002,6 +1002,7 @@
             y = self.loads(s)
             self.assertEqual(y._reduce_called, 1)
 
+    @no_tracing
     def test_bad_getattr(self):
         x = BadGetattr()
         for proto in 0, 1:
@@ -1093,6 +1094,10 @@
             self.assertEqual(len(loaded), len(data))
             self.assertEqual(loaded, data)
 
+    def test_empty_bytestring(self):
+        # issue 11286
+        empty = self.loads(b'\x80\x03U\x00q\x00.', encoding='koi8-r')
+        self.assertEqual(empty, '')
 
 # Test classes for reduce_ex
 

Modified: python/branches/pep-3151/Lib/test/pydoc_mod.py
==============================================================================
--- python/branches/pep-3151/Lib/test/pydoc_mod.py	(original)
+++ python/branches/pep-3151/Lib/test/pydoc_mod.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,7 @@
 __author__ = "Benjamin Peterson"
 __credits__ = "Nobody"
 __version__ = "1.2.3.4"
-
+__xyz__ = "X, Y and Z"
 
 class A:
     """Hello and goodbye"""

Modified: python/branches/pep-3151/Lib/test/pystone.py
==============================================================================
--- python/branches/pep-3151/Lib/test/pystone.py	(original)
+++ python/branches/pep-3151/Lib/test/pystone.py	Sat Feb 26 08:16:32 2011
@@ -72,7 +72,7 @@
 Char1Glob = '\0'
 Char2Glob = '\0'
 Array1Glob = [0]*51
-Array2Glob = list(map(lambda x: x[:], [Array1Glob]*51))
+Array2Glob = [x[:] for x in [Array1Glob]*51]
 PtrGlb = None
 PtrGlbNext = None
 

Modified: python/branches/pep-3151/Lib/test/regrtest.py
==============================================================================
--- python/branches/pep-3151/Lib/test/regrtest.py	(original)
+++ python/branches/pep-3151/Lib/test/regrtest.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,7 @@
 """
 Usage:
 
-python -m test.regrtest [options] [test_name1 [test_name2 ...]]
+python -m test [options] [test_name1 [test_name2 ...]]
 python path/to/Lib/test/regrtest.py [options] [test_name1 [test_name2 ...]]
 
 
@@ -14,7 +14,7 @@
 For more rigorous testing, it is useful to use the following
 command line:
 
-python -E -tt -Wd -3 -m test.regrtest [options] [test_name1 ...]
+python -E -Wd -m test [options] [test_name1 ...]
 
 
 Options:
@@ -29,10 +29,12 @@
 -d/--debug      -- print traceback for failed tests
 -q/--quiet      -- no output unless one or more tests fail
 -S/--slow       -- print the slowest 10 tests
+   --header     -- print header with interpreter info
 
 Selecting tests
 
 -r/--random     -- randomize test execution order (see below)
+   --randseed   -- pass a random seed to reproduce a previous random run
 -f/--fromfile   -- read names of tests to run from a file (see below)
 -x/--exclude    -- arguments are tests to *exclude*
 -s/--single     -- single step through a set of tests (see below)
@@ -167,6 +169,7 @@
 import tempfile
 import platform
 import sysconfig
+import logging
 
 
 # Some times __path__ and __file__ are not absolute (e.g. while running from
@@ -227,7 +230,8 @@
          exclude=False, single=False, randomize=False, fromfile=None,
          findleaks=False, use_resources=None, trace=False, coverdir='coverage',
          runleaks=False, huntrleaks=False, verbose2=False, print_slow=False,
-         random_seed=None, use_mp=None, verbose3=False, forever=False):
+         random_seed=None, use_mp=None, verbose3=False, forever=False,
+         header=False):
     """Execute a test suite.
 
     This also parses command-line options and modifies its behavior
@@ -260,8 +264,8 @@
              'exclude', 'single', 'slow', 'random', 'fromfile', 'findleaks',
              'use=', 'threshold=', 'trace', 'coverdir=', 'nocoverdir',
              'runleaks', 'huntrleaks=', 'memlimit=', 'randseed=',
-             'multiprocess=', 'slaveargs=', 'forever', 'debug', 'start=',
-             'nowindows'])
+             'multiprocess=', 'coverage', 'slaveargs=', 'forever', 'debug',
+             'start=', 'nowindows', 'header'])
     except getopt.error as msg:
         usage(msg)
 
@@ -370,6 +374,8 @@
             forever = True
         elif o in ('-j', '--multiprocess'):
             use_mp = int(a)
+        elif o == '--header':
+            header = True
         elif o == '--slaveargs':
             args, kwargs = json.loads(a)
             try:
@@ -446,12 +452,13 @@
         args = []
 
     # For a partial run, we do not need to clutter the output.
-    if verbose or not (quiet or single or tests or args):
+    if verbose or header or not (quiet or single or tests or args):
         # Print basic platform information
         print("==", platform.python_implementation(), *sys.version.split())
         print("==  ", platform.platform(aliased=True),
                       "%s-endian" % sys.byteorder)
         print("==  ", os.getcwd())
+        print("Testing with flags:", sys.flags)
 
     alltests = findtests(testdir, stdtests, nottests)
     selected = tests or args or alltests
@@ -526,7 +533,7 @@
         def tests_and_args():
             for test in tests:
                 args_tuple = (
-                    (test, verbose, quiet, testdir),
+                    (test, verbose, quiet),
                     dict(huntrleaks=huntrleaks, use_resources=use_resources,
                         debug=debug)
                 )
@@ -598,16 +605,15 @@
             if trace:
                 # If we're tracing code coverage, then we don't exit with status
                 # if on a false return value from main.
-                tracer.runctx('runtest(test, verbose, quiet, testdir)',
+                tracer.runctx('runtest(test, verbose, quiet)',
                               globals=globals(), locals=vars())
             else:
                 try:
-                    result = runtest(test, verbose, quiet,
-                                     testdir, huntrleaks, debug)
+                    result = runtest(test, verbose, quiet, huntrleaks, debug)
                     accumulate_result(test, result)
                     if verbose3 and result[0] == FAILED:
                         print("Re-running test {} in verbose mode".format(test))
-                        runtest(test, True, quiet, testdir, huntrleaks, debug)
+                        runtest(test, True, quiet, huntrleaks, debug)
                 except KeyboardInterrupt:
                     interrupted = True
                     break
@@ -677,8 +683,7 @@
             sys.stdout.flush()
             try:
                 verbose = True
-                ok = runtest(test, True, quiet, testdir,
-                             huntrleaks, debug)
+                ok = runtest(test, True, quiet, huntrleaks, debug)
             except KeyboardInterrupt:
                 # print a newline separate from the ^C
                 print()
@@ -738,20 +743,28 @@
     if os.name == "nt":
         # Replace sys.stdout breaks the stdout newlines on Windows: issue #8533
         return
+
+    import atexit
+
     stdout = sys.stdout
     sys.stdout = open(stdout.fileno(), 'w',
         encoding=stdout.encoding,
-        errors="backslashreplace")
+        errors="backslashreplace",
+        closefd=False)
+
+    def restore_stdout():
+        sys.stdout.close()
+        sys.stdout = stdout
+    atexit.register(restore_stdout)
 
 def runtest(test, verbose, quiet,
-            testdir=None, huntrleaks=False, debug=False, use_resources=None):
+            huntrleaks=False, debug=False, use_resources=None):
     """Run a single test.
 
     test -- the name of the test
     verbose -- if true, print more messages
     quiet -- if true, don't print 'skipped' messages (probably redundant)
     test_times -- a list of (time, test_name) pairs
-    testdir -- test directory
     huntrleaks -- run multiple times to test for leaks; requires a debug
                   build; a triple corresponding to -R's three arguments
 
@@ -768,8 +781,7 @@
     if use_resources is not None:
         support.use_resources = use_resources
     try:
-        return runtest_inner(test, verbose, quiet,
-                             testdir, huntrleaks, debug)
+        return runtest_inner(test, verbose, quiet, huntrleaks, debug)
     finally:
         cleanup_test_droppings(test, verbose)
 
@@ -814,7 +826,8 @@
 
     resources = ('sys.argv', 'cwd', 'sys.stdin', 'sys.stdout', 'sys.stderr',
                  'os.environ', 'sys.path', 'sys.path_hooks', '__import__',
-                 'warnings.filters', 'asyncore.socket_map')
+                 'warnings.filters', 'asyncore.socket_map',
+                 'logging._handlers', 'logging._handlerList', 'sys.gettrace')
 
     def get_sys_argv(self):
         return id(sys.argv), sys.argv, sys.argv[:]
@@ -861,6 +874,11 @@
         sys.path_hooks = saved_hooks[1]
         sys.path_hooks[:] = saved_hooks[2]
 
+    def get_sys_gettrace(self):
+        return sys.gettrace()
+    def restore_sys_gettrace(self, trace_fxn):
+        sys.settrace(trace_fxn)
+
     def get___import__(self):
         return builtins.__import__
     def restore___import__(self, import_):
@@ -882,6 +900,20 @@
             asyncore.close_all(ignore_all=True)
             asyncore.socket_map.update(saved_map)
 
+    def get_logging__handlers(self):
+        # _handlers is a WeakValueDictionary
+        return id(logging._handlers), logging._handlers, logging._handlers.copy()
+    def restore_logging__handlers(self, saved_handlers):
+        # Can't easily revert the logging state
+        pass
+
+    def get_logging__handlerList(self):
+        # _handlerList is a list of weakrefs to handlers
+        return id(logging._handlerList), logging._handlerList, logging._handlerList[:]
+    def restore_logging__handlerList(self, saved_handlerList):
+        # Can't easily revert the logging state
+        pass
+
     def resource_info(self):
         for name in self.resources:
             method_suffix = name.replace('.', '_')
@@ -915,10 +947,8 @@
         return False
 
 
-def runtest_inner(test, verbose, quiet,
-                  testdir=None, huntrleaks=False, debug=False):
+def runtest_inner(test, verbose, quiet, huntrleaks=False, debug=False):
     support.unload(test)
-    testdir = findtestdir(testdir)
     if verbose:
         capture_stdout = None
     else:
@@ -1026,7 +1056,8 @@
         False if the test didn't leak references; True if we detected refleaks.
     """
     # This code is hackish and inelegant, but it seems to do the job.
-    import copyreg, _abcoll
+    import copyreg
+    import collections.abc
 
     if not hasattr(sys, 'gettotalrefcount'):
         raise Exception("Tracking reference leaks requires a debug build "
@@ -1043,7 +1074,7 @@
     else:
         zdc = zipimport._zip_directory_cache.copy()
     abcs = {}
-    for abc in [getattr(_abcoll, a) for a in _abcoll.__all__]:
+    for abc in [getattr(collections.abc, a) for a in collections.abc.__all__]:
         if not isabstract(abc):
             continue
         for obj in abc.__subclasses__() + [abc]:
@@ -1089,7 +1120,7 @@
     import gc, copyreg
     import _strptime, linecache
     import urllib.parse, urllib.request, mimetypes, doctest
-    import struct, filecmp, _abcoll
+    import struct, filecmp, collections.abc
     from distutils.dir_util import _path_created
     from weakref import WeakSet
 
@@ -1116,7 +1147,7 @@
     sys._clear_type_cache()
 
     # Clear ABC registries, restoring previously saved ABC registries.
-    for abc in [getattr(_abcoll, a) for a in _abcoll.__all__]:
+    for abc in [getattr(collections.abc, a) for a in collections.abc.__all__]:
         if not isabstract(abc):
             continue
         for obj in abc.__subclasses__() + [abc]:
@@ -1468,16 +1499,7 @@
         assert self.isvalid()
         return self.expected
 
-if __name__ == '__main__':
-    # findtestdir() gets the dirname out of __file__, so we have to make it
-    # absolute before changing the working directory.
-    # For example __file__ may be relative when running trace or profile.
-    # See issue #9323.
-    __file__ = os.path.abspath(__file__)
-
-    # sanity check
-    assert __file__ == os.path.abspath(sys.argv[0])
-
+def _make_temp_dir_for_build(TEMPDIR):
     # When tests are run from the Python build directory, it is best practice
     # to keep the test files in a subfolder.  It eases the cleanup of leftover
     # files using command "make distclean".
@@ -1493,6 +1515,31 @@
     TESTCWD = 'test_python_{}'.format(os.getpid())
 
     TESTCWD = os.path.join(TEMPDIR, TESTCWD)
+    return TEMPDIR, TESTCWD
+
+if __name__ == '__main__':
+    # Remove regrtest.py's own directory from the module search path. Despite
+    # the elimination of implicit relative imports, this is still needed to
+    # ensure that submodules of the test package do not inappropriately appear
+    # as top-level modules even when people (or buildbots!) invoke regrtest.py
+    # directly instead of using the -m switch
+    mydir = os.path.abspath(os.path.normpath(os.path.dirname(sys.argv[0])))
+    i = len(sys.path)
+    while i >= 0:
+        i -= 1
+        if os.path.abspath(os.path.normpath(sys.path[i])) == mydir:
+            del sys.path[i]
+
+    # findtestdir() gets the dirname out of __file__, so we have to make it
+    # absolute before changing the working directory.
+    # For example __file__ may be relative when running trace or profile.
+    # See issue #9323.
+    __file__ = os.path.abspath(__file__)
+
+    # sanity check
+    assert __file__ == os.path.abspath(sys.argv[0])
+
+    TEMPDIR, TESTCWD = _make_temp_dir_for_build(TEMPDIR)
 
     # Run the tests in a context manager that temporary changes the CWD to a
     # temporary and writable directory. If it's not possible to create or

Modified: python/branches/pep-3151/Lib/test/script_helper.py
==============================================================================
--- python/branches/pep-3151/Lib/test/script_helper.py	(original)
+++ python/branches/pep-3151/Lib/test/script_helper.py	Sat Feb 26 08:16:32 2011
@@ -3,6 +3,7 @@
 
 import sys
 import os
+import re
 import os.path
 import tempfile
 import subprocess
@@ -12,7 +13,7 @@
 import zipfile
 
 from imp import source_from_cache
-from test.support import make_legacy_pyc
+from test.support import make_legacy_pyc, strip_python_stderr
 
 # Executing the interpreter in a subprocess
 def _assert_python(expected_success, *args, **env_vars):
@@ -34,6 +35,7 @@
         p.stdout.close()
         p.stderr.close()
     rc = p.returncode
+    err =  strip_python_stderr(err)
     if (rc and expected_success) or (not rc and not expected_success):
         raise AssertionError(
             "Process return code is %d, "

Modified: python/branches/pep-3151/Lib/test/seq_tests.py
==============================================================================
--- python/branches/pep-3151/Lib/test/seq_tests.py	(original)
+++ python/branches/pep-3151/Lib/test/seq_tests.py	Sat Feb 26 08:16:32 2011
@@ -131,8 +131,8 @@
             self.assertRaises(ZeroDivisionError, self.type2test, IterGenExc(s))
 
     def test_truth(self):
-        self.assert_(not self.type2test())
-        self.assert_(self.type2test([42]))
+        self.assertFalse(self.type2test())
+        self.assertTrue(self.type2test([42]))
 
     def test_getitem(self):
         u = self.type2test([0, 1, 2, 3, 4])
@@ -268,7 +268,7 @@
             pass
         u3 = subclass([0, 1])
         self.assertEqual(u3, u3*1)
-        self.assert_(u3 is not u3*1)
+        self.assertIsNot(u3, u3*1)
 
     def test_iadd(self):
         u = self.type2test([0, 1])

Modified: python/branches/pep-3151/Lib/test/sha256.pem
==============================================================================
--- python/branches/pep-3151/Lib/test/sha256.pem	(original)
+++ python/branches/pep-3151/Lib/test/sha256.pem	Sat Feb 26 08:16:32 2011
@@ -1,33 +1,129 @@
+# Certificate chain for https://sha256.tbs-internet.com
+ 0 s:/C=FR/postalCode=14000/ST=Calvados/L=CAEN/street=22 rue de Bretagne/O=TBS INTERNET/OU=0002 440443810/OU=sha-256 production/CN=sha256.tbs-internet.com
+   i:/C=FR/ST=Calvados/L=Caen/O=TBS INTERNET/OU=Terms and Conditions: http://www.tbs-internet.com/CA/repository/OU=TBS INTERNET CA/CN=TBS X509 CA SGC
 -----BEGIN CERTIFICATE-----
-MIIFxzCCA6+gAwIBAgIJALnlnf5uzTkIMA0GCSqGSIb3DQEBCwUAMEsxCzAJBgNV
-BAYTAkRFMRcwFQYDVQQKEw5zY2hva29rZWtzLm9yZzEjMCEGCSqGSIb3DQEJARYU
-aGFubm9Ac2Nob2tva2Vrcy5vcmcwHhcNMTAwMTI3MDAyMTI1WhcNMjAwMTI1MDAy
-MTI1WjBLMQswCQYDVQQGEwJERTEXMBUGA1UEChMOc2Nob2tva2Vrcy5vcmcxIzAh
-BgkqhkiG9w0BCQEWFGhhbm5vQHNjaG9rb2tla3Mub3JnMIICIjANBgkqhkiG9w0B
-AQEFAAOCAg8AMIICCgKCAgEApJ4ODPwEooMW35dQPlBqdvcfkEvjhcsA7jmJfFqN
-e/1T34zT44X9+KnMBSG2InacbD7eyFgjfaENFsZ87YkEBDIFZ/SHotLJZORQ8PUj
-YoxPG4mjKN+yL2WthNcYbRyJreTbbDroNMuw6tkTSxeSXyYFQrKMCUfErVbZa/d5
-RvfFVk+Au9dVUFhed/Stn5cv+a0ffvpyA7ygihm1kMFICbvPeI0846tmC2Ph7rM5
-pYQyNBDOVpULODTk5Wu6jiiJJygvJWCZ1FdpsdBs5aKWHWdRhX++quGuflTTjH5d
-qaIka4op9H7XksYphTDXmV+qHnva5jbPogwutDQcVsGBQcJaLmQqhsQK13bf4khE
-iWJvfBLfHn8OOpY25ZwwuigJIwifNCxQeeT1FrLmyuYNhz2phPpzx065kqSUSR+A
-Iw8DPE6e65UqMDKqZnID3dQeiQaFrHEV+Ibo0U/tD0YSBw5p33TMh0Es33IBWMac
-m7x4hIFWdhl8W522u6qOrTswY3s8vB7blNWqMc9n7oWH8ybFf7EgKeDVtEN9AyBE
-0WotXIEZWI+WvDbU1ACJXau9sQhYP/eerg7Zwr3iGUy4IQ5oUJibnjtcE+z8zmDN
-pE6YcMCLJyLjXiQ3iHG9mNXzw7wPnslTbEEEukrfSlHGgW8Dm+VrNyW0JUM1bntx
-vbMCAwEAAaOBrTCBqjAdBgNVHQ4EFgQUCedv7pDTuXtCxm4HTw9hUtrTvsowewYD
-VR0jBHQwcoAUCedv7pDTuXtCxm4HTw9hUtrTvsqhT6RNMEsxCzAJBgNVBAYTAkRF
-MRcwFQYDVQQKEw5zY2hva29rZWtzLm9yZzEjMCEGCSqGSIb3DQEJARYUaGFubm9A
-c2Nob2tva2Vrcy5vcmeCCQC55Z3+bs05CDAMBgNVHRMEBTADAQH/MA0GCSqGSIb3
-DQEBCwUAA4ICAQBHKAxA7WA/MEFjet03K8ouzEOr6Jrk2fZOuRhoDZ+9gr4FtaJB
-P3Hh5D00kuSOvDnwsvCohxeNd1KTMAwVmVoH+NZkHERn3UXniUENlp18koI1ehlr
-CZbXbzzE9Te9BelliSFA63q0cq0yJN1x9GyabU34XkAouCAmOqfSpKNZWZHGBHPF
-bbYnZrHEMcsye6vKeTOcg1GqUHGrQM2WK0QaOwnCQv2RblI9VN+SeRoUJ44qTXdW
-TwIYStsIPesacNcAQTStnHgKqIPx4zCwdx5xo8zONbXJfocqwyFqiAofvb9dN1nW
-g1noVBcXB+oRBZW5CjFw87U88itq39i9+BWl835DWLBW2pVmx1QTLGv0RNgs/xVx
-mWnjH4nNHvrjn6pRmqHZTk/SS0Hkl2qtDsynVxIl8EiMTfWSU3DBTuD2J/RSzuOE
-eKtAbaoXkXE31jCl4FEZLITIZd8UkXacb9rN304tAK92L76JOAV+xOZxFRipmvx4
-+A9qQXgLhtP4VaDajb44V/kCKPSA0Vm3apehke9Wl8dDtagfos1e6MxSu3EVLXRF
-SP2U777V77pdMSd0f/7cerKn5FjrxW1v1FaP1oIGniMk4qQNTgA/jvvhjybsPlVA
-jsfnhWGbh1voJa0RQcMiRMsxpw2P1KNOEu37W2eq/vFghVztZJQUmb5iNw==
+MIIGXTCCBUWgAwIBAgIRAMmag+ygSAdxZsbyzYjhuW0wDQYJKoZIhvcNAQELBQAw
+gcQxCzAJBgNVBAYTAkZSMREwDwYDVQQIEwhDYWx2YWRvczENMAsGA1UEBxMEQ2Fl
+bjEVMBMGA1UEChMMVEJTIElOVEVSTkVUMUgwRgYDVQQLEz9UZXJtcyBhbmQgQ29u
+ZGl0aW9uczogaHR0cDovL3d3dy50YnMtaW50ZXJuZXQuY29tL0NBL3JlcG9zaXRv
+cnkxGDAWBgNVBAsTD1RCUyBJTlRFUk5FVCBDQTEYMBYGA1UEAxMPVEJTIFg1MDkg
+Q0EgU0dDMB4XDTEwMDIxODAwMDAwMFoXDTEyMDIxOTIzNTk1OVowgcsxCzAJBgNV
+BAYTAkZSMQ4wDAYDVQQREwUxNDAwMDERMA8GA1UECBMIQ2FsdmFkb3MxDTALBgNV
+BAcTBENBRU4xGzAZBgNVBAkTEjIyIHJ1ZSBkZSBCcmV0YWduZTEVMBMGA1UEChMM
+VEJTIElOVEVSTkVUMRcwFQYDVQQLEw4wMDAyIDQ0MDQ0MzgxMDEbMBkGA1UECxMS
+c2hhLTI1NiBwcm9kdWN0aW9uMSAwHgYDVQQDExdzaGEyNTYudGJzLWludGVybmV0
+LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKbuM8VT7f0nntwu
+N3F7v9KIBlhKNAxqCrziOXU5iqUt8HrQB3DtHbdmII+CpVUlwlmepsx6G+srEZ9a
+MIGAy0nxi5aLb7watkyIdPjJTMvTUBQ/+RPWzt5JtYbbY9BlJ+yci0dctP74f4NU
+ISLtlrEjUbf2gTohLrcE01TfmOF6PDEbB5PKDi38cB3NzKfizWfrOaJW6Q1C1qOJ
+y4/4jkUREX1UFUIxzx7v62VfjXSGlcjGpBX1fvtABQOSLeE0a6gciDZs1REqroFf
+5eXtqYphpTa14Z83ITXMfgg5Nze1VtMnzI9Qx4blYBw4dgQVEuIsYr7FDBOITDzc
+VEVXZx0CAwEAAaOCAj8wggI7MB8GA1UdIwQYMBaAFAdEdoWTKLx/bXjSCuv6TEvf
+2YIfMB0GA1UdDgQWBBSJKI/AYVI9RQNY0QPIqc8ej2QivTAOBgNVHQ8BAf8EBAMC
+BaAwDAYDVR0TAQH/BAIwADA0BgNVHSUELTArBggrBgEFBQcDAQYIKwYBBQUHAwIG
+CisGAQQBgjcKAwMGCWCGSAGG+EIEATBMBgNVHSAERTBDMEEGCysGAQQBgOU3AgQB
+MDIwMAYIKwYBBQUHAgEWJGh0dHBzOi8vd3d3LnRicy1pbnRlcm5ldC5jb20vQ0Ev
+Q1BTNDBtBgNVHR8EZjBkMDKgMKAuhixodHRwOi8vY3JsLnRicy1pbnRlcm5ldC5j
+b20vVEJTWDUwOUNBU0dDLmNybDAuoCygKoYoaHR0cDovL2NybC50YnMteDUwOS5j
+b20vVEJTWDUwOUNBU0dDLmNybDCBpgYIKwYBBQUHAQEEgZkwgZYwOAYIKwYBBQUH
+MAKGLGh0dHA6Ly9jcnQudGJzLWludGVybmV0LmNvbS9UQlNYNTA5Q0FTR0MuY3J0
+MDQGCCsGAQUFBzAChihodHRwOi8vY3J0LnRicy14NTA5LmNvbS9UQlNYNTA5Q0FT
+R0MuY3J0MCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC50YnMteDUwOS5jb20wPwYD
+VR0RBDgwNoIXc2hhMjU2LnRicy1pbnRlcm5ldC5jb22CG3d3dy5zaGEyNTYudGJz
+LWludGVybmV0LmNvbTANBgkqhkiG9w0BAQsFAAOCAQEAA5NL0D4QSqhErhlkdPmz
+XtiMvdGL+ZehM4coTRIpasM/Agt36Rc0NzCvnQwKE+wkngg1Gy2qe7Q0E/ziqBtB
+fZYzdVgu1zdiL4kTaf+wFKYAFGsFbyeEmXysy+CMwaNoF2vpSjCU1UD56bEnTX/W
+fxVZYxtBQUpnu2wOsm8cDZuZRv9XrYgAhGj9Tt6F0aVHSDGn59uwShG1+BVF/uju
+SCyPTTjL1oc7YElJUzR/x4mQJYvtQI8gDIDAGEOs7v3R/gKa5EMfbUQUI4C84UbI
+Yz09Jdnws/MkC/Hm1BZEqk89u7Hvfv+oHqEb0XaUo0TDfsxE0M1sMdnLb91QNQBm
+UQ==
+-----END CERTIFICATE-----
+ 1 s:/C=FR/ST=Calvados/L=Caen/O=TBS INTERNET/OU=Terms and Conditions: http://www.tbs-internet.com/CA/repository/OU=TBS INTERNET CA/CN=TBS X509 CA SGC
+   i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
+-----BEGIN CERTIFICATE-----
+MIIFVjCCBD6gAwIBAgIQXpDZ0ETJMV02WTx3GTnhhTANBgkqhkiG9w0BAQUFADBv
+MQswCQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFk
+ZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBF
+eHRlcm5hbCBDQSBSb290MB4XDTA1MTIwMTAwMDAwMFoXDTE5MDYyNDE5MDYzMFow
+gcQxCzAJBgNVBAYTAkZSMREwDwYDVQQIEwhDYWx2YWRvczENMAsGA1UEBxMEQ2Fl
+bjEVMBMGA1UEChMMVEJTIElOVEVSTkVUMUgwRgYDVQQLEz9UZXJtcyBhbmQgQ29u
+ZGl0aW9uczogaHR0cDovL3d3dy50YnMtaW50ZXJuZXQuY29tL0NBL3JlcG9zaXRv
+cnkxGDAWBgNVBAsTD1RCUyBJTlRFUk5FVCBDQTEYMBYGA1UEAxMPVEJTIFg1MDkg
+Q0EgU0dDMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsgOkO3f7wzN6
+rOjg45tR5vjBfzK7qmV9IBxb/QW9EEXxG+E7FNhZqQLtwGBKoSsHTnQqV75wWMk0
+9tinWvftBkSpj5sTi/8cbzJfUvTSVYh3Qxv6AVVjMMH/ruLjE6y+4PoaPs8WoYAQ
+ts5R4Z1g8c/WnTepLst2x0/Wv7GmuoQi+gXvHU6YrBiu7XkeYhzc95QdviWSJRDk
+owhb5K43qhcvjRmBfO/paGlCliDGZp8mHwrI21mwobWpVjTxZRwYO3bd4+TGcI4G
+Ie5wmHwE8F7SK1tgSqbBacKjDa93j7txKkfz/Yd2n7TGqOXiHPsJpG655vrKtnXk
+9vs1zoDeJQIDAQABo4IBljCCAZIwHQYDVR0OBBYEFAdEdoWTKLx/bXjSCuv6TEvf
+2YIfMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/AgEAMCAGA1UdJQQZ
+MBcGCisGAQQBgjcKAwMGCWCGSAGG+EIEATAYBgNVHSAEETAPMA0GCysGAQQBgOU3
+AgQBMHsGA1UdHwR0MHIwOKA2oDSGMmh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL0Fk
+ZFRydXN0RXh0ZXJuYWxDQVJvb3QuY3JsMDagNKAyhjBodHRwOi8vY3JsLmNvbW9k
+by5uZXQvQWRkVHJ1c3RFeHRlcm5hbENBUm9vdC5jcmwwgYAGCCsGAQUFBwEBBHQw
+cjA4BggrBgEFBQcwAoYsaHR0cDovL2NydC5jb21vZG9jYS5jb20vQWRkVHJ1c3RV
+VE5TR0NDQS5jcnQwNgYIKwYBBQUHMAKGKmh0dHA6Ly9jcnQuY29tb2RvLm5ldC9B
+ZGRUcnVzdFVUTlNHQ0NBLmNydDARBglghkgBhvhCAQEEBAMCAgQwDQYJKoZIhvcN
+AQEFBQADggEBAK2zEzs+jcIrVK9oDkdDZNvhuBYTdCfpxfFs+OAujW0bIfJAy232
+euVsnJm6u/+OrqKudD2tad2BbejLLXhMZViaCmK7D9nrXHx4te5EP8rL19SUVqLY
+1pTnv5dhNgEgvA7n5lIzDSYs7yRLsr7HJsYPr6SeYSuZizyX1SNz7ooJ32/F3X98
+RB0Mlc/E0OyOrkQ9/y5IrnpnaSora8CnUrV5XNOg+kyCz9edCyx4D5wXYcwZPVWz
+8aDqquESrezPyjtfi4WRO4s/VD3HLZvOxzMrWAVYCDG9FxaOhF0QGuuG1F7F3GKV
+v6prNyCl016kRl2j1UT+a7gLd8fA25A4C9E=
+-----END CERTIFICATE-----
+ 2 s:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
+   i:/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network/OU=http://www.usertrust.com/CN=UTN - DATACorp SGC
+-----BEGIN CERTIFICATE-----
+MIIEZjCCA06gAwIBAgIQUSYKkxzif5zDpV954HKugjANBgkqhkiG9w0BAQUFADCB
+kzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug
+Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho
+dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xGzAZBgNVBAMTElVUTiAtIERBVEFDb3Jw
+IFNHQzAeFw0wNTA2MDcwODA5MTBaFw0xOTA2MjQxOTA2MzBaMG8xCzAJBgNVBAYT
+AlNFMRQwEgYDVQQKEwtBZGRUcnVzdCBBQjEmMCQGA1UECxMdQWRkVHJ1c3QgRXh0
+ZXJuYWwgVFRQIE5ldHdvcmsxIjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENB
+IFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC39xoz5vIABC05
+4E5b7R+8bA/Ntfojts7emxEzl6QpTH2Tn71KvJPtAxrjj8/lbVBa1pcplFqAsEl6
+2y6V/bjKvzc4LR4+kUGtcFbH8E8/6DKedMrIkFTpxl8PeJ2aQDwOrGGqXhSPnoeh
+alDc15pOrwWzpnGUnHGzUGAKxxOdOAeGAqjpqGkmGJCrTLBPI6s6T4TY386f4Wlv
+u9dC12tE5Met7m1BX3JacQg3s3llpFmglDf3AC8NwpJy2tA4ctsUqEXEXSp9t7TW
+xO6szRNEt8kr3UMAJfphuWlqWCMRt6czj1Z1WfXNKddGtworZbbTQm8Vsrh7++/p
+XVPVNFonAgMBAAGjgdgwgdUwHwYDVR0jBBgwFoAUUzLRs89/+uDxoF2FTpLSnkUd
+tE8wHQYDVR0OBBYEFK29mHo0tCb3+sQmVO8DveAky1QaMA4GA1UdDwEB/wQEAwIB
+BjAPBgNVHRMBAf8EBTADAQH/MBEGCWCGSAGG+EIBAQQEAwIBAjAgBgNVHSUEGTAX
+BgorBgEEAYI3CgMDBglghkgBhvhCBAEwPQYDVR0fBDYwNDAyoDCgLoYsaHR0cDov
+L2NybC51c2VydHJ1c3QuY29tL1VUTi1EQVRBQ29ycFNHQy5jcmwwDQYJKoZIhvcN
+AQEFBQADggEBAMbuUxdoFLJRIh6QWA2U/b3xcOWGLcM2MY9USEbnLQg3vGwKYOEO
+rVE04BKT6b64q7gmtOmWPSiPrmQH/uAB7MXjkesYoPF1ftsK5p+R26+udd8jkWjd
+FwBaS/9kbHDrARrQkNnHptZt9hPk/7XJ0h4qy7ElQyZ42TCbTg0evmnv3+r+LbPM
++bDdtRTKkdSytaX7ARmjR3mfnYyVhzT4HziS2jamEfpr62vp3EV4FTkG101B5CHI
+3C+H0be/SGB1pWLLJN47YaApIKa+xWycxOkKaSLvkTr6Jq/RW0GnOuL4OAdCq8Fb
++M5tug8EPzI0rNwEKNdwMBQmBsTkm5jVz3g=
+-----END CERTIFICATE-----
+ 3 s:/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network/OU=http://www.usertrust.com/CN=UTN - DATACorp SGC
+   i:/C=US/ST=UT/L=Salt Lake City/O=The USERTRUST Network/OU=http://www.usertrust.com/CN=UTN - DATACorp SGC
+-----BEGIN CERTIFICATE-----
+MIIEXjCCA0agAwIBAgIQRL4Mi1AAIbQR0ypoBqmtaTANBgkqhkiG9w0BAQUFADCB
+kzELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAlVUMRcwFQYDVQQHEw5TYWx0IExha2Ug
+Q2l0eTEeMBwGA1UEChMVVGhlIFVTRVJUUlVTVCBOZXR3b3JrMSEwHwYDVQQLExho
+dHRwOi8vd3d3LnVzZXJ0cnVzdC5jb20xGzAZBgNVBAMTElVUTiAtIERBVEFDb3Jw
+IFNHQzAeFw05OTA2MjQxODU3MjFaFw0xOTA2MjQxOTA2MzBaMIGTMQswCQYDVQQG
+EwJVUzELMAkGA1UECBMCVVQxFzAVBgNVBAcTDlNhbHQgTGFrZSBDaXR5MR4wHAYD
+VQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxITAfBgNVBAsTGGh0dHA6Ly93d3cu
+dXNlcnRydXN0LmNvbTEbMBkGA1UEAxMSVVROIC0gREFUQUNvcnAgU0dDMIIBIjAN
+BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3+5YEKIrblXEjr8uRgnn4AgPLit6
+E5Qbvfa2gI5lBZMAHryv4g+OGQ0SR+ysraP6LnD43m77VkIVni5c7yPeIbkFdicZ
+D0/Ww5y0vpQZY/KmEQrrU0icvvIpOxboGqBMpsn0GFlowHDyUwDAXlCCpVZvNvlK
+4ESGoE1O1kduSUrLZ9emxAW5jh70/P/N5zbgnAVssjMiFdC04MwXwLLA9P4yPykq
+lXvY8qdOD1R8oQ2AswkDwf9c3V6aPryuvEeKaq5xyh+xKrhfQgUL7EYw0XILyulW
+bfXv33i+Ybqypa4ETLyorGkVl73v67SMvzX41MPRKA5cOp9wGDMgd8SirwIDAQAB
+o4GrMIGoMAsGA1UdDwQEAwIBxjAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBRT
+MtGzz3/64PGgXYVOktKeRR20TzA9BgNVHR8ENjA0MDKgMKAuhixodHRwOi8vY3Js
+LnVzZXJ0cnVzdC5jb20vVVROLURBVEFDb3JwU0dDLmNybDAqBgNVHSUEIzAhBggr
+BgEFBQcDAQYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMA0GCSqGSIb3DQEBBQUAA4IB
+AQAnNZcAiosovcYzMB4p/OL31ZjUQLtgyr+rFywJNn9Q+kHcrpY6CiM+iVnJowft
+Gzet/Hy+UUla3joKVAgWRcKZsYfNjGjgaQPpxE6YsjuMFrMOoAyYUJuTqXAJyCyj
+j98C5OBxOvG0I3KgqgHf35g+FFCgMSa9KOlaMCZ1+XtgHI3zzVAmbQQnmt/VDUVH
+KWss5nbZqSl9Mt3JNjy9rjXxEZ4du5A/EkdOjtd+D2JzHVImOBwYSf0wdJrE5SIv
+2MCN7ZF6TACPcn9d2t0bi0Vr591pl6jFVkwPDPafepE39peC4N1xaf92P2BNPM/3
+mfnGV/TJVTl4uix5yaaIK/QI
 -----END CERTIFICATE-----

Modified: python/branches/pep-3151/Lib/test/string_tests.py
==============================================================================
--- python/branches/pep-3151/Lib/test/string_tests.py	(original)
+++ python/branches/pep-3151/Lib/test/string_tests.py	Sat Feb 26 08:16:32 2011
@@ -67,7 +67,7 @@
             else:
                 obj = subtype(obj)
                 realresult = getattr(obj, methodname)(*args)
-                self.assert_(obj is not realresult)
+                self.assertIsNot(obj, realresult)
 
     # check that obj.method(*args) raises exc
     def checkraises(self, exc, obj, methodname, *args):
@@ -1197,34 +1197,34 @@
             pass
         s1 = subclass("abcd")
         s2 = t().join([s1])
-        self.assert_(s1 is not s2)
-        self.assert_(type(s2) is t)
+        self.assertIsNot(s1, s2)
+        self.assertIs(type(s2), t)
 
         s1 = t("abcd")
         s2 = t().join([s1])
-        self.assert_(s1 is s2)
+        self.assertIs(s1, s2)
 
         # Should also test mixed-type join.
         if t is str:
             s1 = subclass("abcd")
             s2 = "".join([s1])
-            self.assert_(s1 is not s2)
-            self.assert_(type(s2) is t)
+            self.assertIsNot(s1, s2)
+            self.assertIs(type(s2), t)
 
             s1 = t("abcd")
             s2 = "".join([s1])
-            self.assert_(s1 is s2)
+            self.assertIs(s1, s2)
 
 ##         elif t is str8:
 ##             s1 = subclass("abcd")
 ##             s2 = "".join([s1])
-##             self.assert_(s1 is not s2)
-##             self.assert_(type(s2) is str) # promotes!
+##             self.assertIsNot(s1, s2)
+##             self.assertIs(type(s2), str) # promotes!
 
 ##             s1 = t("abcd")
 ##             s2 = "".join([s1])
-##             self.assert_(s1 is not s2)
-##             self.assert_(type(s2) is str) # promotes!
+##             self.assertIsNot(s1, s2)
+##             self.assertIs(type(s2), str) # promotes!
 
         else:
             self.fail("unexpected type for MixinStrUnicodeTest %r" % t)

Modified: python/branches/pep-3151/Lib/test/support.py
==============================================================================
--- python/branches/pep-3151/Lib/test/support.py	(original)
+++ python/branches/pep-3151/Lib/test/support.py	Sat Feb 26 08:16:32 2011
@@ -15,13 +15,13 @@
 import warnings
 import unittest
 import importlib
-import collections
+import collections.abc
 import re
 import subprocess
 import imp
 import time
 import sysconfig
-
+import logging.handlers
 
 try:
     import _thread
@@ -33,7 +33,7 @@
     "verbose", "use_resources", "max_memuse", "record_original_stdout",
     "get_original_stdout", "unload", "unlink", "rmtree", "forget",
     "is_resource_enabled", "requires", "find_unused_port", "bind_port",
-    "fcmp", "is_jython", "TESTFN", "HOST", "FUZZ", "SAVEDCWD", "temp_cwd",
+    "is_jython", "TESTFN", "HOST", "SAVEDCWD", "temp_cwd",
     "findfile", "sortdict", "check_syntax_error", "open_urlresource",
     "check_warnings", "CleanImport", "EnvironmentVarGuard",
     "TransientResource", "captured_output", "captured_stdout",
@@ -42,7 +42,8 @@
     "set_memlimit", "bigmemtest", "bigaddrspacetest", "BasicTestRunner",
     "run_unittest", "run_doctest", "threading_setup", "threading_cleanup",
     "reap_children", "cpython_only", "check_impl_detail", "get_attribute",
-    "swap_item", "swap_attr", "can_symlink", "skip_unless_symlink"]
+    "swap_item", "swap_attr", "requires_IEEE_754",
+    "TestHandler", "Matcher", "can_symlink", "skip_unless_symlink"]
 
 
 class Error(Exception):
@@ -348,23 +349,10 @@
     port = sock.getsockname()[1]
     return port
 
-FUZZ = 1e-6
-
-def fcmp(x, y): # fuzzy comparison function
-    if isinstance(x, float) or isinstance(y, float):
-        try:
-            fuzz = (abs(x) + abs(y)) * FUZZ
-            if abs(x-y) <= fuzz:
-                return 0
-        except:
-            pass
-    elif type(x) == type(y) and isinstance(x, (tuple, list)):
-        for i in range(min(len(x), len(y))):
-            outcome = fcmp(x[i], y[i])
-            if outcome != 0:
-                return outcome
-        return (len(x) > len(y)) - (len(x) < len(y))
-    return (x > y) - (x < y)
+# decorator for skipping tests on non-IEEE 754 platforms
+requires_IEEE_754 = unittest.skipUnless(
+    float.__getformat__("double").startswith("IEEE"),
+    "test requires IEEE 754 doubles")
 
 is_jython = sys.platform.startswith('java')
 
@@ -676,7 +664,7 @@
         sys.modules.update(self.original_modules)
 
 
-class EnvironmentVarGuard(collections.MutableMapping):
+class EnvironmentVarGuard(collections.abc.MutableMapping):
 
     """Class to help protect the environment variable properly.  Can be used as
     a context manager."""
@@ -794,6 +782,7 @@
     default_errnos = [
         ('ECONNREFUSED', 111),
         ('ECONNRESET', 104),
+        ('EHOSTUNREACH', 113),
         ('ENETUNREACH', 101),
         ('ETIMEDOUT', 110),
     ]
@@ -868,6 +857,9 @@
 def captured_stdout():
     return captured_output("stdout")
 
+def captured_stderr():
+    return captured_output("stderr")
+
 def captured_stdin():
     return captured_output("stdin")
 
@@ -968,13 +960,12 @@
         raise ValueError('Memory limit %r too low to be useful' % (limit,))
     max_memuse = memlimit
 
-def bigmemtest(minsize, memuse, overhead=5*_1M):
+def bigmemtest(minsize, memuse):
     """Decorator for bigmem tests.
 
     'minsize' is the minimum useful size for the test (in arbitrary,
     test-interpreted units.) 'memuse' is the number of 'bytes per size' for
-    the test, or a good estimate of it. 'overhead' specifies fixed overhead,
-    independent of the testsize, and defaults to 5Mb.
+    the test, or a good estimate of it.
 
     The decorator tries to guess a good value for 'size' and passes it to
     the decorated test function. If minsize * memuse is more than the
@@ -986,52 +977,43 @@
             # Retrieve values in case someone decided to adjust them
             minsize = wrapper.minsize
             memuse = wrapper.memuse
-            overhead = wrapper.overhead
             if not max_memuse:
                 # If max_memuse is 0 (the default),
                 # we still want to run the tests with size set to a few kb,
                 # to make sure they work. We still want to avoid using
                 # too much memory, though, but we do that noisily.
                 maxsize = 5147
-                self.assertFalse(maxsize * memuse + overhead > 20 * _1M)
+                self.assertFalse(maxsize * memuse > 20 * _1M)
             else:
-                maxsize = int((max_memuse - overhead) / memuse)
+                maxsize = int(max_memuse / memuse)
                 if maxsize < minsize:
-                    # Really ought to print 'test skipped' or something
-                    if verbose:
-                        sys.stderr.write("Skipping %s because of memory "
-                                         "constraint\n" % (f.__name__,))
-                    return
-                # Try to keep some breathing room in memory use
-                maxsize = max(maxsize - 50 * _1M, minsize)
+                    raise unittest.SkipTest(
+                        "not enough memory: %.1fG minimum needed"
+                        % (minsize * memuse / (1024 ** 3)))
             return f(self, maxsize)
         wrapper.minsize = minsize
         wrapper.memuse = memuse
-        wrapper.overhead = overhead
         return wrapper
     return decorator
 
-def precisionbigmemtest(size, memuse, overhead=5*_1M):
+def precisionbigmemtest(size, memuse):
     def decorator(f):
         def wrapper(self):
             size = wrapper.size
             memuse = wrapper.memuse
-            overhead = wrapper.overhead
             if not real_max_memuse:
                 maxsize = 5147
             else:
                 maxsize = size
 
                 if real_max_memuse and real_max_memuse < maxsize * memuse:
-                    if verbose:
-                        sys.stderr.write("Skipping %s because of memory "
-                                         "constraint\n" % (f.__name__,))
-                    return
+                    raise unittest.SkipTest(
+                        "not enough memory: %.1fG minimum needed"
+                        % (size * memuse / (1024 ** 3)))
 
             return f(self, maxsize)
         wrapper.size = size
         wrapper.memuse = memuse
-        wrapper.overhead = overhead
         return wrapper
     return decorator
 
@@ -1039,9 +1021,13 @@
     """Decorator for tests that fill the address space."""
     def wrapper(self):
         if max_memuse < MAX_Py_ssize_t:
-            if verbose:
-                sys.stderr.write("Skipping %s because of memory "
-                                 "constraint\n" % (f.__name__,))
+            if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31:
+                raise unittest.SkipTest(
+                    "not enough memory: try a 32-bit build instead")
+            else:
+                raise unittest.SkipTest(
+                    "not enough memory: %.1fG minimum needed"
+                    % (MAX_Py_ssize_t / (1024 ** 3)))
         else:
             return f(self)
     return wrapper
@@ -1104,6 +1090,32 @@
     return guards.get(platform.python_implementation().lower(), default)
 
 
+def no_tracing(func):
+    """Decorator to temporarily turn off tracing for the duration of a test."""
+    if not hasattr(sys, 'gettrace'):
+        return func
+    else:
+        @functools.wraps(func)
+        def wrapper(*args, **kwargs):
+            original_trace = sys.gettrace()
+            try:
+                sys.settrace(None)
+                return func(*args, **kwargs)
+            finally:
+                sys.settrace(original_trace)
+        return wrapper
+
+
+def refcount_test(test):
+    """Decorator for tests which involve reference counting.
+
+    To start, the decorator does not run the test if is not run by CPython.
+    After that, any trace function is unset during the test to prevent
+    unexpected refcounts caused by the trace function.
+
+    """
+    return no_tracing(cpython_only(test))
+
 
 def _run_suite(suite):
     """Run tests from a unittest.TestSuite-derived class."""
@@ -1189,6 +1201,12 @@
                  if k.startswith('encodings.')]
     sys.modules.clear()
     sys.modules.update(encodings)
+    # XXX: This kind of problem can affect more than just encodings. In particular
+    # extension modules (such as _ssl) don't cope with reloading properly.
+    # Really, test modules should be cleaning out the test specific modules they
+    # know they added (ala test_runpy) rather than relying on this function (as
+    # test_importhooks and test_pkg do currently).
+    # Implicitly imported *real* modules should be left alone (see issue 10556).
     sys.modules.update(oldmodules)
 
 #=======================================================================
@@ -1256,27 +1274,6 @@
             except:
                 break
 
-try:
-    from .symlink_support import enable_symlink_privilege
-except:
-    enable_symlink_privilege = lambda: True
-
-def can_symlink():
-    """It's no longer sufficient to test for the presence of symlink in the
-    os module - on Windows XP and earlier, os.symlink exists but a
-    NotImplementedError is thrown.
-    """
-    has_symlink = hasattr(os, 'symlink')
-    is_old_windows = sys.platform == "win32" and sys.getwindowsversion().major < 6
-    has_privilege = False if is_old_windows else enable_symlink_privilege()
-    return has_symlink and (not is_old_windows) and has_privilege
-
-def skip_unless_symlink(test):
-    """Skip decorator for tests that require functional symlink"""
-    selector = can_symlink()
-    msg = "Requires functional symlink implementation"
-    return [unittest.skip(msg)(test), test][selector]
-
 @contextlib.contextmanager
 def swap_attr(obj, attr, new_val):
     """Temporary swap out an attribute with a new object.
@@ -1359,3 +1356,88 @@
         if v > 0:
             args.append('-' + opt * v)
     return args
+
+#============================================================
+# Support for assertions about logging.
+#============================================================
+
+class TestHandler(logging.handlers.BufferingHandler):
+    def __init__(self, matcher):
+        # BufferingHandler takes a "capacity" argument
+        # so as to know when to flush. As we're overriding
+        # shouldFlush anyway, we can set a capacity of zero.
+        # You can call flush() manually to clear out the
+        # buffer.
+        logging.handlers.BufferingHandler.__init__(self, 0)
+        self.matcher = matcher
+
+    def shouldFlush(self):
+        return False
+
+    def emit(self, record):
+        self.format(record)
+        self.buffer.append(record.__dict__)
+
+    def matches(self, **kwargs):
+        """
+        Look for a saved dict whose keys/values match the supplied arguments.
+        """
+        result = False
+        for d in self.buffer:
+            if self.matcher.matches(d, **kwargs):
+                result = True
+                break
+        return result
+
+class Matcher(object):
+
+    _partial_matches = ('msg', 'message')
+
+    def matches(self, d, **kwargs):
+        """
+        Try to match a single dict with the supplied arguments.
+
+        Keys whose values are strings and which are in self._partial_matches
+        will be checked for partial (i.e. substring) matches. You can extend
+        this scheme to (for example) do regular expression matching, etc.
+        """
+        result = True
+        for k in kwargs:
+            v = kwargs[k]
+            dv = d.get(k)
+            if not self.match_value(k, dv, v):
+                result = False
+                break
+        return result
+
+    def match_value(self, k, dv, v):
+        """
+        Try to match a single stored value (dv) with a supplied value (v).
+        """
+        if type(v) != type(dv):
+            result = False
+        elif type(dv) is not str or k not in self._partial_matches:
+            result = (v == dv)
+        else:
+            result = dv.find(v) >= 0
+        return result
+
+
+_can_symlink = None
+def can_symlink():
+    global _can_symlink
+    if _can_symlink is not None:
+        return _can_symlink
+    try:
+        os.symlink(TESTFN, TESTFN + "can_symlink")
+        can = True
+    except (OSError, NotImplementedError):
+        can = False
+    _can_symlink = can
+    return can
+
+def skip_unless_symlink(test):
+    """Skip decorator for tests that require functional symlink"""
+    ok = can_symlink()
+    msg = "Requires functional symlink implementation"
+    return test if ok else unittest.skip(msg)(test)

Deleted: python/branches/pep-3151/Lib/test/symlink_support.py
==============================================================================
--- python/branches/pep-3151/Lib/test/symlink_support.py	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,206 +0,0 @@
-"""
-A module built to test if the current process has the privilege to
-create symlinks on Windows.
-"""
-
-# allow script to run natively under python 2.6+
-from __future__ import print_function
-
-import ctypes
-from ctypes import wintypes
-
-GetCurrentProcess = ctypes.windll.kernel32.GetCurrentProcess
-GetCurrentProcess.restype = wintypes.HANDLE
-OpenProcessToken = ctypes.windll.advapi32.OpenProcessToken
-OpenProcessToken.argtypes = (wintypes.HANDLE, wintypes.DWORD,
-                             ctypes.POINTER(wintypes.HANDLE))
-OpenProcessToken.restype = wintypes.BOOL
-
-class LUID(ctypes.Structure):
-    _fields_ = [
-            ('low_part', wintypes.DWORD),
-            ('high_part', wintypes.LONG),
-            ]
-
-    def __eq__(self, other):
-        return (
-                self.high_part == other.high_part and
-                self.low_part == other.low_part
-                )
-
-    def __ne__(self, other):
-        return not (self==other)
-
-LookupPrivilegeValue = ctypes.windll.advapi32.LookupPrivilegeValueW
-LookupPrivilegeValue.argtypes = (
-        wintypes.LPWSTR, # system name
-        wintypes.LPWSTR, # name
-        ctypes.POINTER(LUID),
-        )
-LookupPrivilegeValue.restype = wintypes.BOOL
-
-class TOKEN_INFORMATION_CLASS:
-    TokenUser = 1
-    TokenGroups = 2
-    TokenPrivileges = 3
-    # ... see http://msdn.microsoft.com/en-us/library/aa379626%28VS.85%29.aspx
-
-SE_PRIVILEGE_ENABLED_BY_DEFAULT = (0x00000001)
-SE_PRIVILEGE_ENABLED            = (0x00000002)
-SE_PRIVILEGE_REMOVED            = (0x00000004)
-SE_PRIVILEGE_USED_FOR_ACCESS    = (0x80000000)
-
-class LUID_AND_ATTRIBUTES(ctypes.Structure):
-    _fields_ = [
-            ('LUID', LUID),
-            ('attributes', wintypes.DWORD),
-            ]
-
-    def is_enabled(self):
-        return bool(self.attributes & SE_PRIVILEGE_ENABLED)
-
-    def enable(self):
-        self.attributes |= SE_PRIVILEGE_ENABLED
-
-    def get_name(self):
-        size = wintypes.DWORD(10240)
-        buf = ctypes.create_unicode_buffer(size.value)
-        res = LookupPrivilegeName(None, self.LUID, buf, size)
-        if res == 0:
-            raise RuntimeError
-        return buf[:size.value]
-
-    def __str__(self):
-        name = self.name
-        fmt = ['{name}', '{name} (enabled)'][self.is_enabled()]
-        return fmt.format(**vars())
-
-LookupPrivilegeName = ctypes.windll.advapi32.LookupPrivilegeNameW
-LookupPrivilegeName.argtypes = (
-        wintypes.LPWSTR, # lpSystemName
-        ctypes.POINTER(LUID), # lpLuid
-        wintypes.LPWSTR, # lpName
-        ctypes.POINTER(wintypes.DWORD), #cchName
-        )
-LookupPrivilegeName.restype = wintypes.BOOL
-
-class TOKEN_PRIVILEGES(ctypes.Structure):
-    _fields_ = [
-            ('count', wintypes.DWORD),
-            ('privileges', LUID_AND_ATTRIBUTES*0),
-            ]
-
-    def get_array(self):
-        array_type = LUID_AND_ATTRIBUTES*self.count
-        privileges = ctypes.cast(self.privileges,
-                                 ctypes.POINTER(array_type)).contents
-        return privileges
-
-    def __iter__(self):
-        return iter(self.get_array())
-
-PTOKEN_PRIVILEGES = ctypes.POINTER(TOKEN_PRIVILEGES)
-
-GetTokenInformation = ctypes.windll.advapi32.GetTokenInformation
-GetTokenInformation.argtypes = [
-        wintypes.HANDLE, # TokenHandle
-        ctypes.c_uint, # TOKEN_INFORMATION_CLASS value
-        ctypes.c_void_p, # TokenInformation
-        wintypes.DWORD, # TokenInformationLength
-        ctypes.POINTER(wintypes.DWORD), # ReturnLength
-        ]
-GetTokenInformation.restype = wintypes.BOOL
-
-# http://msdn.microsoft.com/en-us/library/aa375202%28VS.85%29.aspx
-AdjustTokenPrivileges = ctypes.windll.advapi32.AdjustTokenPrivileges
-AdjustTokenPrivileges.restype = wintypes.BOOL
-AdjustTokenPrivileges.argtypes = [
-        wintypes.HANDLE,                # TokenHandle
-        wintypes.BOOL,                  # DisableAllPrivileges
-        PTOKEN_PRIVILEGES,              # NewState (optional)
-        wintypes.DWORD,                 # BufferLength of PreviousState
-        PTOKEN_PRIVILEGES,              # PreviousState (out, optional)
-        ctypes.POINTER(wintypes.DWORD), # ReturnLength
-        ]
-
-def get_process_token():
-    "Get the current process token"
-    token = wintypes.HANDLE()
-    TOKEN_ALL_ACCESS = 0xf01ff
-    res = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, token)
-    if not res > 0:
-        raise RuntimeError("Couldn't get process token")
-    return token
-
-def get_symlink_luid():
-    "Get the LUID for the SeCreateSymbolicLinkPrivilege"
-    symlink_luid = LUID()
-    res = LookupPrivilegeValue(None, "SeCreateSymbolicLinkPrivilege",
-                               symlink_luid)
-    if not res > 0:
-        raise RuntimeError("Couldn't lookup privilege value")
-    return symlink_luid
-
-def get_privilege_information():
-    "Get all privileges associated with the current process."
-    # first call with zero length to determine what size buffer we need
-
-    return_length = wintypes.DWORD()
-    params = [
-            get_process_token(),
-            TOKEN_INFORMATION_CLASS.TokenPrivileges,
-            None,
-            0,
-            return_length,
-            ]
-
-    res = GetTokenInformation(*params)
-
-    # assume we now have the necessary length in return_length
-
-    buffer = ctypes.create_string_buffer(return_length.value)
-    params[2] = buffer
-    params[3] = return_length.value
-
-    res = GetTokenInformation(*params)
-    assert res > 0, "Error in second GetTokenInformation (%d)" % res
-
-    privileges = ctypes.cast(buffer, ctypes.POINTER(TOKEN_PRIVILEGES)).contents
-    return privileges
-
-def report_privilege_information():
-    "Report all privilege information assigned to the current process."
-    privileges = get_privilege_information()
-    print("found {0} privileges".format(privileges.count))
-    tuple(map(print, privileges))
-
-def enable_symlink_privilege():
-    """
-    Try to assign the symlink privilege to the current process token.
-    Return True if the assignment is successful.
-    """
-    # create a space in memory for a TOKEN_PRIVILEGES structure
-    #  with one element
-    size = ctypes.sizeof(TOKEN_PRIVILEGES)
-    size += ctypes.sizeof(LUID_AND_ATTRIBUTES)
-    buffer = ctypes.create_string_buffer(size)
-    tp = ctypes.cast(buffer, ctypes.POINTER(TOKEN_PRIVILEGES)).contents
-    tp.count = 1
-    tp.get_array()[0].enable()
-    tp.get_array()[0].LUID = get_symlink_luid()
-    token = get_process_token()
-    res = AdjustTokenPrivileges(token, False, tp, 0, None, None)
-    if res == 0:
-        raise RuntimeError("Error in AdjustTokenPrivileges")
-
-    ERROR_NOT_ALL_ASSIGNED = 1300
-    return ctypes.windll.kernel32.GetLastError() != ERROR_NOT_ALL_ASSIGNED
-
-def main():
-    assigned = enable_symlink_privilege()
-    msg = ['failure', 'success'][assigned]
-
-    print("Symlink privilege assignment completed with {0}".format(msg))
-
-if __name__ == '__main__':
-    main()

Modified: python/branches/pep-3151/Lib/test/test__locale.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test__locale.py	(original)
+++ python/branches/pep-3151/Lib/test/test__locale.py	Sat Feb 26 08:16:32 2011
@@ -59,7 +59,7 @@
         known_value = known_numerics.get(used_locale,
                                     ('', ''))[data_type == 'thousands_sep']
         if known_value and calc_value:
-            self.assertEquals(calc_value, known_value,
+            self.assertEqual(calc_value, known_value,
                                 self.lc_numeric_err_msg % (
                                     calc_value, known_value,
                                     calc_type, data_type, set_locale,
@@ -107,7 +107,7 @@
                     set_locale = setlocale(LC_NUMERIC)
                 except Error:
                     set_locale = "<not able to determine>"
-                self.assertEquals(nl_radixchar, li_radixchar,
+                self.assertEqual(nl_radixchar, li_radixchar,
                                 "%s (nl_langinfo) != %s (localeconv) "
                                 "(set to %s, using %s)" % (
                                                 nl_radixchar, li_radixchar,
@@ -127,9 +127,9 @@
             if loc == 'eu_ES' and localeconv()['decimal_point'] == "' ":
                 continue
 
-            self.assertEquals(int(eval('3.14') * 100), 314,
+            self.assertEqual(int(eval('3.14') * 100), 314,
                                 "using eval('3.14') failed for %s" % loc)
-            self.assertEquals(int(float('3.14') * 100), 314,
+            self.assertEqual(int(float('3.14') * 100), 314,
                                 "using float('3.14') failed for %s" % loc)
             if localeconv()['decimal_point'] != '.':
                 self.assertRaises(ValueError, float,

Modified: python/branches/pep-3151/Lib/test/test_abc.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_abc.py	(original)
+++ python/branches/pep-3151/Lib/test/test_abc.py	Sat Feb 26 08:16:32 2011
@@ -98,13 +98,6 @@
             self.assertRaises(TypeError, F)  # because bar is abstract now
             self.assertTrue(isabstract(F))
 
-    def test_type_has_no_abstractmethods(self):
-        # type pretends not to have __abstractmethods__.
-        self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
-        class meta(type):
-            pass
-        self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
-
     def test_metaclass_abc(self):
         # Metaclasses can be ABCs, too.
         class A(metaclass=abc.ABCMeta):
@@ -128,11 +121,32 @@
         self.assertFalse(issubclass(B, (A,)))
         self.assertNotIsInstance(b, A)
         self.assertNotIsInstance(b, (A,))
-        A.register(B)
+        B1 = A.register(B)
+        self.assertTrue(issubclass(B, A))
+        self.assertTrue(issubclass(B, (A,)))
+        self.assertIsInstance(b, A)
+        self.assertIsInstance(b, (A,))
+        self.assertIs(B1, B)
+        class C(B):
+            pass
+        c = C()
+        self.assertTrue(issubclass(C, A))
+        self.assertTrue(issubclass(C, (A,)))
+        self.assertIsInstance(c, A)
+        self.assertIsInstance(c, (A,))
+
+    def test_register_as_class_deco(self):
+        class A(metaclass=abc.ABCMeta):
+            pass
+        @A.register
+        class B(object):
+            pass
+        b = B()
         self.assertTrue(issubclass(B, A))
         self.assertTrue(issubclass(B, (A,)))
         self.assertIsInstance(b, A)
         self.assertIsInstance(b, (A,))
+        @A.register
         class C(B):
             pass
         c = C()
@@ -140,6 +154,7 @@
         self.assertTrue(issubclass(C, (A,)))
         self.assertIsInstance(c, A)
         self.assertIsInstance(c, (A,))
+        self.assertIs(C, A.register(C))
 
     def test_isinstance_invalidation(self):
         class A(metaclass=abc.ABCMeta):
@@ -192,8 +207,8 @@
     def test_register_non_class(self):
         class A(metaclass=abc.ABCMeta):
             pass
-        self.assertRaisesRegexp(TypeError, "Can only register classes",
-                                A.register, 4)
+        self.assertRaisesRegex(TypeError, "Can only register classes",
+                               A.register, 4)
 
     def test_registration_transitiveness(self):
         class A(metaclass=abc.ABCMeta):

Modified: python/branches/pep-3151/Lib/test/test_argparse.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_argparse.py	(original)
+++ python/branches/pep-3151/Lib/test/test_argparse.py	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,7 @@
 import inspect
 import os
 import shutil
+import stat
 import sys
 import textwrap
 import tempfile
@@ -45,14 +46,13 @@
 
     def tearDown(self):
         os.chdir(self.old_dir)
-        while True:
-            try:
-                shutil.rmtree(self.temp_dir)
-            except WindowsError:
-                continue
-            else:
-                break
+        shutil.rmtree(self.temp_dir, True)
 
+    def create_readonly_file(self, filename):
+        file_path = os.path.join(self.temp_dir, filename)
+        with open(file_path, 'w') as file:
+            file.write(filename)
+        os.chmod(file_path, stat.S_IREAD)
 
 class Sig(object):
 
@@ -1446,17 +1446,19 @@
             file = open(os.path.join(self.temp_dir, file_name), 'w')
             file.write(file_name)
             file.close()
+        self.create_readonly_file('readonly')
 
     argument_signatures = [
         Sig('-x', type=argparse.FileType()),
         Sig('spam', type=argparse.FileType('r')),
     ]
-    failures = ['-x', '']
+    failures = ['-x', '', 'non-existent-file.txt']
     successes = [
         ('foo', NS(x=None, spam=RFile('foo'))),
         ('-x foo bar', NS(x=RFile('foo'), spam=RFile('bar'))),
         ('bar -x foo', NS(x=RFile('foo'), spam=RFile('bar'))),
         ('-x - -', NS(x=sys.stdin, spam=sys.stdin)),
+        ('readonly', NS(x=None, spam=RFile('readonly'))),
     ]
 
 
@@ -1503,11 +1505,15 @@
 class TestFileTypeW(TempDirMixin, ParserTestCase):
     """Test the FileType option/argument type for writing files"""
 
+    def setUp(self):
+        super(TestFileTypeW, self).setUp()
+        self.create_readonly_file('readonly')
+
     argument_signatures = [
         Sig('-x', type=argparse.FileType('w')),
         Sig('spam', type=argparse.FileType('w')),
     ]
-    failures = ['-x', '']
+    failures = ['-x', '', 'readonly']
     successes = [
         ('foo', NS(x=None, spam=WFile('foo'))),
         ('-x foo bar', NS(x=WFile('foo'), spam=WFile('bar'))),
@@ -1708,7 +1714,8 @@
     def assertArgumentParserError(self, *args, **kwargs):
         self.assertRaises(ArgumentParserError, *args, **kwargs)
 
-    def _get_parser(self, subparser_help=False, prefix_chars=None):
+    def _get_parser(self, subparser_help=False, prefix_chars=None,
+                    aliases=False):
         # create a parser with a subparsers argument
         if prefix_chars:
             parser = ErrorRaisingArgumentParser(
@@ -1724,13 +1731,21 @@
             'bar', type=float, help='bar help')
 
         # check that only one subparsers argument can be added
-        subparsers = parser.add_subparsers(help='command help')
+        subparsers_kwargs = {}
+        if aliases:
+            subparsers_kwargs['metavar'] = 'COMMAND'
+            subparsers_kwargs['title'] = 'commands'
+        else:
+            subparsers_kwargs['help'] = 'command help'
+        subparsers = parser.add_subparsers(**subparsers_kwargs)
         self.assertArgumentParserError(parser.add_subparsers)
 
         # add first sub-parser
         parser1_kwargs = dict(description='1 description')
         if subparser_help:
             parser1_kwargs['help'] = '1 help'
+        if aliases:
+            parser1_kwargs['aliases'] = ['1alias1', '1alias2']
         parser1 = subparsers.add_parser('1', **parser1_kwargs)
         parser1.add_argument('-w', type=int, help='w help')
         parser1.add_argument('x', choices='abc', help='x help')
@@ -1947,6 +1962,44 @@
               -y {1,2,3}  y help
             '''))
 
+    def test_alias_invocation(self):
+        parser = self._get_parser(aliases=True)
+        self.assertEqual(
+            parser.parse_known_args('0.5 1alias1 b'.split()),
+            (NS(foo=False, bar=0.5, w=None, x='b'), []),
+        )
+        self.assertEqual(
+            parser.parse_known_args('0.5 1alias2 b'.split()),
+            (NS(foo=False, bar=0.5, w=None, x='b'), []),
+        )
+
+    def test_error_alias_invocation(self):
+        parser = self._get_parser(aliases=True)
+        self.assertArgumentParserError(parser.parse_args,
+                                       '0.5 1alias3 b'.split())
+
+    def test_alias_help(self):
+        parser = self._get_parser(aliases=True, subparser_help=True)
+        self.maxDiff = None
+        self.assertEqual(parser.format_help(), textwrap.dedent("""\
+            usage: PROG [-h] [--foo] bar COMMAND ...
+
+            main description
+
+            positional arguments:
+              bar                   bar help
+
+            optional arguments:
+              -h, --help            show this help message and exit
+              --foo                 foo help
+
+            commands:
+              COMMAND
+                1 (1alias1, 1alias2)
+                                    1 help
+                2                   2 help
+            """))
+
 # ============
 # Groups tests
 # ============
@@ -2487,6 +2540,46 @@
         '''
 
 
+class TestMutuallyExclusiveInGroup(MEMixin, TestCase):
+
+    def get_parser(self, required=None):
+        parser = ErrorRaisingArgumentParser(prog='PROG')
+        titled_group = parser.add_argument_group(
+            title='Titled group', description='Group description')
+        mutex_group = \
+            titled_group.add_mutually_exclusive_group(required=required)
+        mutex_group.add_argument('--bar', help='bar help')
+        mutex_group.add_argument('--baz', help='baz help')
+        return parser
+
+    failures = ['--bar X --baz Y', '--baz X --bar Y']
+    successes = [
+        ('--bar X', NS(bar='X', baz=None)),
+        ('--baz Y', NS(bar=None, baz='Y')),
+    ]
+    successes_when_not_required = [
+        ('', NS(bar=None, baz=None)),
+    ]
+
+    usage_when_not_required = '''\
+        usage: PROG [-h] [--bar BAR | --baz BAZ]
+        '''
+    usage_when_required = '''\
+        usage: PROG [-h] (--bar BAR | --baz BAZ)
+        '''
+    help = '''\
+
+        optional arguments:
+          -h, --help  show this help message and exit
+
+        Titled group:
+          Group description
+
+          --bar BAR   bar help
+          --baz BAZ   baz help
+        '''
+
+
 class TestMutuallyExclusiveOptionalsAndPositionalsMixed(MEMixin, TestCase):
 
     def get_parser(self, required):
@@ -2698,18 +2791,18 @@
 
     def test_empty(self):
         ns = argparse.Namespace()
-        self.assertEquals('' in ns, False)
-        self.assertEquals('' not in ns, True)
-        self.assertEquals('x' in ns, False)
+        self.assertEqual('' in ns, False)
+        self.assertEqual('' not in ns, True)
+        self.assertEqual('x' in ns, False)
 
     def test_non_empty(self):
         ns = argparse.Namespace(x=1, y=2)
-        self.assertEquals('x' in ns, True)
-        self.assertEquals('x' not in ns, False)
-        self.assertEquals('y' in ns, True)
-        self.assertEquals('' in ns, False)
-        self.assertEquals('xx' in ns, False)
-        self.assertEquals('z' in ns, False)
+        self.assertEqual('x' in ns, True)
+        self.assertEqual('x' not in ns, False)
+        self.assertEqual('y' in ns, True)
+        self.assertEqual('' in ns, False)
+        self.assertEqual('xx' in ns, False)
+        self.assertEqual('z' in ns, False)
 
 # =====================
 # Help formatting tests
@@ -4235,7 +4328,7 @@
     def _test_module_encoding(self, path):
         path, _ = os.path.splitext(path)
         path += ".py"
-        with codecs.open(path, 'r', 'utf8') as f:
+        with codecs.open(path, 'r', 'utf-8') as f:
             f.read()
 
     def test_argparse_module_encoding(self):
@@ -4259,7 +4352,7 @@
 # ArgumentTypeError tests
 # =======================
 
-class TestArgumentError(TestCase):
+class TestArgumentTypeError(TestCase):
 
     def test_argument_type_error(self):
 
@@ -4315,7 +4408,7 @@
         items = [
             name
             for name, value in vars(argparse).items()
-            if not name.startswith("_")
+            if not (name.startswith("_") or name == 'ngettext')
             if not inspect.ismodule(value)
         ]
         self.assertEqual(sorted(items), sorted(argparse.__all__))

Modified: python/branches/pep-3151/Lib/test/test_array.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_array.py	(original)
+++ python/branches/pep-3151/Lib/test/test_array.py	Sat Feb 26 08:16:32 2011
@@ -22,7 +22,7 @@
 
 class ArraySubclassWithKwargs(array.array):
     def __init__(self, typecode, newarg=None):
-        array.array.__init__(typecode)
+        array.array.__init__(self)
 
 tests = [] # list to accumulate all tests
 typecodes = "ubBhHiIlLfd"
@@ -238,9 +238,9 @@
     def test_reduce_ex(self):
         a = array.array(self.typecode, self.example)
         for protocol in range(3):
-            self.assert_(a.__reduce_ex__(protocol)[0] is array.array)
+            self.assertIs(a.__reduce_ex__(protocol)[0], array.array)
         for protocol in range(3, pickle.HIGHEST_PROTOCOL):
-            self.assert_(a.__reduce_ex__(protocol)[0] is array_reconstructor)
+            self.assertIs(a.__reduce_ex__(protocol)[0], array_reconstructor)
 
     def test_pickle(self):
         for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
@@ -398,6 +398,11 @@
         if a.itemsize>1:
             self.assertRaises(ValueError, b.frombytes, b"x")
 
+    def test_fromarray(self):
+        a = array.array(self.typecode, self.example)
+        b = array.array(self.typecode, a)
+        self.assertEqual(a, b)
+
     def test_repr(self):
         a = array.array(self.typecode, 2*self.example)
         self.assertEqual(a, eval(repr(a), {"array": array.array}))
@@ -504,6 +509,12 @@
             array.array(self.typecode)
         )
 
+        a = 5 * array.array(self.typecode, self.example[:1])
+        self.assertEqual(
+            a,
+            array.array(self.typecode, [a[0]] * 5)
+        )
+
         self.assertRaises(TypeError, a.__mul__, "bad")
 
     def test_imul(self):
@@ -785,11 +796,11 @@
                     data.reverse()
                     L[start:stop:step] = data
                     a[start:stop:step] = array.array(self.typecode, data)
-                    self.assertEquals(a, array.array(self.typecode, L))
+                    self.assertEqual(a, array.array(self.typecode, L))
 
                     del L[start:stop:step]
                     del a[start:stop:step]
-                    self.assertEquals(a, array.array(self.typecode, L))
+                    self.assertEqual(a, array.array(self.typecode, L))
 
     def test_index(self):
         example = 2*self.example
@@ -1107,6 +1118,11 @@
 
         self.assertRaises(AttributeError, setattr, a, "color", "blue")
 
+    def test_frombytearray(self):
+        a = array.array('b', range(10))
+        b = array.array(self.typecode, a)
+        self.assertEqual(a, b)
+
 class SignedNumberTest(NumberTest):
     example = [-1, 0, 1, 42, 0x7f]
     smallerexample = [-1, 0, 1, 42, 0x7e]

Modified: python/branches/pep-3151/Lib/test/test_ast.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_ast.py	(original)
+++ python/branches/pep-3151/Lib/test/test_ast.py	Sat Feb 26 08:16:32 2011
@@ -141,7 +141,7 @@
                                     (eval_tests, eval_results, "eval")):
             for i, o in zip(input, output):
                 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
-                self.assertEquals(to_tuple(ast_tree), o)
+                self.assertEqual(to_tuple(ast_tree), o)
                 self._assertTrueorder(ast_tree, (0, 0))
 
     def test_slice(self):
@@ -164,20 +164,20 @@
 
     def test_nodeclasses(self):
         x = ast.BinOp(1, 2, 3, lineno=0)
-        self.assertEquals(x.left, 1)
-        self.assertEquals(x.op, 2)
-        self.assertEquals(x.right, 3)
-        self.assertEquals(x.lineno, 0)
+        self.assertEqual(x.left, 1)
+        self.assertEqual(x.op, 2)
+        self.assertEqual(x.right, 3)
+        self.assertEqual(x.lineno, 0)
 
         # node raises exception when not given enough arguments
         self.assertRaises(TypeError, ast.BinOp, 1, 2)
 
         # can set attributes through kwargs too
         x = ast.BinOp(left=1, op=2, right=3, lineno=0)
-        self.assertEquals(x.left, 1)
-        self.assertEquals(x.op, 2)
-        self.assertEquals(x.right, 3)
-        self.assertEquals(x.lineno, 0)
+        self.assertEqual(x.left, 1)
+        self.assertEqual(x.op, 2)
+        self.assertEqual(x.right, 3)
+        self.assertEqual(x.lineno, 0)
 
         # this used to fail because Sub._fields was None
         x = ast.Sub()
@@ -195,7 +195,14 @@
             for protocol in protocols:
                 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
                     ast2 = mod.loads(mod.dumps(ast, protocol))
-                    self.assertEquals(to_tuple(ast2), to_tuple(ast))
+                    self.assertEqual(to_tuple(ast2), to_tuple(ast))
+
+    def test_invalid_sum(self):
+        pos = dict(lineno=2, col_offset=3)
+        m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
+        with self.assertRaises(TypeError) as cm:
+            compile(m, "<test>", "exec")
+        self.assertIn("but got <_ast.expr", str(cm.exception))
 
 
 class ASTHelpers_Test(unittest.TestCase):
@@ -255,6 +262,14 @@
         self.assertEqual(ast.dump(src, include_attributes=True),
             'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
             'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
+            'col_offset=0))'
+        )
+        # issue10869: do not increment lineno of root twice
+        src = ast.parse('1 + 1', mode='eval')
+        self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
+        self.assertEqual(ast.dump(src, include_attributes=True),
+            'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
+            'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
             'col_offset=0))'
         )
 

Modified: python/branches/pep-3151/Lib/test/test_asyncore.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_asyncore.py	(original)
+++ python/branches/pep-3151/Lib/test/test_asyncore.py	Sat Feb 26 08:16:32 2011
@@ -312,8 +312,8 @@
         d = asyncore.dispatcher(socket.socket())
         # make sure the error message no longer refers to the socket
         # object but the dispatcher instance instead
-        self.assertRaisesRegexp(AttributeError, 'dispatcher instance',
-                                getattr, d, 'foo')
+        self.assertRaisesRegex(AttributeError, 'dispatcher instance',
+                               getattr, d, 'foo')
         # cheap inheritance with the underlying socket is supposed
         # to still work but a DeprecationWarning is expected
         with warnings.catch_warnings(record=True) as w:
@@ -329,7 +329,7 @@
         if hasattr(os, 'strerror'):
             self.assertEqual(err, os.strerror(errno.EPERM))
         err = asyncore._strerror(-1)
-        self.assertIn("unknown error", err.lower())
+        self.assertTrue(err != "")
 
 
 class dispatcherwithsend_noread(asyncore.dispatcher_with_send):
@@ -352,7 +352,7 @@
     @support.reap_threads
     def test_send(self):
         evt = threading.Event()
-        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        sock = socket.socket()
         sock.settimeout(3)
         port = support.bind_port(sock)
 
@@ -367,7 +367,7 @@
 
             data = b"Suppose there isn't a 16-ton weight?"
             d = dispatcherwithsend_noread()
-            d.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+            d.create_socket()
             d.connect((HOST, port))
 
             # give time for socket to connect
@@ -474,7 +474,7 @@
 
     def __init__(self, handler=BaseTestHandler, host=HOST, port=0):
         asyncore.dispatcher.__init__(self)
-        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+        self.create_socket()
         self.set_reuse_addr()
         self.bind((host, port))
         self.listen(5)
@@ -495,7 +495,7 @@
 
     def __init__(self, address):
         BaseTestHandler.__init__(self)
-        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+        self.create_socket()
         self.connect(address)
 
     def handle_connect(self):
@@ -536,7 +536,7 @@
 
             def __init__(self):
                 BaseTestHandler.__init__(self)
-                self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+                self.create_socket()
                 self.bind((HOST, 0))
                 self.listen(5)
                 self.address = self.socket.getsockname()[:2]
@@ -555,7 +555,7 @@
 
             def __init__(self):
                 BaseTestHandler.__init__(self)
-                self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+                self.create_socket()
                 self.bind((HOST, 0))
                 self.listen(5)
                 self.address = self.socket.getsockname()[:2]
@@ -693,20 +693,20 @@
 
     def test_create_socket(self):
         s = asyncore.dispatcher()
-        s.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+        s.create_socket()
         self.assertEqual(s.socket.family, socket.AF_INET)
         SOCK_NONBLOCK = getattr(socket, 'SOCK_NONBLOCK', 0)
         self.assertEqual(s.socket.type, socket.SOCK_STREAM | SOCK_NONBLOCK)
 
     def test_bind(self):
         s1 = asyncore.dispatcher()
-        s1.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+        s1.create_socket()
         s1.bind((HOST, 0))
         s1.listen(5)
         port = s1.socket.getsockname()[1]
 
         s2 = asyncore.dispatcher()
-        s2.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+        s2.create_socket()
         # EADDRINUSE indicates the socket was correctly bound
         self.assertRaises(socket.error, s2.bind, (HOST, port))
 
@@ -723,7 +723,7 @@
             self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET,
                                                  socket.SO_REUSEADDR))
             s.socket.close()
-            s.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+            s.create_socket()
             s.set_reuse_addr()
             self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET,
                                                  socket.SO_REUSEADDR))

Modified: python/branches/pep-3151/Lib/test/test_atexit.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_atexit.py	(original)
+++ python/branches/pep-3151/Lib/test/test_atexit.py	Sat Feb 26 08:16:32 2011
@@ -25,8 +25,9 @@
 
 class TestCase(unittest.TestCase):
     def setUp(self):
+        self.save_stdout = sys.stdout
+        self.save_stderr = sys.stderr
         self.stream = io.StringIO()
-        self.save_stdout, self.save_stderr = sys.stderr, sys.stdout
         sys.stdout = sys.stderr = self.stream
         atexit._clear()
 
@@ -65,6 +66,14 @@
 
         self.assertRaises(TypeError, atexit._run_exitfuncs)
 
+    def test_raise_unnormalized(self):
+        # Issue #10756: Make sure that an unnormalized exception is
+        # handled properly
+        atexit.register(lambda: 1 / 0)
+
+        self.assertRaises(ZeroDivisionError, atexit._run_exitfuncs)
+        self.assertIn("ZeroDivisionError", self.stream.getvalue())
+
     def test_stress(self):
         a = [0]
         def inc():

Modified: python/branches/pep-3151/Lib/test/test_augassign.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_augassign.py	(original)
+++ python/branches/pep-3151/Lib/test/test_augassign.py	Sat Feb 26 08:16:32 2011
@@ -17,7 +17,7 @@
         x |= 5
         x ^= 1
         x /= 2
-        self.assertEquals(x, 3.0)
+        self.assertEqual(x, 3.0)
 
     def test_with_unpacking(self):
         self.assertRaises(SyntaxError, compile, "x, b += 3", "<test>", "exec")
@@ -34,7 +34,7 @@
         x[0] |= 5
         x[0] ^= 1
         x[0] /= 2
-        self.assertEquals(x[0], 3.0)
+        self.assertEqual(x[0], 3.0)
 
     def testInDict(self):
         x = {0: 2}
@@ -48,21 +48,21 @@
         x[0] |= 5
         x[0] ^= 1
         x[0] /= 2
-        self.assertEquals(x[0], 3.0)
+        self.assertEqual(x[0], 3.0)
 
     def testSequences(self):
         x = [1,2]
         x += [3,4]
         x *= 2
 
-        self.assertEquals(x, [1, 2, 3, 4, 1, 2, 3, 4])
+        self.assertEqual(x, [1, 2, 3, 4, 1, 2, 3, 4])
 
         x = [1, 2, 3]
         y = x
         x[1:2] *= 2
         y[1:2] += [1]
 
-        self.assertEquals(x, [1, 2, 1, 2, 3])
+        self.assertEqual(x, [1, 2, 1, 2, 3])
         self.assertTrue(x is y)
 
     def testCustomMethods1(self):
@@ -90,14 +90,14 @@
 
         self.assertIsInstance(x, aug_test)
         self.assertTrue(y is not x)
-        self.assertEquals(x.val, 11)
+        self.assertEqual(x.val, 11)
 
         x = aug_test2(2)
         y = x
         x += 10
 
         self.assertTrue(y is x)
-        self.assertEquals(x.val, 12)
+        self.assertEqual(x.val, 12)
 
         x = aug_test3(3)
         y = x
@@ -105,7 +105,7 @@
 
         self.assertIsInstance(x, aug_test3)
         self.assertTrue(y is not x)
-        self.assertEquals(x.val, 13)
+        self.assertEqual(x.val, 13)
 
 
     def testCustomMethods2(test_self):
@@ -269,7 +269,7 @@
         1 << x
         x <<= 1
 
-        test_self.assertEquals(output, '''\
+        test_self.assertEqual(output, '''\
 __add__ called
 __radd__ called
 __iadd__ called

Modified: python/branches/pep-3151/Lib/test/test_base64.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_base64.py	(original)
+++ python/branches/pep-3151/Lib/test/test_base64.py	Sat Feb 26 08:16:32 2011
@@ -6,7 +6,7 @@
 import subprocess
 
 
-
+
 class LegacyBase64TestCase(unittest.TestCase):
     def test_encodebytes(self):
         eq = self.assertEqual
@@ -58,7 +58,7 @@
         base64.decode(infp, outfp)
         self.assertEqual(outfp.getvalue(), b'www.python.org')
 
-
+
 class BaseXYTestCase(unittest.TestCase):
     def test_b64encode(self):
         eq = self.assertEqual
@@ -138,9 +138,25 @@
         eq(base64.urlsafe_b64decode(b'01a-b_cd'), b'\xd3V\xbeo\xf7\x1d')
         self.assertRaises(TypeError, base64.urlsafe_b64decode, "")
 
-    def test_b64decode_error(self):
+    def test_b64decode_padding_error(self):
         self.assertRaises(binascii.Error, base64.b64decode, b'abc')
 
+    def test_b64decode_invalid_chars(self):
+        # issue 1466065: Test some invalid characters.
+        tests = ((b'%3d==', b'\xdd'),
+                 (b'$3d==', b'\xdd'),
+                 (b'[==', b''),
+                 (b'YW]3=', b'am'),
+                 (b'3{d==', b'\xdd'),
+                 (b'3d}==', b'\xdd'),
+                 (b'@@', b''),
+                 (b'!', b''),
+                 (b'YWJj\nYWI=', b'abcab'))
+        for bstr, res in tests:
+            self.assertEqual(base64.b64decode(bstr), res)
+            with self.assertRaises(binascii.Error):
+                base64.b64decode(bstr, validate=True)
+
     def test_b32encode(self):
         eq = self.assertEqual
         eq(base64.b32encode(b''), b'')
@@ -209,7 +225,7 @@
         self.assertTrue(issubclass(binascii.Error, ValueError))
 
 
-
+
 class TestMain(unittest.TestCase):
     def get_output(self, *args, **options):
         args = (sys.executable, '-m', 'base64') + args
@@ -228,20 +244,20 @@
             fp.write(b'a\xffb\n')
 
         output = self.get_output('-e', support.TESTFN)
-        self.assertEquals(output.rstrip(), b'Yf9iCg==')
+        self.assertEqual(output.rstrip(), b'Yf9iCg==')
 
         with open(support.TESTFN, 'rb') as fp:
             output = self.get_output('-e', stdin=fp)
-        self.assertEquals(output.rstrip(), b'Yf9iCg==')
+        self.assertEqual(output.rstrip(), b'Yf9iCg==')
 
     def test_decode(self):
         with open(support.TESTFN, 'wb') as fp:
             fp.write(b'Yf9iCg==')
         output = self.get_output('-d', support.TESTFN)
-        self.assertEquals(output.rstrip(), b'a\xffb')
+        self.assertEqual(output.rstrip(), b'a\xffb')
+
 
 
-
 def test_main():
     support.run_unittest(__name__)
 

Modified: python/branches/pep-3151/Lib/test/test_bigaddrspace.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_bigaddrspace.py	(original)
+++ python/branches/pep-3151/Lib/test/test_bigaddrspace.py	Sat Feb 26 08:16:32 2011
@@ -23,25 +23,34 @@
         # Allocate a bytestring that's near the maximum size allowed by
         # the address space, and then try to build a new, larger one through
         # concatenation.
-        x = b"x" * (MAX_Py_ssize_t - 128)
-        self.assertRaises(OverflowError, operator.add, x, b"x" * 128)
+        try:
+            x = b"x" * (MAX_Py_ssize_t - 128)
+            self.assertRaises(OverflowError, operator.add, x, b"x" * 128)
+        finally:
+            x = None
 
     @bigaddrspacetest
     def test_optimized_concat(self):
-        x = b"x" * (MAX_Py_ssize_t - 128)
+        try:
+            x = b"x" * (MAX_Py_ssize_t - 128)
 
-        with self.assertRaises(OverflowError) as cm:
-            # this statement uses a fast path in ceval.c
-            x = x + b"x" * 128
-
-        with self.assertRaises(OverflowError) as cm:
-            # this statement uses a fast path in ceval.c
-            x +=  b"x" * 128
+            with self.assertRaises(OverflowError) as cm:
+                # this statement used a fast path in ceval.c
+                x = x + b"x" * 128
+
+            with self.assertRaises(OverflowError) as cm:
+                # this statement used a fast path in ceval.c
+                x +=  b"x" * 128
+        finally:
+            x = None
 
     @bigaddrspacetest
     def test_repeat(self):
-        x = b"x" * (MAX_Py_ssize_t - 128)
-        self.assertRaises(OverflowError, operator.mul, x, 128)
+        try:
+            x = b"x" * (MAX_Py_ssize_t - 128)
+            self.assertRaises(OverflowError, operator.mul, x, 128)
+        finally:
+            x = None
 
 
 class StrTest(unittest.TestCase):
@@ -50,28 +59,37 @@
 
     @bigaddrspacetest
     def test_concat(self):
-        # Create a string half the size that would fill the address space
-        x = "x" * (MAX_Py_ssize_t // (2 * self.unicodesize))
-        # Unicode objects trigger MemoryError in case an operation that's
-        # going to cause a size overflow is executed
-        self.assertRaises(MemoryError, operator.add, x, x)
+        try:
+            # Create a string that would fill almost the address space
+            x = "x" * int(MAX_Py_ssize_t // (1.1 * self.unicodesize))
+            # Unicode objects trigger MemoryError in case an operation that's
+            # going to cause a size overflow is executed
+            self.assertRaises(MemoryError, operator.add, x, x)
+        finally:
+            x = None
 
     @bigaddrspacetest
     def test_optimized_concat(self):
-        x = "x" * (MAX_Py_ssize_t // (2 * self.unicodesize))
+        try:
+            x = "x" * int(MAX_Py_ssize_t // (1.1 * self.unicodesize))
 
-        with self.assertRaises(MemoryError) as cm:
-            # this statement uses a fast path in ceval.c
-            x = x + x
-
-        with self.assertRaises(MemoryError) as cm:
-            # this statement uses a fast path in ceval.c
-            x +=  x
+            with self.assertRaises(MemoryError) as cm:
+                # this statement uses a fast path in ceval.c
+                x = x + x
+
+            with self.assertRaises(MemoryError) as cm:
+                # this statement uses a fast path in ceval.c
+                x +=  x
+        finally:
+            x = None
 
     @bigaddrspacetest
     def test_repeat(self):
-        x = "x" * (MAX_Py_ssize_t // (2 * self.unicodesize))
-        self.assertRaises(MemoryError, operator.mul, x, 2)
+        try:
+            x = "x" * int(MAX_Py_ssize_t // (1.1 * self.unicodesize))
+            self.assertRaises(MemoryError, operator.mul, x, 2)
+        finally:
+            x = None
 
 
 def test_main():

Modified: python/branches/pep-3151/Lib/test/test_bigmem.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_bigmem.py	(original)
+++ python/branches/pep-3151/Lib/test/test_bigmem.py	Sat Feb 26 08:16:32 2011
@@ -13,7 +13,7 @@
 #    doesn't release the old 's' (if it exists) until well after its new
 #    value has been created. Use 'del s' before the create_largestring call.
 #
-#  - Do *not* compare large objects using assertEquals or similar. It's a
+#  - Do *not* compare large objects using assertEqual or similar. It's a
 #    lengthy operation and the errormessage will be utterly useless due to
 #    its size. To make sure whether a result has the right contents, better
 #    to use the strip or count methods, or compare meaningful slices.
@@ -48,32 +48,32 @@
         SUBSTR = self.from_latin1(' abc def ghi')
         s = _('-') * size + SUBSTR
         caps = s.capitalize()
-        self.assertEquals(caps[-len(SUBSTR):],
+        self.assertEqual(caps[-len(SUBSTR):],
                          SUBSTR.capitalize())
-        self.assertEquals(caps.lstrip(_('-')), SUBSTR)
+        self.assertEqual(caps.lstrip(_('-')), SUBSTR)
 
     @bigmemtest(minsize=_2G + 10, memuse=1)
     def test_center(self, size):
         SUBSTR = self.from_latin1(' abc def ghi')
         s = SUBSTR.center(size)
-        self.assertEquals(len(s), size)
+        self.assertEqual(len(s), size)
         lpadsize = rpadsize = (len(s) - len(SUBSTR)) // 2
         if len(s) % 2:
             lpadsize += 1
-        self.assertEquals(s[lpadsize:-rpadsize], SUBSTR)
-        self.assertEquals(s.strip(), SUBSTR.strip())
+        self.assertEqual(s[lpadsize:-rpadsize], SUBSTR)
+        self.assertEqual(s.strip(), SUBSTR.strip())
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_count(self, size):
         _ = self.from_latin1
         SUBSTR = _(' abc def ghi')
         s = _('.') * size + SUBSTR
-        self.assertEquals(s.count(_('.')), size)
+        self.assertEqual(s.count(_('.')), size)
         s += _('.')
-        self.assertEquals(s.count(_('.')), size + 1)
-        self.assertEquals(s.count(_(' ')), 3)
-        self.assertEquals(s.count(_('i')), 1)
-        self.assertEquals(s.count(_('j')), 0)
+        self.assertEqual(s.count(_('.')), size + 1)
+        self.assertEqual(s.count(_(' ')), 3)
+        self.assertEqual(s.count(_('i')), 1)
+        self.assertEqual(s.count(_('j')), 0)
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_endswith(self, size):
@@ -92,13 +92,13 @@
         _ = self.from_latin1
         s = _('-') * size
         tabsize = 8
-        self.assertEquals(s.expandtabs(), s)
+        self.assertEqual(s.expandtabs(), s)
         del s
         slen, remainder = divmod(size, tabsize)
         s = _('       \t') * slen
         s = s.expandtabs(tabsize)
-        self.assertEquals(len(s), size - remainder)
-        self.assertEquals(len(s.strip(_(' '))), 0)
+        self.assertEqual(len(s), size - remainder)
+        self.assertEqual(len(s.strip(_(' '))), 0)
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_find(self, size):
@@ -106,16 +106,16 @@
         SUBSTR = _(' abc def ghi')
         sublen = len(SUBSTR)
         s = _('').join([SUBSTR, _('-') * size, SUBSTR])
-        self.assertEquals(s.find(_(' ')), 0)
-        self.assertEquals(s.find(SUBSTR), 0)
-        self.assertEquals(s.find(_(' '), sublen), sublen + size)
-        self.assertEquals(s.find(SUBSTR, len(SUBSTR)), sublen + size)
-        self.assertEquals(s.find(_('i')), SUBSTR.find(_('i')))
-        self.assertEquals(s.find(_('i'), sublen),
+        self.assertEqual(s.find(_(' ')), 0)
+        self.assertEqual(s.find(SUBSTR), 0)
+        self.assertEqual(s.find(_(' '), sublen), sublen + size)
+        self.assertEqual(s.find(SUBSTR, len(SUBSTR)), sublen + size)
+        self.assertEqual(s.find(_('i')), SUBSTR.find(_('i')))
+        self.assertEqual(s.find(_('i'), sublen),
                          sublen + size + SUBSTR.find(_('i')))
-        self.assertEquals(s.find(_('i'), size),
+        self.assertEqual(s.find(_('i'), size),
                          sublen + size + SUBSTR.find(_('i')))
-        self.assertEquals(s.find(_('j')), -1)
+        self.assertEqual(s.find(_('j')), -1)
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_index(self, size):
@@ -123,14 +123,14 @@
         SUBSTR = _(' abc def ghi')
         sublen = len(SUBSTR)
         s = _('').join([SUBSTR, _('-') * size, SUBSTR])
-        self.assertEquals(s.index(_(' ')), 0)
-        self.assertEquals(s.index(SUBSTR), 0)
-        self.assertEquals(s.index(_(' '), sublen), sublen + size)
-        self.assertEquals(s.index(SUBSTR, sublen), sublen + size)
-        self.assertEquals(s.index(_('i')), SUBSTR.index(_('i')))
-        self.assertEquals(s.index(_('i'), sublen),
+        self.assertEqual(s.index(_(' ')), 0)
+        self.assertEqual(s.index(SUBSTR), 0)
+        self.assertEqual(s.index(_(' '), sublen), sublen + size)
+        self.assertEqual(s.index(SUBSTR, sublen), sublen + size)
+        self.assertEqual(s.index(_('i')), SUBSTR.index(_('i')))
+        self.assertEqual(s.index(_('i'), sublen),
                          sublen + size + SUBSTR.index(_('i')))
-        self.assertEquals(s.index(_('i'), size),
+        self.assertEqual(s.index(_('i'), size),
                          sublen + size + SUBSTR.index(_('i')))
         self.assertRaises(ValueError, s.index, _('j'))
 
@@ -209,8 +209,8 @@
         _ = self.from_latin1
         s = _('A') * size
         x = s.join([_('aaaaa'), _('bbbbb')])
-        self.assertEquals(x.count(_('a')), 5)
-        self.assertEquals(x.count(_('b')), 5)
+        self.assertEqual(x.count(_('a')), 5)
+        self.assertEqual(x.count(_('b')), 5)
         self.assertTrue(x.startswith(_('aaaaaA')))
         self.assertTrue(x.endswith(_('Abbbbb')))
 
@@ -220,27 +220,27 @@
         SUBSTR = _(' abc def ghi')
         s = SUBSTR.ljust(size)
         self.assertTrue(s.startswith(SUBSTR + _('  ')))
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.strip(), SUBSTR.strip())
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.strip(), SUBSTR.strip())
 
     @bigmemtest(minsize=_2G + 10, memuse=2)
     def test_lower(self, size):
         _ = self.from_latin1
         s = _('A') * size
         s = s.lower()
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.count(_('a')), size)
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.count(_('a')), size)
 
     @bigmemtest(minsize=_2G + 10, memuse=1)
     def test_lstrip(self, size):
         _ = self.from_latin1
         SUBSTR = _('abc def ghi')
         s = SUBSTR.rjust(size)
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.lstrip(), SUBSTR.lstrip())
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.lstrip(), SUBSTR.lstrip())
         del s
         s = SUBSTR.ljust(size)
-        self.assertEquals(len(s), size)
+        self.assertEqual(len(s), size)
         # Type-specific optimization
         if isinstance(s, (str, bytes)):
             stripped = s.lstrip()
@@ -252,12 +252,12 @@
         replacement = _('a')
         s = _(' ') * size
         s = s.replace(_(' '), replacement)
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.count(replacement), size)
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.count(replacement), size)
         s = s.replace(replacement, _(' '), size - 4)
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.count(replacement), 4)
-        self.assertEquals(s[-10:], _('      aaaa'))
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.count(replacement), 4)
+        self.assertEqual(s[-10:], _('      aaaa'))
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_rfind(self, size):
@@ -265,15 +265,15 @@
         SUBSTR = _(' abc def ghi')
         sublen = len(SUBSTR)
         s = _('').join([SUBSTR, _('-') * size, SUBSTR])
-        self.assertEquals(s.rfind(_(' ')), sublen + size + SUBSTR.rfind(_(' ')))
-        self.assertEquals(s.rfind(SUBSTR), sublen + size)
-        self.assertEquals(s.rfind(_(' '), 0, size), SUBSTR.rfind(_(' ')))
-        self.assertEquals(s.rfind(SUBSTR, 0, sublen + size), 0)
-        self.assertEquals(s.rfind(_('i')), sublen + size + SUBSTR.rfind(_('i')))
-        self.assertEquals(s.rfind(_('i'), 0, sublen), SUBSTR.rfind(_('i')))
-        self.assertEquals(s.rfind(_('i'), 0, sublen + size),
-                          SUBSTR.rfind(_('i')))
-        self.assertEquals(s.rfind(_('j')), -1)
+        self.assertEqual(s.rfind(_(' ')), sublen + size + SUBSTR.rfind(_(' ')))
+        self.assertEqual(s.rfind(SUBSTR), sublen + size)
+        self.assertEqual(s.rfind(_(' '), 0, size), SUBSTR.rfind(_(' ')))
+        self.assertEqual(s.rfind(SUBSTR, 0, sublen + size), 0)
+        self.assertEqual(s.rfind(_('i')), sublen + size + SUBSTR.rfind(_('i')))
+        self.assertEqual(s.rfind(_('i'), 0, sublen), SUBSTR.rfind(_('i')))
+        self.assertEqual(s.rfind(_('i'), 0, sublen + size),
+                         SUBSTR.rfind(_('i')))
+        self.assertEqual(s.rfind(_('j')), -1)
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_rindex(self, size):
@@ -281,17 +281,17 @@
         SUBSTR = _(' abc def ghi')
         sublen = len(SUBSTR)
         s = _('').join([SUBSTR, _('-') * size, SUBSTR])
-        self.assertEquals(s.rindex(_(' ')),
-                          sublen + size + SUBSTR.rindex(_(' ')))
-        self.assertEquals(s.rindex(SUBSTR), sublen + size)
-        self.assertEquals(s.rindex(_(' '), 0, sublen + size - 1),
-                          SUBSTR.rindex(_(' ')))
-        self.assertEquals(s.rindex(SUBSTR, 0, sublen + size), 0)
-        self.assertEquals(s.rindex(_('i')),
-                          sublen + size + SUBSTR.rindex(_('i')))
-        self.assertEquals(s.rindex(_('i'), 0, sublen), SUBSTR.rindex(_('i')))
-        self.assertEquals(s.rindex(_('i'), 0, sublen + size),
-                          SUBSTR.rindex(_('i')))
+        self.assertEqual(s.rindex(_(' ')),
+                         sublen + size + SUBSTR.rindex(_(' ')))
+        self.assertEqual(s.rindex(SUBSTR), sublen + size)
+        self.assertEqual(s.rindex(_(' '), 0, sublen + size - 1),
+                         SUBSTR.rindex(_(' ')))
+        self.assertEqual(s.rindex(SUBSTR, 0, sublen + size), 0)
+        self.assertEqual(s.rindex(_('i')),
+                         sublen + size + SUBSTR.rindex(_('i')))
+        self.assertEqual(s.rindex(_('i'), 0, sublen), SUBSTR.rindex(_('i')))
+        self.assertEqual(s.rindex(_('i'), 0, sublen + size),
+                         SUBSTR.rindex(_('i')))
         self.assertRaises(ValueError, s.rindex, _('j'))
 
     @bigmemtest(minsize=_2G + 10, memuse=1)
@@ -300,19 +300,19 @@
         SUBSTR = _(' abc def ghi')
         s = SUBSTR.ljust(size)
         self.assertTrue(s.startswith(SUBSTR + _('  ')))
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.strip(), SUBSTR.strip())
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.strip(), SUBSTR.strip())
 
     @bigmemtest(minsize=_2G + 10, memuse=1)
     def test_rstrip(self, size):
         _ = self.from_latin1
         SUBSTR = _(' abc def ghi')
         s = SUBSTR.ljust(size)
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.rstrip(), SUBSTR.rstrip())
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.rstrip(), SUBSTR.rstrip())
         del s
         s = SUBSTR.rjust(size)
-        self.assertEquals(len(s), size)
+        self.assertEqual(len(s), size)
         # Type-specific optimization
         if isinstance(s, (str, bytes)):
             stripped = s.rstrip()
@@ -330,16 +330,16 @@
         SUBSTR = _('a') + _(' ') * chunksize
         s = SUBSTR * chunksize
         l = s.split()
-        self.assertEquals(len(l), chunksize)
+        self.assertEqual(len(l), chunksize)
         expected = _('a')
         for item in l:
-            self.assertEquals(item, expected)
+            self.assertEqual(item, expected)
         del l
         l = s.split(_('a'))
-        self.assertEquals(len(l), chunksize + 1)
+        self.assertEqual(len(l), chunksize + 1)
         expected = _(' ') * chunksize
         for item in filter(None, l):
-            self.assertEquals(item, expected)
+            self.assertEqual(item, expected)
 
     # Allocates a string of twice size (and briefly two) and a list of
     # size.  Because of internal affairs, the s.split() call produces a
@@ -352,12 +352,12 @@
         _ = self.from_latin1
         s = _(' a') * size + _(' ')
         l = s.split()
-        self.assertEquals(len(l), size)
-        self.assertEquals(set(l), set([_('a')]))
+        self.assertEqual(len(l), size)
+        self.assertEqual(set(l), set([_('a')]))
         del l
         l = s.split(_('a'))
-        self.assertEquals(len(l), size + 1)
-        self.assertEquals(set(l), set([_(' ')]))
+        self.assertEqual(len(l), size + 1)
+        self.assertEqual(set(l), set([_(' ')]))
 
     @bigmemtest(minsize=_2G, memuse=2.1)
     def test_splitlines(self, size):
@@ -368,10 +368,10 @@
         SUBSTR = _(' ') * chunksize + _('\n') + _(' ') * chunksize + _('\r\n')
         s = SUBSTR * chunksize
         l = s.splitlines()
-        self.assertEquals(len(l), chunksize * 2)
+        self.assertEqual(len(l), chunksize * 2)
         expected = _(' ') * chunksize
         for item in l:
-            self.assertEquals(item, expected)
+            self.assertEqual(item, expected)
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_startswith(self, size):
@@ -387,12 +387,12 @@
         _ = self.from_latin1
         SUBSTR = _('   abc def ghi   ')
         s = SUBSTR.rjust(size)
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.strip(), SUBSTR.strip())
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.strip(), SUBSTR.strip())
         del s
         s = SUBSTR.ljust(size)
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.strip(), SUBSTR.strip())
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.strip(), SUBSTR.strip())
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_swapcase(self, size):
@@ -402,9 +402,9 @@
         repeats = size // sublen + 2
         s = SUBSTR * repeats
         s = s.swapcase()
-        self.assertEquals(len(s), sublen * repeats)
-        self.assertEquals(s[:sublen * 3], SUBSTR.swapcase() * 3)
-        self.assertEquals(s[-sublen * 3:], SUBSTR.swapcase() * 3)
+        self.assertEqual(len(s), sublen * repeats)
+        self.assertEqual(s[:sublen * 3], SUBSTR.swapcase() * 3)
+        self.assertEqual(s[-sublen * 3:], SUBSTR.swapcase() * 3)
 
     @bigmemtest(minsize=_2G, memuse=2)
     def test_title(self, size):
@@ -431,20 +431,20 @@
         repeats = size // sublen + 2
         s = SUBSTR * repeats
         s = s.translate(trans)
-        self.assertEquals(len(s), repeats * sublen)
-        self.assertEquals(s[:sublen], SUBSTR.translate(trans))
-        self.assertEquals(s[-sublen:], SUBSTR.translate(trans))
-        self.assertEquals(s.count(_('.')), 0)
-        self.assertEquals(s.count(_('!')), repeats * 2)
-        self.assertEquals(s.count(_('z')), repeats * 3)
+        self.assertEqual(len(s), repeats * sublen)
+        self.assertEqual(s[:sublen], SUBSTR.translate(trans))
+        self.assertEqual(s[-sublen:], SUBSTR.translate(trans))
+        self.assertEqual(s.count(_('.')), 0)
+        self.assertEqual(s.count(_('!')), repeats * 2)
+        self.assertEqual(s.count(_('z')), repeats * 3)
 
     @bigmemtest(minsize=_2G + 5, memuse=2)
     def test_upper(self, size):
         _ = self.from_latin1
         s = _('a') * size
         s = s.upper()
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.count(_('A')), size)
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.count(_('A')), size)
 
     @bigmemtest(minsize=_2G + 20, memuse=1)
     def test_zfill(self, size):
@@ -453,8 +453,8 @@
         s = SUBSTR.zfill(size)
         self.assertTrue(s.endswith(_('0') + SUBSTR[1:]))
         self.assertTrue(s.startswith(_('-0')))
-        self.assertEquals(len(s), size)
-        self.assertEquals(s.count(_('0')), size - len(SUBSTR))
+        self.assertEqual(len(s), size)
+        self.assertEqual(s.count(_('0')), size - len(SUBSTR))
 
     # This test is meaningful even with size < 2G, as long as the
     # doubled string is > 2G (but it tests more if both are > 2G :)
@@ -462,10 +462,10 @@
     def test_concat(self, size):
         _ = self.from_latin1
         s = _('.') * size
-        self.assertEquals(len(s), size)
+        self.assertEqual(len(s), size)
         s = s + s
-        self.assertEquals(len(s), size * 2)
-        self.assertEquals(s.count(_('.')), size * 2)
+        self.assertEqual(len(s), size * 2)
+        self.assertEqual(s.count(_('.')), size * 2)
 
     # This test is meaningful even with size < 2G, as long as the
     # repeated string is > 2G (but it tests more if both are > 2G :)
@@ -473,10 +473,10 @@
     def test_repeat(self, size):
         _ = self.from_latin1
         s = _('.') * size
-        self.assertEquals(len(s), size)
+        self.assertEqual(len(s), size)
         s = s * 2
-        self.assertEquals(len(s), size * 2)
-        self.assertEquals(s.count(_('.')), size * 2)
+        self.assertEqual(len(s), size * 2)
+        self.assertEqual(s.count(_('.')), size * 2)
 
     @bigmemtest(minsize=_2G + 20, memuse=2)
     def test_slice_and_getitem(self, size):
@@ -487,26 +487,26 @@
         stepsize = len(s) // 100
         stepsize = stepsize - (stepsize % sublen)
         for i in range(0, len(s) - stepsize, stepsize):
-            self.assertEquals(s[i], SUBSTR[0])
-            self.assertEquals(s[i:i + sublen], SUBSTR)
-            self.assertEquals(s[i:i + sublen:2], SUBSTR[::2])
+            self.assertEqual(s[i], SUBSTR[0])
+            self.assertEqual(s[i:i + sublen], SUBSTR)
+            self.assertEqual(s[i:i + sublen:2], SUBSTR[::2])
             if i > 0:
-                self.assertEquals(s[i + sublen - 1:i - 1:-3],
-                                  SUBSTR[sublen::-3])
+                self.assertEqual(s[i + sublen - 1:i - 1:-3],
+                                 SUBSTR[sublen::-3])
         # Make sure we do some slicing and indexing near the end of the
         # string, too.
-        self.assertEquals(s[len(s) - 1], SUBSTR[-1])
-        self.assertEquals(s[-1], SUBSTR[-1])
-        self.assertEquals(s[len(s) - 10], SUBSTR[0])
-        self.assertEquals(s[-sublen], SUBSTR[0])
-        self.assertEquals(s[len(s):], _(''))
-        self.assertEquals(s[len(s) - 1:], SUBSTR[-1:])
-        self.assertEquals(s[-1:], SUBSTR[-1:])
-        self.assertEquals(s[len(s) - sublen:], SUBSTR)
-        self.assertEquals(s[-sublen:], SUBSTR)
-        self.assertEquals(len(s[:]), len(s))
-        self.assertEquals(len(s[:len(s) - 5]), len(s) - 5)
-        self.assertEquals(len(s[5:-5]), len(s) - 10)
+        self.assertEqual(s[len(s) - 1], SUBSTR[-1])
+        self.assertEqual(s[-1], SUBSTR[-1])
+        self.assertEqual(s[len(s) - 10], SUBSTR[0])
+        self.assertEqual(s[-sublen], SUBSTR[0])
+        self.assertEqual(s[len(s):], _(''))
+        self.assertEqual(s[len(s) - 1:], SUBSTR[-1:])
+        self.assertEqual(s[-1:], SUBSTR[-1:])
+        self.assertEqual(s[len(s) - sublen:], SUBSTR)
+        self.assertEqual(s[-sublen:], SUBSTR)
+        self.assertEqual(len(s[:]), len(s))
+        self.assertEqual(len(s[:len(s) - 5]), len(s) - 5)
+        self.assertEqual(len(s[5:-5]), len(s) - 10)
 
         self.assertRaises(IndexError, operator.getitem, s, len(s))
         self.assertRaises(IndexError, operator.getitem, s, len(s) + 1)
@@ -564,8 +564,11 @@
         if expectedsize is None:
             expectedsize = size
 
-        s = c * size
-        self.assertEquals(len(s.encode(enc)), expectedsize)
+        try:
+            s = c * size
+            self.assertEqual(len(s.encode(enc)), expectedsize)
+        finally:
+            s = None
 
     def setUp(self):
         # HACK: adjust memory use of tests inherited from BaseStrTest
@@ -586,7 +589,8 @@
         for name, memuse in self._adjusted.items():
             getattr(type(self), name).memuse = memuse
 
-    @bigmemtest(minsize=_2G + 2, memuse=character_size + 1)
+    # the utf8 encoder preallocates big time (4x the number of characters)
+    @bigmemtest(minsize=_2G + 2, memuse=character_size + 4)
     def test_encode(self, size):
         return self.basic_encode_test(size, 'utf-8')
 
@@ -632,7 +636,7 @@
         self.assertEqual(s, sf)
         del sf
         sf = '..%s..' % (s,)
-        self.assertEquals(len(sf), len(s) + 4)
+        self.assertEqual(len(sf), len(s) + 4)
         self.assertTrue(sf.startswith('..-'))
         self.assertTrue(sf.endswith('-..'))
         del s, sf
@@ -642,18 +646,18 @@
         s = ''.join([edge, '%s', edge])
         del edge
         s = s % '...'
-        self.assertEquals(len(s), size * 2 + 3)
-        self.assertEquals(s.count('.'), 3)
-        self.assertEquals(s.count('-'), size * 2)
+        self.assertEqual(len(s), size * 2 + 3)
+        self.assertEqual(s.count('.'), 3)
+        self.assertEqual(s.count('-'), size * 2)
 
     @bigmemtest(minsize=_2G + 10, memuse=character_size * 2)
     def test_repr_small(self, size):
         s = '-' * size
         s = repr(s)
-        self.assertEquals(len(s), size + 2)
-        self.assertEquals(s[0], "'")
-        self.assertEquals(s[-1], "'")
-        self.assertEquals(s.count('-'), size)
+        self.assertEqual(len(s), size + 2)
+        self.assertEqual(s[0], "'")
+        self.assertEqual(s[-1], "'")
+        self.assertEqual(s.count('-'), size)
         del s
         # repr() will create a string four times as large as this 'binary
         # string', but we don't want to allocate much more than twice
@@ -661,21 +665,21 @@
         size = size // 5 * 2
         s = '\x00' * size
         s = repr(s)
-        self.assertEquals(len(s), size * 4 + 2)
-        self.assertEquals(s[0], "'")
-        self.assertEquals(s[-1], "'")
-        self.assertEquals(s.count('\\'), size)
-        self.assertEquals(s.count('0'), size * 2)
+        self.assertEqual(len(s), size * 4 + 2)
+        self.assertEqual(s[0], "'")
+        self.assertEqual(s[-1], "'")
+        self.assertEqual(s.count('\\'), size)
+        self.assertEqual(s.count('0'), size * 2)
 
     @bigmemtest(minsize=_2G + 10, memuse=character_size * 5)
     def test_repr_large(self, size):
         s = '\x00' * size
         s = repr(s)
-        self.assertEquals(len(s), size * 4 + 2)
-        self.assertEquals(s[0], "'")
-        self.assertEquals(s[-1], "'")
-        self.assertEquals(s.count('\\'), size)
-        self.assertEquals(s.count('0'), size * 2)
+        self.assertEqual(len(s), size * 4 + 2)
+        self.assertEqual(s[0], "'")
+        self.assertEqual(s[-1], "'")
+        self.assertEqual(s.count('\\'), size)
+        self.assertEqual(s.count('0'), size * 2)
 
     @bigmemtest(minsize=2**32 / 5, memuse=character_size * 7)
     def test_unicode_repr(self, size):
@@ -703,23 +707,23 @@
 class BytesTest(unittest.TestCase, BaseStrTest):
 
     def from_latin1(self, s):
-        return s.encode("latin1")
+        return s.encode("latin-1")
 
     @bigmemtest(minsize=_2G + 2, memuse=1 + character_size)
     def test_decode(self, size):
         s = self.from_latin1('.') * size
-        self.assertEquals(len(s.decode('utf-8')), size)
+        self.assertEqual(len(s.decode('utf-8')), size)
 
 
 class BytearrayTest(unittest.TestCase, BaseStrTest):
 
     def from_latin1(self, s):
-        return bytearray(s.encode("latin1"))
+        return bytearray(s.encode("latin-1"))
 
     @bigmemtest(minsize=_2G + 2, memuse=1 + character_size)
     def test_decode(self, size):
         s = self.from_latin1('.') * size
-        self.assertEquals(len(s.decode('utf-8')), size)
+        self.assertEqual(len(s.decode('utf-8')), size)
 
     test_hash = None
     test_split_large = None
@@ -754,9 +758,9 @@
     # skipped, in verbose mode.)
     def basic_concat_test(self, size):
         t = ((),) * size
-        self.assertEquals(len(t), size)
+        self.assertEqual(len(t), size)
         t = t + t
-        self.assertEquals(len(t), size * 2)
+        self.assertEqual(len(t), size * 2)
 
     @bigmemtest(minsize=_2G // 2 + 2, memuse=24)
     def test_concat_small(self, size):
@@ -769,7 +773,7 @@
     @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5)
     def test_contains(self, size):
         t = (1, 2, 3, 4, 5) * size
-        self.assertEquals(len(t), size * 5)
+        self.assertEqual(len(t), size * 5)
         self.assertIn(5, t)
         self.assertNotIn((1, 2, 3, 4, 5), t)
         self.assertNotIn(0, t)
@@ -785,27 +789,27 @@
     @bigmemtest(minsize=_2G + 10, memuse=8)
     def test_index_and_slice(self, size):
         t = (None,) * size
-        self.assertEquals(len(t), size)
-        self.assertEquals(t[-1], None)
-        self.assertEquals(t[5], None)
-        self.assertEquals(t[size - 1], None)
+        self.assertEqual(len(t), size)
+        self.assertEqual(t[-1], None)
+        self.assertEqual(t[5], None)
+        self.assertEqual(t[size - 1], None)
         self.assertRaises(IndexError, operator.getitem, t, size)
-        self.assertEquals(t[:5], (None,) * 5)
-        self.assertEquals(t[-5:], (None,) * 5)
-        self.assertEquals(t[20:25], (None,) * 5)
-        self.assertEquals(t[-25:-20], (None,) * 5)
-        self.assertEquals(t[size - 5:], (None,) * 5)
-        self.assertEquals(t[size - 5:size], (None,) * 5)
-        self.assertEquals(t[size - 6:size - 2], (None,) * 4)
-        self.assertEquals(t[size:size], ())
-        self.assertEquals(t[size:size+5], ())
+        self.assertEqual(t[:5], (None,) * 5)
+        self.assertEqual(t[-5:], (None,) * 5)
+        self.assertEqual(t[20:25], (None,) * 5)
+        self.assertEqual(t[-25:-20], (None,) * 5)
+        self.assertEqual(t[size - 5:], (None,) * 5)
+        self.assertEqual(t[size - 5:size], (None,) * 5)
+        self.assertEqual(t[size - 6:size - 2], (None,) * 4)
+        self.assertEqual(t[size:size], ())
+        self.assertEqual(t[size:size+5], ())
 
     # Like test_concat, split in two.
     def basic_test_repeat(self, size):
         t = ('',) * size
-        self.assertEquals(len(t), size)
+        self.assertEqual(len(t), size)
         t = t * 2
-        self.assertEquals(len(t), size * 2)
+        self.assertEqual(len(t), size * 2)
 
     @bigmemtest(minsize=_2G // 2 + 2, memuse=24)
     def test_repeat_small(self, size):
@@ -829,9 +833,9 @@
         else:
             count = 0
             for item in t:
-                self.assertEquals(item, count)
+                self.assertEqual(item, count)
                 count += 1
-            self.assertEquals(count, size)
+            self.assertEqual(count, size)
 
     @precisionbigmemtest(size=_1G - 25, memuse=9)
     def test_from_almost_2G_generator(self, size):
@@ -840,9 +844,9 @@
             t = tuple(range(size))
             count = 0
             for item in t:
-                self.assertEquals(item, count)
+                self.assertEqual(item, count)
                 count += 1
-            self.assertEquals(count, size)
+            self.assertEqual(count, size)
         except MemoryError:
             pass # acceptable, expected on 32-bit
 
@@ -851,10 +855,10 @@
         t = (0,) * size
         s = repr(t)
         # The repr of a tuple of 0's is exactly three times the tuple length.
-        self.assertEquals(len(s), size * 3)
-        self.assertEquals(s[:5], '(0, 0')
-        self.assertEquals(s[-5:], '0, 0)')
-        self.assertEquals(s.count('0'), size)
+        self.assertEqual(len(s), size * 3)
+        self.assertEqual(s[:5], '(0, 0')
+        self.assertEqual(s[-5:], '0, 0)')
+        self.assertEqual(s.count('0'), size)
 
     @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3 * character_size)
     def test_repr_small(self, size):
@@ -890,9 +894,9 @@
     # skipped, in verbose mode.)
     def basic_test_concat(self, size):
         l = [[]] * size
-        self.assertEquals(len(l), size)
+        self.assertEqual(len(l), size)
         l = l + l
-        self.assertEquals(len(l), size * 2)
+        self.assertEqual(len(l), size * 2)
 
     @bigmemtest(minsize=_2G // 2 + 2, memuse=24)
     def test_concat_small(self, size):
@@ -905,7 +909,7 @@
     def basic_test_inplace_concat(self, size):
         l = [sys.stdout] * size
         l += l
-        self.assertEquals(len(l), size * 2)
+        self.assertEqual(len(l), size * 2)
         self.assertTrue(l[0] is l[-1])
         self.assertTrue(l[size - 1] is l[size + 1])
 
@@ -920,7 +924,7 @@
     @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5)
     def test_contains(self, size):
         l = [1, 2, 3, 4, 5] * size
-        self.assertEquals(len(l), size * 5)
+        self.assertEqual(len(l), size * 5)
         self.assertIn(5, l)
         self.assertNotIn([1, 2, 3, 4, 5], l)
         self.assertNotIn(0, l)
@@ -933,66 +937,66 @@
     @bigmemtest(minsize=_2G + 10, memuse=8)
     def test_index_and_slice(self, size):
         l = [None] * size
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[-1], None)
-        self.assertEquals(l[5], None)
-        self.assertEquals(l[size - 1], None)
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[-1], None)
+        self.assertEqual(l[5], None)
+        self.assertEqual(l[size - 1], None)
         self.assertRaises(IndexError, operator.getitem, l, size)
-        self.assertEquals(l[:5], [None] * 5)
-        self.assertEquals(l[-5:], [None] * 5)
-        self.assertEquals(l[20:25], [None] * 5)
-        self.assertEquals(l[-25:-20], [None] * 5)
-        self.assertEquals(l[size - 5:], [None] * 5)
-        self.assertEquals(l[size - 5:size], [None] * 5)
-        self.assertEquals(l[size - 6:size - 2], [None] * 4)
-        self.assertEquals(l[size:size], [])
-        self.assertEquals(l[size:size+5], [])
+        self.assertEqual(l[:5], [None] * 5)
+        self.assertEqual(l[-5:], [None] * 5)
+        self.assertEqual(l[20:25], [None] * 5)
+        self.assertEqual(l[-25:-20], [None] * 5)
+        self.assertEqual(l[size - 5:], [None] * 5)
+        self.assertEqual(l[size - 5:size], [None] * 5)
+        self.assertEqual(l[size - 6:size - 2], [None] * 4)
+        self.assertEqual(l[size:size], [])
+        self.assertEqual(l[size:size+5], [])
 
         l[size - 2] = 5
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[-3:], [None, 5, None])
-        self.assertEquals(l.count(5), 1)
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[-3:], [None, 5, None])
+        self.assertEqual(l.count(5), 1)
         self.assertRaises(IndexError, operator.setitem, l, size, 6)
-        self.assertEquals(len(l), size)
+        self.assertEqual(len(l), size)
 
         l[size - 7:] = [1, 2, 3, 4, 5]
         size -= 2
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[-7:], [None, None, 1, 2, 3, 4, 5])
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[-7:], [None, None, 1, 2, 3, 4, 5])
 
         l[:7] = [1, 2, 3, 4, 5]
         size -= 2
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[:7], [1, 2, 3, 4, 5, None, None])
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[:7], [1, 2, 3, 4, 5, None, None])
 
         del l[size - 1]
         size -= 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[-1], 4)
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[-1], 4)
 
         del l[-2:]
         size -= 2
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[-1], 2)
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[-1], 2)
 
         del l[0]
         size -= 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[0], 2)
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[0], 2)
 
         del l[:2]
         size -= 2
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[0], 4)
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[0], 4)
 
     # Like test_concat, split in two.
     def basic_test_repeat(self, size):
         l = [] * size
         self.assertFalse(l)
         l = [''] * size
-        self.assertEquals(len(l), size)
+        self.assertEqual(len(l), size)
         l = l * 2
-        self.assertEquals(len(l), size * 2)
+        self.assertEqual(len(l), size * 2)
 
     @bigmemtest(minsize=_2G // 2 + 2, memuse=24)
     def test_repeat_small(self, size):
@@ -1005,13 +1009,13 @@
     def basic_test_inplace_repeat(self, size):
         l = ['']
         l *= size
-        self.assertEquals(len(l), size)
+        self.assertEqual(len(l), size)
         self.assertTrue(l[0] is l[-1])
         del l
 
         l = [''] * size
         l *= 2
-        self.assertEquals(len(l), size * 2)
+        self.assertEqual(len(l), size * 2)
         self.assertTrue(l[size - 1] is l[-1])
 
     @bigmemtest(minsize=_2G // 2 + 2, memuse=16)
@@ -1026,10 +1030,10 @@
         l = [0] * size
         s = repr(l)
         # The repr of a list of 0's is exactly three times the list length.
-        self.assertEquals(len(s), size * 3)
-        self.assertEquals(s[:5], '[0, 0')
-        self.assertEquals(s[-5:], '0, 0]')
-        self.assertEquals(s.count('0'), size)
+        self.assertEqual(len(s), size * 3)
+        self.assertEqual(s[:5], '[0, 0')
+        self.assertEqual(s[-5:], '0, 0]')
+        self.assertEqual(s.count('0'), size)
 
     @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3 * character_size)
     def test_repr_small(self, size):
@@ -1045,20 +1049,20 @@
     def test_append(self, size):
         l = [object()] * size
         l.append(object())
-        self.assertEquals(len(l), size+1)
+        self.assertEqual(len(l), size+1)
         self.assertTrue(l[-3] is l[-2])
         self.assertFalse(l[-2] is l[-1])
 
     @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5)
     def test_count(self, size):
         l = [1, 2, 3, 4, 5] * size
-        self.assertEquals(l.count(1), size)
-        self.assertEquals(l.count("1"), 0)
+        self.assertEqual(l.count(1), size)
+        self.assertEqual(l.count("1"), 0)
 
     def basic_test_extend(self, size):
         l = [object] * size
         l.extend(l)
-        self.assertEquals(len(l), size * 2)
+        self.assertEqual(len(l), size * 2)
         self.assertTrue(l[0] is l[-1])
         self.assertTrue(l[size - 1] is l[size + 1])
 
@@ -1074,9 +1078,9 @@
     def test_index(self, size):
         l = [1, 2, 3, 4, 5] * size
         size *= 5
-        self.assertEquals(l.index(1), 0)
-        self.assertEquals(l.index(5, size - 5), size - 1)
-        self.assertEquals(l.index(5, size - 5, size), size - 1)
+        self.assertEqual(l.index(1), 0)
+        self.assertEqual(l.index(5, size - 5), size - 1)
+        self.assertEqual(l.index(5, size - 5, size), size - 1)
         self.assertRaises(ValueError, l.index, 1, size - 4, size)
         self.assertRaises(ValueError, l.index, 6)
 
@@ -1086,80 +1090,80 @@
         l = [1.0] * size
         l.insert(size - 1, "A")
         size += 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[-3:], [1.0, "A", 1.0])
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[-3:], [1.0, "A", 1.0])
 
         l.insert(size + 1, "B")
         size += 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[-3:], ["A", 1.0, "B"])
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[-3:], ["A", 1.0, "B"])
 
         l.insert(1, "C")
         size += 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[:3], [1.0, "C", 1.0])
-        self.assertEquals(l[size - 3:], ["A", 1.0, "B"])
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[:3], [1.0, "C", 1.0])
+        self.assertEqual(l[size - 3:], ["A", 1.0, "B"])
 
     @bigmemtest(minsize=_2G // 5 + 4, memuse=8 * 5)
     def test_pop(self, size):
         l = ["a", "b", "c", "d", "e"] * size
         size *= 5
-        self.assertEquals(len(l), size)
+        self.assertEqual(len(l), size)
 
         item = l.pop()
         size -= 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(item, "e")
-        self.assertEquals(l[-2:], ["c", "d"])
+        self.assertEqual(len(l), size)
+        self.assertEqual(item, "e")
+        self.assertEqual(l[-2:], ["c", "d"])
 
         item = l.pop(0)
         size -= 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(item, "a")
-        self.assertEquals(l[:2], ["b", "c"])
+        self.assertEqual(len(l), size)
+        self.assertEqual(item, "a")
+        self.assertEqual(l[:2], ["b", "c"])
 
         item = l.pop(size - 2)
         size -= 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(item, "c")
-        self.assertEquals(l[-2:], ["b", "d"])
+        self.assertEqual(len(l), size)
+        self.assertEqual(item, "c")
+        self.assertEqual(l[-2:], ["b", "d"])
 
     @bigmemtest(minsize=_2G + 10, memuse=8)
     def test_remove(self, size):
         l = [10] * size
-        self.assertEquals(len(l), size)
+        self.assertEqual(len(l), size)
 
         l.remove(10)
         size -= 1
-        self.assertEquals(len(l), size)
+        self.assertEqual(len(l), size)
 
         # Because of the earlier l.remove(), this append doesn't trigger
         # a resize.
         l.append(5)
         size += 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[-2:], [10, 5])
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[-2:], [10, 5])
         l.remove(5)
         size -= 1
-        self.assertEquals(len(l), size)
-        self.assertEquals(l[-2:], [10, 10])
+        self.assertEqual(len(l), size)
+        self.assertEqual(l[-2:], [10, 10])
 
     @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5)
     def test_reverse(self, size):
         l = [1, 2, 3, 4, 5] * size
         l.reverse()
-        self.assertEquals(len(l), size * 5)
-        self.assertEquals(l[-5:], [5, 4, 3, 2, 1])
-        self.assertEquals(l[:5], [5, 4, 3, 2, 1])
+        self.assertEqual(len(l), size * 5)
+        self.assertEqual(l[-5:], [5, 4, 3, 2, 1])
+        self.assertEqual(l[:5], [5, 4, 3, 2, 1])
 
     @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5)
     def test_sort(self, size):
         l = [1, 2, 3, 4, 5] * size
         l.sort()
-        self.assertEquals(len(l), size * 5)
-        self.assertEquals(l.count(1), size)
-        self.assertEquals(l[:10], [1] * 10)
-        self.assertEquals(l[-10:], [5] * 10)
+        self.assertEqual(len(l), size * 5)
+        self.assertEqual(l.count(1), size)
+        self.assertEqual(l[:10], [1] * 10)
+        self.assertEqual(l[-10:], [5] * 10)
 
 def test_main():
     support.run_unittest(StrTest, BytesTest, BytearrayTest,

Modified: python/branches/pep-3151/Lib/test/test_bool.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_bool.py	(original)
+++ python/branches/pep-3151/Lib/test/test_bool.py	Sat Feb 26 08:16:32 2011
@@ -174,8 +174,8 @@
         self.assertIs(hasattr([], "wobble"), False)
 
     def test_callable(self):
-        self.assertIs(hasattr(len, '__call__'), True)
-        self.assertIs(hasattr(1, '__call__'), False)
+        self.assertIs(callable(len), True)
+        self.assertIs(callable(1), False)
 
     def test_isinstance(self):
         self.assertIs(isinstance(True, bool), True)

Modified: python/branches/pep-3151/Lib/test/test_builtin.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_builtin.py	(original)
+++ python/branches/pep-3151/Lib/test/test_builtin.py	Sat Feb 26 08:16:32 2011
@@ -6,10 +6,11 @@
 import warnings
 import collections
 import io
+import ast
 import types
 import builtins
 import random
-from test.support import fcmp, TESTFN, unlink,  run_unittest, check_warnings
+from test.support import TESTFN, unlink,  run_unittest, check_warnings
 from operator import neg
 
 
@@ -207,22 +208,39 @@
         self.assertTrue(isinstance(x, int))
         self.assertEqual(-x, sys.maxsize+1)
 
-    # XXX(nnorwitz): This test case for callable should probably be removed.
     def test_callable(self):
-        self.assertTrue(hasattr(len, '__call__'))
+        self.assertTrue(callable(len))
+        self.assertFalse(callable("a"))
+        self.assertTrue(callable(callable))
+        self.assertTrue(callable(lambda x, y: x + y))
+        self.assertFalse(callable(__builtins__))
         def f(): pass
-        self.assertTrue(hasattr(f, '__call__'))
-        class C:
+        self.assertTrue(callable(f))
+
+        class C1:
             def meth(self): pass
-        self.assertTrue(hasattr(C, '__call__'))
-        x = C()
-        self.assertTrue(hasattr(x.meth, '__call__'))
-        self.assertTrue(not hasattr(x, '__call__'))
-        class D(C):
+        self.assertTrue(callable(C1))
+        c = C1()
+        self.assertTrue(callable(c.meth))
+        self.assertFalse(callable(c))
+
+        # __call__ is looked up on the class, not the instance
+        c.__call__ = None
+        self.assertFalse(callable(c))
+        c.__call__ = lambda self: 0
+        self.assertFalse(callable(c))
+        del c.__call__
+        self.assertFalse(callable(c))
+
+        class C2(object):
             def __call__(self): pass
-        y = D()
-        self.assertTrue(hasattr(y, '__call__'))
-        y()
+        c2 = C2()
+        self.assertTrue(callable(c2))
+        c2.__call__ = None
+        self.assertTrue(callable(c2))
+        class C3(C2): pass
+        c3 = C3()
+        self.assertTrue(callable(c3))
 
     def test_chr(self):
         self.assertEqual(chr(32), ' ')
@@ -268,6 +286,34 @@
         self.assertRaises(TypeError, compile, chr(0), 'f', 'exec')
         self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')
 
+        # test the optimize argument
+
+        codestr = '''def f():
+        """doc"""
+        try:
+            assert False
+        except AssertionError:
+            return (True, f.__doc__)
+        else:
+            return (False, f.__doc__)
+        '''
+        def f(): """doc"""
+        values = [(-1, __debug__, f.__doc__),
+                  (0, True, 'doc'),
+                  (1, False, 'doc'),
+                  (2, False, None)]
+        for optval, debugval, docstring in values:
+            # test both direct compilation and compilation via AST
+            codeobjs = []
+            codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval))
+            tree = ast.parse(codestr)
+            codeobjs.append(compile(tree, "<test>", "exec", optimize=optval))
+            for code in codeobjs:
+                ns = {}
+                exec(code, ns)
+                rv = ns['f']()
+                self.assertEqual(rv, (debugval, docstring))
+
     def test_delattr(self):
         sys.spam = 1
         delattr(sys, 'spam')
@@ -348,10 +394,13 @@
 
         self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))
 
-        self.assertTrue(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
-        self.assertTrue(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
-        self.assertTrue(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
-        self.assertTrue(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
+        for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)),
+                                        (-3.25, 1.0, (-4.0, 0.75)),
+                                        (3.25, -1.0, (-4.0, -0.75)),
+                                        (-3.25, -1.0, (3.0, -0.25))]:
+            result = divmod(num, denom)
+            self.assertAlmostEqual(result[0], exp_result[0])
+            self.assertAlmostEqual(result[1], exp_result[1])
 
         self.assertRaises(TypeError, divmod)
 
@@ -542,11 +591,11 @@
         class X:
             def __hash__(self):
                 return 2**100
-        self.assertEquals(type(hash(X())), int)
+        self.assertEqual(type(hash(X())), int)
         class Z(int):
             def __hash__(self):
                 return self
-        self.assertEquals(hash(Z(42)), hash(42))
+        self.assertEqual(hash(Z(42)), hash(42))
 
     def test_hex(self):
         self.assertEqual(hex(16), '0x10')
@@ -777,7 +826,7 @@
         self.assertEqual(next(it), 1)
         self.assertRaises(StopIteration, next, it)
         self.assertRaises(StopIteration, next, it)
-        self.assertEquals(next(it, 42), 42)
+        self.assertEqual(next(it, 42), 42)
 
         class Iter(object):
             def __iter__(self):
@@ -786,7 +835,7 @@
                 raise StopIteration
 
         it = iter(Iter())
-        self.assertEquals(next(it, 42), 42)
+        self.assertEqual(next(it, 42), 42)
         self.assertRaises(StopIteration, next, it)
 
         def gen():
@@ -794,9 +843,9 @@
             return
 
         it = gen()
-        self.assertEquals(next(it), 1)
+        self.assertEqual(next(it), 1)
         self.assertRaises(StopIteration, next, it)
-        self.assertEquals(next(it, 42), 42)
+        self.assertEqual(next(it, 42), 42)
 
     def test_oct(self):
         self.assertEqual(oct(100), '0o144')
@@ -906,182 +955,6 @@
 
         self.assertRaises(TypeError, pow)
 
-    def test_range(self):
-        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])
-
-        #issue 6334: the internal stored range length was being
-        #computed incorrectly in some cases involving large arguments.
-        x = range(10**20, 10**20+10, 3)
-        self.assertEqual(len(x), 4)
-        self.assertEqual(len(list(x)), 4)
-
-        x = range(10**20+10, 10**20, 3)
-        self.assertEqual(len(x), 0)
-        self.assertEqual(len(list(x)), 0)
-
-        x = range(10**20, 10**20+10, -3)
-        self.assertEqual(len(x), 0)
-        self.assertEqual(len(list(x)), 0)
-
-        x = range(10**20+10, 10**20, -3)
-        self.assertEqual(len(x), 4)
-        self.assertEqual(len(list(x)), 4)
-
-        # Now test range() with longs
-        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.maxsize)
-        b = int(100 * sys.maxsize)
-        c = int(50 * sys.maxsize)
-
-        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(range(a, b, c))
-        self.assertIn(a, seq)
-        self.assertNotIn(b, seq)
-        self.assertEqual(len(seq), 2)
-
-        seq = list(range(b, a, -c))
-        self.assertIn(b, seq)
-        self.assertNotIn(a, seq)
-        self.assertEqual(len(seq), 2)
-
-        seq = list(range(-a, -b, -c))
-        self.assertIn(-a, seq)
-        self.assertNotIn(-b, seq)
-        self.assertEqual(len(seq), 2)
-
-        self.assertRaises(TypeError, range)
-        self.assertRaises(TypeError, range, 1, 2, 3, 4)
-        self.assertRaises(ValueError, range, 1, 2, 0)
-        self.assertRaises(ValueError, range, a, a + 1, int(0))
-
-        """ XXX(nnorwitz):
-        class badzero(int):
-            def __eq__(self, other):
-                raise RuntimeError
-            __ne__ = __lt__ = __gt__ = __le__ = __ge__ = __eq__
-
-        # XXX This won't (but should!) raise RuntimeError if a is an int...
-        self.assertRaises(RuntimeError, range, a, a + 1, badzero(1))
-        """
-
-        # Reject floats.
-        self.assertRaises(TypeError, range, 1., 1., 1.)
-        self.assertRaises(TypeError, range, 1e100, 1e101, 1e101)
-
-        self.assertRaises(TypeError, range, 0, "spam")
-        self.assertRaises(TypeError, range, 0, 42, "spam")
-
-        #NEAL self.assertRaises(OverflowError, range, -sys.maxsize, sys.maxsize)
-        #NEAL self.assertRaises(OverflowError, range, 0, 2*sys.maxsize)
-
-        self.assertRaises(OverflowError, len, range(0, sys.maxsize**10))
-
-        bignum = 2*sys.maxsize
-        smallnum = 42
-
-        # User-defined class with an __index__ method
-        class I:
-            def __init__(self, n):
-                self.n = int(n)
-            def __index__(self):
-                return self.n
-        self.assertEqual(list(range(I(bignum), I(bignum + 1))), [bignum])
-        self.assertEqual(list(range(I(smallnum), I(smallnum + 1))), [smallnum])
-
-        # User-defined class with a failing __index__ method
-        class IX:
-            def __index__(self):
-                raise RuntimeError
-        self.assertRaises(RuntimeError, range, IX())
-
-        # User-defined class with an invalid __index__ method
-        class IN:
-            def __index__(self):
-                return "not a number"
-
-        self.assertRaises(TypeError, range, IN())
-        # Exercise various combinations of bad arguments, to check
-        # refcounting logic
-        self.assertRaises(TypeError, range, 0.0)
-
-        self.assertRaises(TypeError, range, 0, 0.0)
-        self.assertRaises(TypeError, range, 0.0, 0)
-        self.assertRaises(TypeError, range, 0.0, 0.0)
-
-        self.assertRaises(TypeError, range, 0, 0, 1.0)
-        self.assertRaises(TypeError, range, 0, 0.0, 1)
-        self.assertRaises(TypeError, range, 0, 0.0, 1.0)
-        self.assertRaises(TypeError, range, 0.0, 0, 1)
-        self.assertRaises(TypeError, range, 0.0, 0, 1.0)
-        self.assertRaises(TypeError, range, 0.0, 0.0, 1)
-        self.assertRaises(TypeError, range, 0.0, 0.0, 1.0)
-
-        self.assertEqual(range(3).count(-1), 0)
-        self.assertEqual(range(3).count(0), 1)
-        self.assertEqual(range(3).count(1), 1)
-        self.assertEqual(range(3).count(2), 1)
-        self.assertEqual(range(3).count(3), 0)
-
-        self.assertEqual(range(10**20).count(1), 1)
-        self.assertEqual(range(10**20).count(10**20), 0)
-        self.assertEqual(range(3).index(1), 1)
-        self.assertEqual(range(1, 2**100, 2).count(2**87), 0)
-        self.assertEqual(range(1, 2**100, 2).count(2**87+1), 1)
-
-        self.assertEqual(range(1, 10, 3).index(4), 1)
-        self.assertEqual(range(1, -10, -3).index(-5), 2)
-
-        self.assertEqual(range(10**20).index(1), 1)
-        self.assertEqual(range(10**20).index(10**20 - 1), 10**20 - 1)
-
-        self.assertRaises(ValueError, range(1, 2**100, 2).index, 2**87)
-        self.assertEqual(range(1, 2**100, 2).index(2**87+1), 2**86)
-
-        class AlwaysEqual(object):
-            def __eq__(self, other):
-                return True
-        always_equal = AlwaysEqual()
-        self.assertEqual(range(10).count(always_equal), 10)
-        self.assertEqual(range(10).index(always_equal), 0)
-
-    def test_range_index(self):
-        u = range(2)
-        self.assertEqual(u.index(0), 0)
-        self.assertEqual(u.index(1), 1)
-        self.assertRaises(ValueError, u.index, 2)
-
-        u = range(-2, 3)
-        self.assertEqual(u.count(0), 1)
-        self.assertEqual(u.index(0), 2)
-        self.assertRaises(TypeError, u.index)
-
-        class BadExc(Exception):
-            pass
-
-        class BadCmp:
-            def __eq__(self, other):
-                if other == 2:
-                    raise BadExc()
-                return False
-
-        a = range(4)
-        self.assertRaises(BadExc, a.index, BadCmp())
-
-        a = range(-2, 3)
-        self.assertEqual(a.index(0), 2)
-
     def test_input(self):
         self.write_testfile()
         fp = open(TESTFN, 'r')

Modified: python/branches/pep-3151/Lib/test/test_bytes.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_bytes.py	(original)
+++ python/branches/pep-3151/Lib/test/test_bytes.py	Sat Feb 26 08:16:32 2011
@@ -188,24 +188,26 @@
 
     def test_encoding(self):
         sample = "Hello world\n\u1234\u5678\u9abc"
-        for enc in ("utf8", "utf16"):
+        for enc in ("utf-8", "utf-16"):
             b = self.type2test(sample, enc)
             self.assertEqual(b, self.type2test(sample.encode(enc)))
-        self.assertRaises(UnicodeEncodeError, self.type2test, sample, "latin1")
-        b = self.type2test(sample, "latin1", "ignore")
+        self.assertRaises(UnicodeEncodeError, self.type2test, sample, "latin-1")
+        b = self.type2test(sample, "latin-1", "ignore")
         self.assertEqual(b, self.type2test(sample[:-3], "utf-8"))
 
     def test_decode(self):
         sample = "Hello world\n\u1234\u5678\u9abc\def0\def0"
-        for enc in ("utf8", "utf16"):
+        for enc in ("utf-8", "utf-16"):
             b = self.type2test(sample, enc)
             self.assertEqual(b.decode(enc), sample)
         sample = "Hello world\n\x80\x81\xfe\xff"
-        b = self.type2test(sample, "latin1")
-        self.assertRaises(UnicodeDecodeError, b.decode, "utf8")
-        self.assertEqual(b.decode("utf8", "ignore"), "Hello world\n")
-        self.assertEqual(b.decode(errors="ignore", encoding="utf8"),
+        b = self.type2test(sample, "latin-1")
+        self.assertRaises(UnicodeDecodeError, b.decode, "utf-8")
+        self.assertEqual(b.decode("utf-8", "ignore"), "Hello world\n")
+        self.assertEqual(b.decode(errors="ignore", encoding="utf-8"),
                          "Hello world\n")
+        # Default encoding is utf-8
+        self.assertEqual(self.type2test(b'\xe2\x98\x83').decode(), '\u2603')
 
     def test_from_int(self):
         b = self.type2test(0)
@@ -266,11 +268,11 @@
     def test_fromhex(self):
         self.assertRaises(TypeError, self.type2test.fromhex)
         self.assertRaises(TypeError, self.type2test.fromhex, 1)
-        self.assertEquals(self.type2test.fromhex(''), self.type2test())
+        self.assertEqual(self.type2test.fromhex(''), self.type2test())
         b = bytearray([0x1a, 0x2b, 0x30])
-        self.assertEquals(self.type2test.fromhex('1a2B30'), b)
-        self.assertEquals(self.type2test.fromhex('  1A 2B  30   '), b)
-        self.assertEquals(self.type2test.fromhex('0000'), b'\0\0')
+        self.assertEqual(self.type2test.fromhex('1a2B30'), b)
+        self.assertEqual(self.type2test.fromhex('  1A 2B  30   '), b)
+        self.assertEqual(self.type2test.fromhex('0000'), b'\0\0')
         self.assertRaises(TypeError, self.type2test.fromhex, b'1B')
         self.assertRaises(ValueError, self.type2test.fromhex, 'a')
         self.assertRaises(ValueError, self.type2test.fromhex, 'rt')
@@ -497,6 +499,27 @@
                 return None
         self.assertRaises(TypeError, bytes, A())
 
+    # Test PyBytes_FromFormat()
+    def test_from_format(self):
+        test.support.import_module('ctypes')
+        from ctypes import pythonapi, py_object, c_int, c_char_p
+        PyBytes_FromFormat = pythonapi.PyBytes_FromFormat
+        PyBytes_FromFormat.restype = py_object
+
+        self.assertEqual(PyBytes_FromFormat(b'format'),
+                         b'format')
+
+        self.assertEqual(PyBytes_FromFormat(b'%'), b'%')
+        self.assertEqual(PyBytes_FromFormat(b'%%'), b'%')
+        self.assertEqual(PyBytes_FromFormat(b'%%s'), b'%s')
+        self.assertEqual(PyBytes_FromFormat(b'[%%]'), b'[%]')
+        self.assertEqual(PyBytes_FromFormat(b'%%%c', c_int(ord('_'))), b'%_')
+
+        self.assertEqual(PyBytes_FromFormat(b'c:%c', c_int(255)),
+                         b'c:\xff')
+        self.assertEqual(PyBytes_FromFormat(b's:%s', c_char_p(b'cstr')),
+                         b's:cstr')
+
 
 class ByteArrayTest(BaseBytesTest):
     type2test = bytearray
@@ -626,11 +649,11 @@
                     data.reverse()
                     L[start:stop:step] = data
                     b[start:stop:step] = data
-                    self.assertEquals(b, bytearray(L))
+                    self.assertEqual(b, bytearray(L))
 
                     del L[start:stop:step]
                     del b[start:stop:step]
-                    self.assertEquals(b, bytearray(L))
+                    self.assertEqual(b, bytearray(L))
 
     def test_setslice_trap(self):
         # This test verifies that we correctly handle assigning self
@@ -809,25 +832,25 @@
         resize(10)
         orig = b[:]
         self.assertRaises(BufferError, resize, 11)
-        self.assertEquals(b, orig)
+        self.assertEqual(b, orig)
         self.assertRaises(BufferError, resize, 9)
-        self.assertEquals(b, orig)
+        self.assertEqual(b, orig)
         self.assertRaises(BufferError, resize, 0)
-        self.assertEquals(b, orig)
+        self.assertEqual(b, orig)
         # Other operations implying resize
         self.assertRaises(BufferError, b.pop, 0)
-        self.assertEquals(b, orig)
+        self.assertEqual(b, orig)
         self.assertRaises(BufferError, b.remove, b[1])
-        self.assertEquals(b, orig)
+        self.assertEqual(b, orig)
         def delitem():
             del b[1]
         self.assertRaises(BufferError, delitem)
-        self.assertEquals(b, orig)
+        self.assertEqual(b, orig)
         # deleting a non-contiguous slice
         def delslice():
             b[1:-1:2] = b""
         self.assertRaises(BufferError, delslice)
-        self.assertEquals(b, orig)
+        self.assertEqual(b, orig)
 
 
 class AssortedBytesTest(unittest.TestCase):

Modified: python/branches/pep-3151/Lib/test/test_bz2.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_bz2.py	(original)
+++ python/branches/pep-3151/Lib/test/test_bz2.py	Sat Feb 26 08:16:32 2011
@@ -86,7 +86,7 @@
                 if not str:
                     break
                 text += str
-            self.assertEqual(text, text)
+            self.assertEqual(text, self.TEXT)
 
     def testRead100(self):
         # "Test BZ2File.read(100)"

Modified: python/branches/pep-3151/Lib/test/test_calendar.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_calendar.py	(original)
+++ python/branches/pep-3151/Lib/test/test_calendar.py	Sat Feb 26 08:16:32 2011
@@ -262,7 +262,7 @@
             return
         calendar.LocaleHTMLCalendar(locale='').formatmonthname(2010, 10)
         new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
-        self.assertEquals(old_october, new_october)
+        self.assertEqual(old_october, new_october)
 
 
 class MonthCalendarTestCase(unittest.TestCase):
@@ -430,6 +430,26 @@
         with self.assertRaises(calendar.IllegalMonthError):
             calendar.monthrange(2004, 13)
 
+class LeapdaysTestCase(unittest.TestCase):
+    def test_no_range(self):
+        # test when no range i.e. two identical years as args
+        self.assertEqual(calendar.leapdays(2010,2010), 0)
+
+    def test_no_leapdays(self):
+        # test when no leap years in range
+        self.assertEqual(calendar.leapdays(2010,2011), 0)
+
+    def test_no_leapdays_upper_boundary(self):
+        # test no leap years in range, when upper boundary is a leap year
+        self.assertEqual(calendar.leapdays(2010,2012), 0)
+
+    def test_one_leapday_lower_boundary(self):
+        # test when one leap year in range, lower boundary is leap year
+        self.assertEqual(calendar.leapdays(2012,2013), 1)
+
+    def test_several_leapyears_in_range(self):
+        self.assertEqual(calendar.leapdays(1997,2020), 5)
+
 
 def test_main():
     support.run_unittest(
@@ -439,6 +459,7 @@
         SundayTestCase,
         TimegmTestCase,
         MonthRangeTestCase,
+        LeapdaysTestCase,
     )
 
 

Modified: python/branches/pep-3151/Lib/test/test_capi.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_capi.py	(original)
+++ python/branches/pep-3151/Lib/test/test_capi.py	Sat Feb 26 08:16:32 2011
@@ -50,6 +50,8 @@
                          b'Fatal Python error:'
                          b' PyThreadState_Get: no current thread')
 
+    def test_memoryview_from_NULL_pointer(self):
+        self.assertRaises(ValueError, _testcapi.make_memoryview_from_NULL_pointer)
 
 @unittest.skipUnless(threading, 'Threading required for this test.')
 class TestPendingCalls(unittest.TestCase):

Deleted: python/branches/pep-3151/Lib/test/test_cfgparser.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_cfgparser.py	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,1004 +0,0 @@
-import collections
-import configparser
-import io
-import os
-import unittest
-import textwrap
-
-from test import support
-
-class SortedDict(collections.UserDict):
-
-    def items(self):
-        return sorted(self.data.items())
-
-    def keys(self):
-        return sorted(self.data.keys())
-
-    def values(self):
-        return [i[1] for i in self.items()]
-
-    def iteritems(self): return iter(self.items())
-    def iterkeys(self): return iter(self.keys())
-    __iter__ = iterkeys
-    def itervalues(self): return iter(self.values())
-
-
-class CfgParserTestCaseClass(unittest.TestCase):
-    allow_no_value = False
-    delimiters = ('=', ':')
-    comment_prefixes = (';', '#')
-    empty_lines_in_values = True
-    dict_type = configparser._default_dict
-    strict = False
-
-    def newconfig(self, defaults=None):
-        arguments = dict(
-            defaults=defaults,
-            allow_no_value=self.allow_no_value,
-            delimiters=self.delimiters,
-            comment_prefixes=self.comment_prefixes,
-            empty_lines_in_values=self.empty_lines_in_values,
-            dict_type=self.dict_type,
-            strict=self.strict,
-        )
-        return self.config_class(**arguments)
-
-    def fromstring(self, string, defaults=None):
-        cf = self.newconfig(defaults)
-        cf.read_string(string)
-        return cf
-
-class BasicTestCase(CfgParserTestCaseClass):
-
-    def basic_test(self, cf):
-        E = ['Commented Bar',
-             'Foo Bar',
-             'Internationalized Stuff',
-             'Long Line',
-             'Section\\with$weird%characters[\t',
-             'Spaces',
-             'Spacey Bar',
-             'Spacey Bar From The Beginning',
-             'Types',
-             ]
-
-        if self.allow_no_value:
-            E.append('NoValue')
-        E.sort()
-
-        # API access
-        L = cf.sections()
-        L.sort()
-        eq = self.assertEqual
-        eq(L, E)
-
-        # mapping access
-        L = [section for section in cf]
-        L.sort()
-        E.append(configparser.DEFAULTSECT)
-        E.sort()
-        eq(L, E)
-
-        # The use of spaces in the section names serves as a
-        # regression test for SourceForge bug #583248:
-        # http://www.python.org/sf/583248
-
-        # API access
-        eq(cf.get('Foo Bar', 'foo'), 'bar1')
-        eq(cf.get('Spacey Bar', 'foo'), 'bar2')
-        eq(cf.get('Spacey Bar From The Beginning', 'foo'), 'bar3')
-        eq(cf.get('Spacey Bar From The Beginning', 'baz'), 'qwe')
-        eq(cf.get('Commented Bar', 'foo'), 'bar4')
-        eq(cf.get('Commented Bar', 'baz'), 'qwe')
-        eq(cf.get('Spaces', 'key with spaces'), 'value')
-        eq(cf.get('Spaces', 'another with spaces'), 'splat!')
-        eq(cf.getint('Types', 'int'), 42)
-        eq(cf.get('Types', 'int'), "42")
-        self.assertAlmostEqual(cf.getfloat('Types', 'float'), 0.44)
-        eq(cf.get('Types', 'float'), "0.44")
-        eq(cf.getboolean('Types', 'boolean'), False)
-        if self.allow_no_value:
-            eq(cf.get('NoValue', 'option-without-value'), None)
-
-        # test vars= and fallback=
-        eq(cf.get('Foo Bar', 'foo', fallback='baz'), 'bar1')
-        eq(cf.get('Foo Bar', 'foo', vars={'foo': 'baz'}), 'baz')
-        with self.assertRaises(configparser.NoSectionError):
-            cf.get('No Such Foo Bar', 'foo')
-        with self.assertRaises(configparser.NoOptionError):
-            cf.get('Foo Bar', 'no-such-foo')
-        eq(cf.get('No Such Foo Bar', 'foo', fallback='baz'), 'baz')
-        eq(cf.get('Foo Bar', 'no-such-foo', fallback='baz'), 'baz')
-        eq(cf.get('Spacey Bar', 'foo', fallback=None), 'bar2')
-        eq(cf.get('No Such Spacey Bar', 'foo', fallback=None), None)
-        eq(cf.getint('Types', 'int', fallback=18), 42)
-        eq(cf.getint('Types', 'no-such-int', fallback=18), 18)
-        eq(cf.getint('Types', 'no-such-int', fallback="18"), "18") # sic!
-        self.assertAlmostEqual(cf.getfloat('Types', 'float',
-                                           fallback=0.0), 0.44)
-        self.assertAlmostEqual(cf.getfloat('Types', 'no-such-float',
-                                           fallback=0.0), 0.0)
-        eq(cf.getfloat('Types', 'no-such-float', fallback="0.0"), "0.0") # sic!
-        eq(cf.getboolean('Types', 'boolean', fallback=True), False)
-        eq(cf.getboolean('Types', 'no-such-boolean', fallback="yes"),
-           "yes") # sic!
-        eq(cf.getboolean('Types', 'no-such-boolean', fallback=True), True)
-        eq(cf.getboolean('No Such Types', 'boolean', fallback=True), True)
-        if self.allow_no_value:
-            eq(cf.get('NoValue', 'option-without-value', fallback=False), None)
-            eq(cf.get('NoValue', 'no-such-option-without-value',
-                      fallback=False), False)
-
-        # mapping access
-        eq(cf['Foo Bar']['foo'], 'bar1')
-        eq(cf['Spacey Bar']['foo'], 'bar2')
-        eq(cf['Spacey Bar From The Beginning']['foo'], 'bar3')
-        eq(cf['Spacey Bar From The Beginning']['baz'], 'qwe')
-        eq(cf['Commented Bar']['foo'], 'bar4')
-        eq(cf['Commented Bar']['baz'], 'qwe')
-        eq(cf['Spaces']['key with spaces'], 'value')
-        eq(cf['Spaces']['another with spaces'], 'splat!')
-        eq(cf['Long Line']['foo'],
-           'this line is much, much longer than my editor\nlikes it.')
-        if self.allow_no_value:
-            eq(cf['NoValue']['option-without-value'], None)
-
-        # API access
-        self.assertNotIn('__name__', cf.options("Foo Bar"),
-                         '__name__ "option" should not be exposed by the API!')
-
-        # mapping access
-        self.assertNotIn('__name__', cf['Foo Bar'],
-                         '__name__ "option" should not be exposed by '
-                         'mapping protocol access')
-        self.assertFalse('__name__' in cf['Foo Bar'])
-        with self.assertRaises(ValueError):
-            cf['Foo Bar']['__name__']
-        with self.assertRaises(ValueError):
-            del cf['Foo Bar']['__name__']
-        with self.assertRaises(ValueError):
-            cf['Foo Bar']['__name__'] = "can't write to this special name"
-
-        # Make sure the right things happen for remove_option();
-        # added to include check for SourceForge bug #123324:
-
-        # API acceess
-        self.assertTrue(cf.remove_option('Foo Bar', 'foo'),
-                        "remove_option() failed to report existence of option")
-        self.assertFalse(cf.has_option('Foo Bar', 'foo'),
-                    "remove_option() failed to remove option")
-        self.assertFalse(cf.remove_option('Foo Bar', 'foo'),
-                    "remove_option() failed to report non-existence of option"
-                    " that was removed")
-
-        with self.assertRaises(configparser.NoSectionError) as cm:
-            cf.remove_option('No Such Section', 'foo')
-        self.assertEqual(cm.exception.args, ('No Such Section',))
-
-        eq(cf.get('Long Line', 'foo'),
-           'this line is much, much longer than my editor\nlikes it.')
-
-        # mapping access
-        del cf['Spacey Bar']['foo']
-        self.assertFalse('foo' in cf['Spacey Bar'])
-        with self.assertRaises(KeyError):
-            del cf['Spacey Bar']['foo']
-        with self.assertRaises(KeyError):
-            del cf['No Such Section']['foo']
-
-    def test_basic(self):
-        config_string = """\
-[Foo Bar]
-foo{0[0]}bar1
-[Spacey Bar]
-foo {0[0]} bar2
-[Spacey Bar From The Beginning]
-  foo {0[0]} bar3
-  baz {0[0]} qwe
-[Commented Bar]
-foo{0[1]} bar4 {1[1]} comment
-baz{0[0]}qwe {1[0]}another one
-[Long Line]
-foo{0[1]} this line is much, much longer than my editor
-   likes it.
-[Section\\with$weird%characters[\t]
-[Internationalized Stuff]
-foo[bg]{0[1]} Bulgarian
-foo{0[0]}Default
-foo[en]{0[0]}English
-foo[de]{0[0]}Deutsch
-[Spaces]
-key with spaces {0[1]} value
-another with spaces {0[0]} splat!
-[Types]
-int {0[1]} 42
-float {0[0]} 0.44
-boolean {0[0]} NO
-""".format(self.delimiters, self.comment_prefixes)
-        if self.allow_no_value:
-            config_string += (
-                "[NoValue]\n"
-                "option-without-value\n"
-                )
-        cf = self.fromstring(config_string)
-        self.basic_test(cf)
-        if self.strict:
-            with self.assertRaises(configparser.DuplicateOptionError):
-                cf.read_string(textwrap.dedent("""\
-                    [Duplicate Options Here]
-                    option {0[0]} with a value
-                    option {0[1]} with another value
-                """.format(self.delimiters)))
-            with self.assertRaises(configparser.DuplicateSectionError):
-                cf.read_string(textwrap.dedent("""\
-                    [And Now For Something]
-                    completely different {0[0]} True
-                    [And Now For Something]
-                    the larch {0[1]} 1
-                """.format(self.delimiters)))
-        else:
-            cf.read_string(textwrap.dedent("""\
-                [Duplicate Options Here]
-                option {0[0]} with a value
-                option {0[1]} with another value
-            """.format(self.delimiters)))
-
-            cf.read_string(textwrap.dedent("""\
-                [And Now For Something]
-                completely different {0[0]} True
-                [And Now For Something]
-                the larch {0[1]} 1
-            """.format(self.delimiters)))
-
-    def test_basic_from_dict(self):
-        config = {
-            "Foo Bar": {
-                "foo": "bar1",
-            },
-            "Spacey Bar": {
-                "foo": "bar2",
-            },
-            "Spacey Bar From The Beginning": {
-                "foo": "bar3",
-                "baz": "qwe",
-            },
-            "Commented Bar": {
-                "foo": "bar4",
-                "baz": "qwe",
-            },
-            "Long Line": {
-                "foo": "this line is much, much longer than my editor\nlikes "
-                       "it.",
-            },
-            "Section\\with$weird%characters[\t": {
-            },
-            "Internationalized Stuff": {
-                "foo[bg]": "Bulgarian",
-                "foo": "Default",
-                "foo[en]": "English",
-                "foo[de]": "Deutsch",
-            },
-            "Spaces": {
-                "key with spaces": "value",
-                "another with spaces": "splat!",
-            },
-            "Types": {
-                "int": 42,
-                "float": 0.44,
-                "boolean": False,
-            },
-        }
-        if self.allow_no_value:
-            config.update({
-                "NoValue": {
-                    "option-without-value": None,
-                }
-            })
-        cf = self.newconfig()
-        cf.read_dict(config)
-        self.basic_test(cf)
-        if self.strict:
-            with self.assertRaises(configparser.DuplicateOptionError):
-                cf.read_dict({
-                    "Duplicate Options Here": {
-                        'option': 'with a value',
-                        'OPTION': 'with another value',
-                    },
-                })
-        else:
-            cf.read_dict({
-                "Duplicate Options Here": {
-                    'option': 'with a value',
-                    'OPTION': 'with another value',
-                },
-            })
-
-
-    def test_case_sensitivity(self):
-        cf = self.newconfig()
-        cf.add_section("A")
-        cf.add_section("a")
-        cf.add_section("B")
-        L = cf.sections()
-        L.sort()
-        eq = self.assertEqual
-        eq(L, ["A", "B", "a"])
-        cf.set("a", "B", "value")
-        eq(cf.options("a"), ["b"])
-        eq(cf.get("a", "b"), "value",
-           "could not locate option, expecting case-insensitive option names")
-        with self.assertRaises(configparser.NoSectionError):
-            # section names are case-sensitive
-            cf.set("b", "A", "value")
-        self.assertTrue(cf.has_option("a", "b"))
-        cf.set("A", "A-B", "A-B value")
-        for opt in ("a-b", "A-b", "a-B", "A-B"):
-            self.assertTrue(
-                cf.has_option("A", opt),
-                "has_option() returned false for option which should exist")
-        eq(cf.options("A"), ["a-b"])
-        eq(cf.options("a"), ["b"])
-        cf.remove_option("a", "B")
-        eq(cf.options("a"), [])
-
-        # SF bug #432369:
-        cf = self.fromstring(
-            "[MySection]\nOption{} first line   \n\tsecond line   \n".format(
-                self.delimiters[0]))
-        eq(cf.options("MySection"), ["option"])
-        eq(cf.get("MySection", "Option"), "first line\nsecond line")
-
-        # SF bug #561822:
-        cf = self.fromstring("[section]\n"
-                             "nekey{}nevalue\n".format(self.delimiters[0]),
-                             defaults={"key":"value"})
-        self.assertTrue(cf.has_option("section", "Key"))
-
-
-    def test_case_sensitivity_mapping_access(self):
-        cf = self.newconfig()
-        cf["A"] = {}
-        cf["a"] = {"B": "value"}
-        cf["B"] = {}
-        L = [section for section in cf]
-        L.sort()
-        eq = self.assertEqual
-        elem_eq = self.assertItemsEqual
-        eq(L, ["A", "B", configparser.DEFAULTSECT, "a"])
-        eq(cf["a"].keys(), {"b"})
-        eq(cf["a"]["b"], "value",
-           "could not locate option, expecting case-insensitive option names")
-        with self.assertRaises(KeyError):
-            # section names are case-sensitive
-            cf["b"]["A"] = "value"
-        self.assertTrue("b" in cf["a"])
-        cf["A"]["A-B"] = "A-B value"
-        for opt in ("a-b", "A-b", "a-B", "A-B"):
-            self.assertTrue(
-                opt in cf["A"],
-                "has_option() returned false for option which should exist")
-        eq(cf["A"].keys(), {"a-b"})
-        eq(cf["a"].keys(), {"b"})
-        del cf["a"]["B"]
-        elem_eq(cf["a"].keys(), {})
-
-        # SF bug #432369:
-        cf = self.fromstring(
-            "[MySection]\nOption{} first line   \n\tsecond line   \n".format(
-                self.delimiters[0]))
-        eq(cf["MySection"].keys(), {"option"})
-        eq(cf["MySection"]["Option"], "first line\nsecond line")
-
-        # SF bug #561822:
-        cf = self.fromstring("[section]\n"
-                             "nekey{}nevalue\n".format(self.delimiters[0]),
-                             defaults={"key":"value"})
-        self.assertTrue("Key" in cf["section"])
-
-    def test_default_case_sensitivity(self):
-        cf = self.newconfig({"foo": "Bar"})
-        self.assertEqual(
-            cf.get("DEFAULT", "Foo"), "Bar",
-            "could not locate option, expecting case-insensitive option names")
-        cf = self.newconfig({"Foo": "Bar"})
-        self.assertEqual(
-            cf.get("DEFAULT", "Foo"), "Bar",
-            "could not locate option, expecting case-insensitive defaults")
-
-    def test_parse_errors(self):
-        cf = self.newconfig()
-        self.parse_error(cf, configparser.ParsingError,
-                         "[Foo]\n"
-                         "{}val-without-opt-name\n".format(self.delimiters[0]))
-        self.parse_error(cf, configparser.ParsingError,
-                         "[Foo]\n"
-                         "{}val-without-opt-name\n".format(self.delimiters[1]))
-        e = self.parse_error(cf, configparser.MissingSectionHeaderError,
-                             "No Section!\n")
-        self.assertEqual(e.args, ('<???>', 1, "No Section!\n"))
-        if not self.allow_no_value:
-            e = self.parse_error(cf, configparser.ParsingError,
-                                "[Foo]\n  wrong-indent\n")
-            self.assertEqual(e.args, ('<???>',))
-            # read_file on a real file
-            tricky = support.findfile("cfgparser.3")
-            if self.delimiters[0] == '=':
-                error = configparser.ParsingError
-                expected = (tricky,)
-            else:
-                error = configparser.MissingSectionHeaderError
-                expected = (tricky, 1,
-                            '  # INI with as many tricky parts as possible\n')
-            with open(tricky, encoding='utf-8') as f:
-                e = self.parse_error(cf, error, f)
-            self.assertEqual(e.args, expected)
-
-    def parse_error(self, cf, exc, src):
-        if hasattr(src, 'readline'):
-            sio = src
-        else:
-            sio = io.StringIO(src)
-        with self.assertRaises(exc) as cm:
-            cf.read_file(sio)
-        return cm.exception
-
-    def test_query_errors(self):
-        cf = self.newconfig()
-        self.assertEqual(cf.sections(), [],
-                         "new ConfigParser should have no defined sections")
-        self.assertFalse(cf.has_section("Foo"),
-                         "new ConfigParser should have no acknowledged "
-                         "sections")
-        with self.assertRaises(configparser.NoSectionError):
-            cf.options("Foo")
-        with self.assertRaises(configparser.NoSectionError):
-            cf.set("foo", "bar", "value")
-        e = self.get_error(cf, configparser.NoSectionError, "foo", "bar")
-        self.assertEqual(e.args, ("foo",))
-        cf.add_section("foo")
-        e = self.get_error(cf, configparser.NoOptionError, "foo", "bar")
-        self.assertEqual(e.args, ("bar", "foo"))
-
-    def get_error(self, cf, exc, section, option):
-        try:
-            cf.get(section, option)
-        except exc as e:
-            return e
-        else:
-            self.fail("expected exception type %s.%s"
-                      % (exc.__module__, exc.__name__))
-
-    def test_boolean(self):
-        cf = self.fromstring(
-            "[BOOLTEST]\n"
-            "T1{equals}1\n"
-            "T2{equals}TRUE\n"
-            "T3{equals}True\n"
-            "T4{equals}oN\n"
-            "T5{equals}yes\n"
-            "F1{equals}0\n"
-            "F2{equals}FALSE\n"
-            "F3{equals}False\n"
-            "F4{equals}oFF\n"
-            "F5{equals}nO\n"
-            "E1{equals}2\n"
-            "E2{equals}foo\n"
-            "E3{equals}-1\n"
-            "E4{equals}0.1\n"
-            "E5{equals}FALSE AND MORE".format(equals=self.delimiters[0])
-            )
-        for x in range(1, 5):
-            self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x))
-            self.assertFalse(cf.getboolean('BOOLTEST', 'f%d' % x))
-            self.assertRaises(ValueError,
-                              cf.getboolean, 'BOOLTEST', 'e%d' % x)
-
-    def test_weird_errors(self):
-        cf = self.newconfig()
-        cf.add_section("Foo")
-        with self.assertRaises(configparser.DuplicateSectionError) as cm:
-            cf.add_section("Foo")
-        e = cm.exception
-        self.assertEqual(str(e), "Section 'Foo' already exists")
-        self.assertEqual(e.args, ("Foo", None, None))
-
-        if self.strict:
-            with self.assertRaises(configparser.DuplicateSectionError) as cm:
-                cf.read_string(textwrap.dedent("""\
-                    [Foo]
-                    will this be added{equals}True
-                    [Bar]
-                    what about this{equals}True
-                    [Foo]
-                    oops{equals}this won't
-                """.format(equals=self.delimiters[0])), source='<foo-bar>')
-            e = cm.exception
-            self.assertEqual(str(e), "While reading from <foo-bar> [line  5]: "
-                                     "section 'Foo' already exists")
-            self.assertEqual(e.args, ("Foo", '<foo-bar>', 5))
-
-            with self.assertRaises(configparser.DuplicateOptionError) as cm:
-                cf.read_dict({'Bar': {'opt': 'val', 'OPT': 'is really `opt`'}})
-            e = cm.exception
-            self.assertEqual(str(e), "While reading from <dict>: option 'opt' "
-                                     "in section 'Bar' already exists")
-            self.assertEqual(e.args, ("Bar", "opt", "<dict>", None))
-
-    def test_write(self):
-        config_string = (
-            "[Long Line]\n"
-            "foo{0[0]} this line is much, much longer than my editor\n"
-            "   likes it.\n"
-            "[DEFAULT]\n"
-            "foo{0[1]} another very\n"
-            " long line\n"
-            "[Long Line - With Comments!]\n"
-            "test {0[1]} we        {comment} can\n"
-            "            also      {comment} place\n"
-            "            comments  {comment} in\n"
-            "            multiline {comment} values"
-            "\n".format(self.delimiters, comment=self.comment_prefixes[0])
-            )
-        if self.allow_no_value:
-            config_string += (
-            "[Valueless]\n"
-            "option-without-value\n"
-            )
-
-        cf = self.fromstring(config_string)
-        output = io.StringIO()
-        cf.write(output)
-        expect_string = (
-            "[DEFAULT]\n"
-            "foo {equals} another very\n"
-            "\tlong line\n"
-            "\n"
-            "[Long Line]\n"
-            "foo {equals} this line is much, much longer than my editor\n"
-            "\tlikes it.\n"
-            "\n"
-            "[Long Line - With Comments!]\n"
-            "test {equals} we\n"
-            "\talso\n"
-            "\tcomments\n"
-            "\tmultiline\n"
-            "\n".format(equals=self.delimiters[0])
-            )
-        if self.allow_no_value:
-            expect_string += (
-                "[Valueless]\n"
-                "option-without-value\n"
-                "\n"
-                )
-        self.assertEqual(output.getvalue(), expect_string)
-
-    def test_set_string_types(self):
-        cf = self.fromstring("[sect]\n"
-                             "option1{eq}foo\n".format(eq=self.delimiters[0]))
-        # Check that we don't get an exception when setting values in
-        # an existing section using strings:
-        class mystr(str):
-            pass
-        cf.set("sect", "option1", "splat")
-        cf.set("sect", "option1", mystr("splat"))
-        cf.set("sect", "option2", "splat")
-        cf.set("sect", "option2", mystr("splat"))
-        cf.set("sect", "option1", "splat")
-        cf.set("sect", "option2", "splat")
-
-    def test_read_returns_file_list(self):
-        if self.delimiters[0] != '=':
-            # skip reading the file if we're using an incompatible format
-            return
-        file1 = support.findfile("cfgparser.1")
-        # check when we pass a mix of readable and non-readable files:
-        cf = self.newconfig()
-        parsed_files = cf.read([file1, "nonexistent-file"])
-        self.assertEqual(parsed_files, [file1])
-        self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
-        # check when we pass only a filename:
-        cf = self.newconfig()
-        parsed_files = cf.read(file1)
-        self.assertEqual(parsed_files, [file1])
-        self.assertEqual(cf.get("Foo Bar", "foo"), "newbar")
-        # check when we pass only missing files:
-        cf = self.newconfig()
-        parsed_files = cf.read(["nonexistent-file"])
-        self.assertEqual(parsed_files, [])
-        # check when we pass no files:
-        cf = self.newconfig()
-        parsed_files = cf.read([])
-        self.assertEqual(parsed_files, [])
-
-    # shared by subclasses
-    def get_interpolation_config(self):
-        return self.fromstring(
-            "[Foo]\n"
-            "bar{equals}something %(with1)s interpolation (1 step)\n"
-            "bar9{equals}something %(with9)s lots of interpolation (9 steps)\n"
-            "bar10{equals}something %(with10)s lots of interpolation (10 steps)\n"
-            "bar11{equals}something %(with11)s lots of interpolation (11 steps)\n"
-            "with11{equals}%(with10)s\n"
-            "with10{equals}%(with9)s\n"
-            "with9{equals}%(with8)s\n"
-            "with8{equals}%(With7)s\n"
-            "with7{equals}%(WITH6)s\n"
-            "with6{equals}%(with5)s\n"
-            "With5{equals}%(with4)s\n"
-            "WITH4{equals}%(with3)s\n"
-            "with3{equals}%(with2)s\n"
-            "with2{equals}%(with1)s\n"
-            "with1{equals}with\n"
-            "\n"
-            "[Mutual Recursion]\n"
-            "foo{equals}%(bar)s\n"
-            "bar{equals}%(foo)s\n"
-            "\n"
-            "[Interpolation Error]\n"
-            "name{equals}%(reference)s\n".format(equals=self.delimiters[0]),
-            # no definition for 'reference'
-            defaults={"getname": "%(__name__)s"})
-
-    def check_items_config(self, expected):
-        cf = self.fromstring(
-            "[section]\n"
-            "name {0[0]} value\n"
-            "key{0[1]} |%(name)s| \n"
-            "getdefault{0[1]} |%(default)s|\n"
-            "getname{0[1]} |%(__name__)s|".format(self.delimiters),
-            defaults={"default": "<default>"})
-        L = list(cf.items("section"))
-        L.sort()
-        self.assertEqual(L, expected)
-
-
-class StrictTestCase(BasicTestCase):
-    config_class = configparser.RawConfigParser
-    strict = True
-
-
-class ConfigParserTestCase(BasicTestCase):
-    config_class = configparser.ConfigParser
-
-    def test_interpolation(self):
-        rawval = {
-            configparser.ConfigParser: ("something %(with11)s "
-                                        "lots of interpolation (11 steps)"),
-            configparser.SafeConfigParser: "%(with1)s",
-        }
-        cf = self.get_interpolation_config()
-        eq = self.assertEqual
-        eq(cf.get("Foo", "getname"), "Foo")
-        eq(cf.get("Foo", "bar"), "something with interpolation (1 step)")
-        eq(cf.get("Foo", "bar9"),
-           "something with lots of interpolation (9 steps)")
-        eq(cf.get("Foo", "bar10"),
-           "something with lots of interpolation (10 steps)")
-        e = self.get_error(cf, configparser.InterpolationDepthError, "Foo", "bar11")
-        self.assertEqual(e.args, ("bar11", "Foo", rawval[self.config_class]))
-
-    def test_interpolation_missing_value(self):
-        rawval = {
-            configparser.ConfigParser: '%(reference)s',
-            configparser.SafeConfigParser: '',
-        }
-        cf = self.get_interpolation_config()
-        e = self.get_error(cf, configparser.InterpolationMissingOptionError,
-                           "Interpolation Error", "name")
-        self.assertEqual(e.reference, "reference")
-        self.assertEqual(e.section, "Interpolation Error")
-        self.assertEqual(e.option, "name")
-        self.assertEqual(e.args, ('name', 'Interpolation Error',
-                                  rawval[self.config_class], 'reference'))
-
-    def test_items(self):
-        self.check_items_config([('default', '<default>'),
-                                 ('getdefault', '|<default>|'),
-                                 ('getname', '|section|'),
-                                 ('key', '|value|'),
-                                 ('name', 'value')])
-
-    def test_set_nonstring_types(self):
-        cf = self.newconfig()
-        cf.add_section('non-string')
-        cf.set('non-string', 'int', 1)
-        cf.set('non-string', 'list', [0, 1, 1, 2, 3, 5, 8, 13, '%('])
-        cf.set('non-string', 'dict', {'pi': 3.14159, '%(': 1,
-                                      '%(list)': '%(list)'})
-        cf.set('non-string', 'string_with_interpolation', '%(list)s')
-        self.assertEqual(cf.get('non-string', 'int', raw=True), 1)
-        self.assertRaises(TypeError, cf.get, 'non-string', 'int')
-        self.assertEqual(cf.get('non-string', 'list', raw=True),
-                         [0, 1, 1, 2, 3, 5, 8, 13, '%('])
-        self.assertRaises(TypeError, cf.get, 'non-string', 'list')
-        self.assertEqual(cf.get('non-string', 'dict', raw=True),
-                         {'pi': 3.14159, '%(': 1, '%(list)': '%(list)'})
-        self.assertRaises(TypeError, cf.get, 'non-string', 'dict')
-        self.assertEqual(cf.get('non-string', 'string_with_interpolation',
-                                raw=True), '%(list)s')
-        self.assertRaises(ValueError, cf.get, 'non-string',
-                          'string_with_interpolation', raw=False)
-
-class ConfigParserTestCaseNonStandardDelimiters(ConfigParserTestCase):
-    delimiters = (':=', '$')
-    comment_prefixes = ('//', '"')
-
-class MultilineValuesTestCase(BasicTestCase):
-    config_class = configparser.ConfigParser
-    wonderful_spam = ("I'm having spam spam spam spam "
-                      "spam spam spam beaked beans spam "
-                      "spam spam and spam!").replace(' ', '\t\n')
-
-    def setUp(self):
-        cf = self.newconfig()
-        for i in range(100):
-            s = 'section{}'.format(i)
-            cf.add_section(s)
-            for j in range(10):
-                cf.set(s, 'lovely_spam{}'.format(j), self.wonderful_spam)
-        with open(support.TESTFN, 'w') as f:
-            cf.write(f)
-
-    def tearDown(self):
-        os.unlink(support.TESTFN)
-
-    def test_dominating_multiline_values(self):
-        # We're reading from file because this is where the code changed
-        # during performance updates in Python 3.2
-        cf_from_file = self.newconfig()
-        with open(support.TESTFN) as f:
-            cf_from_file.read_file(f)
-        self.assertEqual(cf_from_file.get('section8', 'lovely_spam4'),
-                         self.wonderful_spam.replace('\t\n', '\n'))
-
-class RawConfigParserTestCase(BasicTestCase):
-    config_class = configparser.RawConfigParser
-
-    def test_interpolation(self):
-        cf = self.get_interpolation_config()
-        eq = self.assertEqual
-        eq(cf.get("Foo", "getname"), "%(__name__)s")
-        eq(cf.get("Foo", "bar"),
-           "something %(with1)s interpolation (1 step)")
-        eq(cf.get("Foo", "bar9"),
-           "something %(with9)s lots of interpolation (9 steps)")
-        eq(cf.get("Foo", "bar10"),
-           "something %(with10)s lots of interpolation (10 steps)")
-        eq(cf.get("Foo", "bar11"),
-           "something %(with11)s lots of interpolation (11 steps)")
-
-    def test_items(self):
-        self.check_items_config([('default', '<default>'),
-                                 ('getdefault', '|%(default)s|'),
-                                 ('getname', '|%(__name__)s|'),
-                                 ('key', '|%(name)s|'),
-                                 ('name', 'value')])
-
-    def test_set_nonstring_types(self):
-        cf = self.newconfig()
-        cf.add_section('non-string')
-        cf.set('non-string', 'int', 1)
-        cf.set('non-string', 'list', [0, 1, 1, 2, 3, 5, 8, 13])
-        cf.set('non-string', 'dict', {'pi': 3.14159})
-        self.assertEqual(cf.get('non-string', 'int'), 1)
-        self.assertEqual(cf.get('non-string', 'list'),
-                         [0, 1, 1, 2, 3, 5, 8, 13])
-        self.assertEqual(cf.get('non-string', 'dict'), {'pi': 3.14159})
-
-class RawConfigParserTestCaseNonStandardDelimiters(RawConfigParserTestCase):
-    delimiters = (':=', '$')
-    comment_prefixes = ('//', '"')
-
-class RawConfigParserTestSambaConf(BasicTestCase):
-    config_class = configparser.RawConfigParser
-    comment_prefixes = ('#', ';', '//', '----')
-    empty_lines_in_values = False
-
-    def test_reading(self):
-        smbconf = support.findfile("cfgparser.2")
-        # check when we pass a mix of readable and non-readable files:
-        cf = self.newconfig()
-        parsed_files = cf.read([smbconf, "nonexistent-file"], encoding='utf-8')
-        self.assertEqual(parsed_files, [smbconf])
-        sections = ['global', 'homes', 'printers',
-                    'print$', 'pdf-generator', 'tmp', 'Agustin']
-        self.assertEqual(cf.sections(), sections)
-        self.assertEqual(cf.get("global", "workgroup"), "MDKGROUP")
-        self.assertEqual(cf.getint("global", "max log size"), 50)
-        self.assertEqual(cf.get("global", "hosts allow"), "127.")
-        self.assertEqual(cf.get("tmp", "echo command"), "cat %s; rm %s")
-
-class SafeConfigParserTestCase(ConfigParserTestCase):
-    config_class = configparser.SafeConfigParser
-
-    def test_safe_interpolation(self):
-        # See http://www.python.org/sf/511737
-        cf = self.fromstring("[section]\n"
-                             "option1{eq}xxx\n"
-                             "option2{eq}%(option1)s/xxx\n"
-                             "ok{eq}%(option1)s/%%s\n"
-                             "not_ok{eq}%(option2)s/%%s".format(
-                                 eq=self.delimiters[0]))
-        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{eq}foo\n".format(eq=self.delimiters[0]))
-
-        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")
-
-        # bug #5741: double percents are *not* malformed
-        cf.set("sect", "option2", "foo%%bar")
-        self.assertEqual(cf.get("sect", "option2"), "foo%bar")
-
-    def test_set_nonstring_types(self):
-        cf = self.fromstring("[sect]\n"
-                             "option1{eq}foo\n".format(eq=self.delimiters[0]))
-        # Check that we get a TypeError when setting non-string values
-        # in an existing section:
-        self.assertRaises(TypeError, cf.set, "sect", "option1", 1)
-        self.assertRaises(TypeError, cf.set, "sect", "option1", 1.0)
-        self.assertRaises(TypeError, cf.set, "sect", "option1", object())
-        self.assertRaises(TypeError, cf.set, "sect", "option2", 1)
-        self.assertRaises(TypeError, cf.set, "sect", "option2", 1.0)
-        self.assertRaises(TypeError, cf.set, "sect", "option2", object())
-
-    def test_add_section_default_1(self):
-        cf = self.newconfig()
-        self.assertRaises(ValueError, cf.add_section, "default")
-
-    def test_add_section_default_2(self):
-        cf = self.newconfig()
-        self.assertRaises(ValueError, cf.add_section, "DEFAULT")
-
-class SafeConfigParserTestCaseNonStandardDelimiters(SafeConfigParserTestCase):
-    delimiters = (':=', '$')
-    comment_prefixes = ('//', '"')
-
-class SafeConfigParserTestCaseNoValue(SafeConfigParserTestCase):
-    allow_no_value = True
-
-class SafeConfigParserTestCaseTrickyFile(CfgParserTestCaseClass):
-    config_class = configparser.SafeConfigParser
-    delimiters = {'='}
-    comment_prefixes = {'#'}
-    allow_no_value = True
-
-    def test_cfgparser_dot_3(self):
-        tricky = support.findfile("cfgparser.3")
-        cf = self.newconfig()
-        self.assertEqual(len(cf.read(tricky, encoding='utf-8')), 1)
-        self.assertEqual(cf.sections(), ['strange',
-                                         'corruption',
-                                         'yeah, sections can be '
-                                         'indented as well',
-                                         'another one!',
-                                         'no values here',
-                                         'tricky interpolation',
-                                         'more interpolation'])
-        self.assertEqual(cf.getint('DEFAULT', 'go',
-                                   vars={'interpolate': '-1'}), -1)
-        with self.assertRaises(ValueError):
-            # no interpolation will happen
-            cf.getint('DEFAULT', 'go', raw=True, vars={'interpolate': '-1'})
-        self.assertEqual(len(cf.get('strange', 'other').split('\n')), 4)
-        self.assertEqual(len(cf.get('corruption', 'value').split('\n')), 10)
-        longname = 'yeah, sections can be indented as well'
-        self.assertFalse(cf.getboolean(longname, 'are they subsections'))
-        self.assertEquals(cf.get(longname, 'lets use some Unicode'),
-                                           '片仮名')
-        self.assertEqual(len(cf.items('another one!')), 5) # 4 in section and
-                                                           # `go` from DEFAULT
-        with self.assertRaises(configparser.InterpolationMissingOptionError):
-            cf.items('no values here')
-        self.assertEqual(cf.get('tricky interpolation', 'lets'), 'do this')
-        self.assertEqual(cf.get('tricky interpolation', 'lets'),
-                         cf.get('tricky interpolation', 'go'))
-        self.assertEqual(cf.get('more interpolation', 'lets'), 'go shopping')
-
-    def test_unicode_failure(self):
-        tricky = support.findfile("cfgparser.3")
-        cf = self.newconfig()
-        with self.assertRaises(UnicodeDecodeError):
-            cf.read(tricky, encoding='ascii')
-
-
-class Issue7005TestCase(unittest.TestCase):
-    """Test output when None is set() as a value and allow_no_value == False.
-
-    http://bugs.python.org/issue7005
-
-    """
-
-    expected_output = "[section]\noption = None\n\n"
-
-    def prepare(self, config_class):
-        # This is the default, but that's the point.
-        cp = config_class(allow_no_value=False)
-        cp.add_section("section")
-        cp.set("section", "option", None)
-        sio = io.StringIO()
-        cp.write(sio)
-        return sio.getvalue()
-
-    def test_none_as_value_stringified(self):
-        output = self.prepare(configparser.ConfigParser)
-        self.assertEqual(output, self.expected_output)
-
-    def test_none_as_value_stringified_raw(self):
-        output = self.prepare(configparser.RawConfigParser)
-        self.assertEqual(output, self.expected_output)
-
-
-class SortedTestCase(RawConfigParserTestCase):
-    dict_type = SortedDict
-
-    def test_sorted(self):
-        cf = self.fromstring("[b]\n"
-                             "o4=1\n"
-                             "o3=2\n"
-                             "o2=3\n"
-                             "o1=4\n"
-                             "[a]\n"
-                             "k=v\n")
-        output = io.StringIO()
-        cf.write(output)
-        self.assertEquals(output.getvalue(),
-                          "[a]\n"
-                          "k = v\n\n"
-                          "[b]\n"
-                          "o1 = 4\n"
-                          "o2 = 3\n"
-                          "o3 = 2\n"
-                          "o4 = 1\n\n")
-
-
-class CompatibleTestCase(CfgParserTestCaseClass):
-    config_class = configparser.RawConfigParser
-    comment_prefixes = configparser._COMPATIBLE
-
-    def test_comment_handling(self):
-        config_string = textwrap.dedent("""\
-        [Commented Bar]
-        baz=qwe ; a comment
-        foo: bar # not a comment!
-        # but this is a comment
-        ; another comment
-        quirk: this;is not a comment
-        ; a space must precede an inline comment
-        """)
-        cf = self.fromstring(config_string)
-        self.assertEqual(cf.get('Commented Bar', 'foo'), 'bar # not a comment!')
-        self.assertEqual(cf.get('Commented Bar', 'baz'), 'qwe')
-        self.assertEqual(cf.get('Commented Bar', 'quirk'), 'this;is not a comment')
-
-
-def test_main():
-    support.run_unittest(
-        ConfigParserTestCase,
-        ConfigParserTestCaseNonStandardDelimiters,
-        MultilineValuesTestCase,
-        RawConfigParserTestCase,
-        RawConfigParserTestCaseNonStandardDelimiters,
-        RawConfigParserTestSambaConf,
-        SafeConfigParserTestCase,
-        SafeConfigParserTestCaseNonStandardDelimiters,
-        SafeConfigParserTestCaseNoValue,
-        SafeConfigParserTestCaseTrickyFile,
-        SortedTestCase,
-        Issue7005TestCase,
-        StrictTestCase,
-        CompatibleTestCase,
-        )
-
-
-if __name__ == "__main__":
-    test_main()

Modified: python/branches/pep-3151/Lib/test/test_cgi.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_cgi.py	(original)
+++ python/branches/pep-3151/Lib/test/test_cgi.py	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,7 @@
 import sys
 import tempfile
 import unittest
-from io import StringIO
+from io import StringIO, BytesIO
 
 class HackedSysModule:
     # The regression test will have real values in sys.argv, which
@@ -14,7 +14,6 @@
 
 cgi.sys = HackedSysModule()
 
-
 class ComparableException:
     def __init__(self, err):
         self.err = err
@@ -38,7 +37,7 @@
         env['REQUEST_METHOD'] = 'GET'
         env['QUERY_STRING'] = buf
     elif method == "POST":
-        fp = StringIO(buf)
+        fp = BytesIO(buf.encode('latin-1')) # FieldStorage expects bytes
         env['REQUEST_METHOD'] = 'POST'
         env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
         env['CONTENT_LENGTH'] = str(len(buf))
@@ -106,9 +105,10 @@
     return [(p[0], p[1][0]) for p in list]
 
 def gen_result(data, environ):
-    fake_stdin = StringIO(data)
+    encoding = 'latin-1'
+    fake_stdin = BytesIO(data.encode(encoding))
     fake_stdin.seek(0)
-    form = cgi.FieldStorage(fp=fake_stdin, environ=environ)
+    form = cgi.FieldStorage(fp=fake_stdin, environ=environ, encoding=encoding)
 
     result = {}
     for k, v in dict(form).items():
@@ -122,16 +122,16 @@
         for orig, expect in parse_strict_test_cases:
             # Test basic parsing
             d = do_test(orig, "GET")
-            self.assertEqual(d, expect, "Error parsing %s" % repr(orig))
+            self.assertEqual(d, expect, "Error parsing %s method GET" % repr(orig))
             d = do_test(orig, "POST")
-            self.assertEqual(d, expect, "Error parsing %s" % repr(orig))
+            self.assertEqual(d, expect, "Error parsing %s method POST" % repr(orig))
 
             env = {'QUERY_STRING': orig}
             fs = cgi.FieldStorage(environ=env)
             if isinstance(expect, dict):
                 # test dict interface
                 self.assertEqual(len(expect), len(fs))
-                self.assertItemsEqual(expect.keys(), fs.keys())
+                self.assertCountEqual(expect.keys(), fs.keys())
                 ##self.assertEqual(norm(expect.values()), norm(fs.values()))
                 ##self.assertEqual(norm(expect.items()), norm(fs.items()))
                 self.assertEqual(fs.getvalue("nonexistent field", "default"), "default")
@@ -155,6 +155,7 @@
             cgi.logfp = None
             cgi.logfile = "/dev/null"
             cgi.initlog("%s", "Testing log 3")
+            self.addCleanup(cgi.logfp.close)
             cgi.log("Testing log 4")
 
     def test_fieldstorage_readline(self):
@@ -181,9 +182,9 @@
                     setattr(self, name, a)
                 return a
 
-        f = TestReadlineFile(tempfile.TemporaryFile("w+"))
+        f = TestReadlineFile(tempfile.TemporaryFile("wb+"))
         self.addCleanup(f.close)
-        f.write('x' * 256 * 1024)
+        f.write(b'x' * 256 * 1024)
         f.seek(0)
         env = {'REQUEST_METHOD':'PUT'}
         fs = cgi.FieldStorage(fp=f, environ=env)
@@ -192,6 +193,7 @@
         # (by read_binary); if we are chunking properly, it will be called 5 times
         # as long as the chunksize is 1 << 16.
         self.assertTrue(f.numcalls > 2)
+        f.close()
 
     def test_fieldstorage_multipart(self):
         #Test basic FieldStorage multipart parsing
@@ -216,16 +218,18 @@
  Add\x20
 -----------------------------721837373350705526688164684--
 """
-        fs = cgi.FieldStorage(fp=StringIO(postdata), environ=env)
-        self.assertEquals(len(fs.list), 4)
+        encoding = 'ascii'
+        fp = BytesIO(postdata.encode(encoding))
+        fs = cgi.FieldStorage(fp, environ=env, encoding=encoding)
+        self.assertEqual(len(fs.list), 4)
         expect = [{'name':'id', 'filename':None, 'value':'1234'},
                   {'name':'title', 'filename':None, 'value':''},
-                  {'name':'file', 'filename':'test.txt', 'value':'Testing 123.'},
+                  {'name':'file', 'filename':'test.txt', 'value':b'Testing 123.\n'},
                   {'name':'submit', 'filename':None, 'value':' Add '}]
         for x in range(len(fs.list)):
             for k, exp in expect[x].items():
                 got = getattr(fs.list[x], k)
-                self.assertEquals(got, exp)
+                self.assertEqual(got, exp)
 
     _qs_result = {
         'key1': 'value1',
@@ -245,8 +249,7 @@
         self.assertEqual(self._qs_result, v)
 
     def testQSAndFormData(self):
-        data = """
----123
+        data = """---123
 Content-Disposition: form-data; name="key2"
 
 value2y
@@ -270,8 +273,7 @@
         self.assertEqual(self._qs_result, v)
 
     def testQSAndFormDataFile(self):
-        data = """
----123
+        data = """---123
 Content-Disposition: form-data; name="key2"
 
 value2y
@@ -299,7 +301,7 @@
         }
         result = self._qs_result.copy()
         result.update({
-            'upload': 'this is the content of the fake file'
+            'upload': b'this is the content of the fake file\n'
         })
         v = gen_result(data, environ)
         self.assertEqual(result, v)

Modified: python/branches/pep-3151/Lib/test/test_charmapcodec.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_charmapcodec.py	(original)
+++ python/branches/pep-3151/Lib/test/test_charmapcodec.py	Sat Feb 26 08:16:32 2011
@@ -27,24 +27,24 @@
 
 class CharmapCodecTest(unittest.TestCase):
     def test_constructorx(self):
-        self.assertEquals(str(b'abc', codecname), 'abc')
-        self.assertEquals(str(b'xdef', codecname), 'abcdef')
-        self.assertEquals(str(b'defx', codecname), 'defabc')
-        self.assertEquals(str(b'dxf', codecname), 'dabcf')
-        self.assertEquals(str(b'dxfx', codecname), 'dabcfabc')
+        self.assertEqual(str(b'abc', codecname), 'abc')
+        self.assertEqual(str(b'xdef', codecname), 'abcdef')
+        self.assertEqual(str(b'defx', codecname), 'defabc')
+        self.assertEqual(str(b'dxf', codecname), 'dabcf')
+        self.assertEqual(str(b'dxfx', codecname), 'dabcfabc')
 
     def test_encodex(self):
-        self.assertEquals('abc'.encode(codecname), b'abc')
-        self.assertEquals('xdef'.encode(codecname), b'abcdef')
-        self.assertEquals('defx'.encode(codecname), b'defabc')
-        self.assertEquals('dxf'.encode(codecname), b'dabcf')
-        self.assertEquals('dxfx'.encode(codecname), b'dabcfabc')
+        self.assertEqual('abc'.encode(codecname), b'abc')
+        self.assertEqual('xdef'.encode(codecname), b'abcdef')
+        self.assertEqual('defx'.encode(codecname), b'defabc')
+        self.assertEqual('dxf'.encode(codecname), b'dabcf')
+        self.assertEqual('dxfx'.encode(codecname), b'dabcfabc')
 
     def test_constructory(self):
-        self.assertEquals(str(b'ydef', codecname), 'def')
-        self.assertEquals(str(b'defy', codecname), 'def')
-        self.assertEquals(str(b'dyf', codecname), 'df')
-        self.assertEquals(str(b'dyfy', codecname), 'df')
+        self.assertEqual(str(b'ydef', codecname), 'def')
+        self.assertEqual(str(b'defy', codecname), 'def')
+        self.assertEqual(str(b'dyf', codecname), 'df')
+        self.assertEqual(str(b'dyfy', codecname), 'df')
 
     def test_maptoundefined(self):
         self.assertRaises(UnicodeError, str, b'abc\001', codecname)

Modified: python/branches/pep-3151/Lib/test/test_class.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_class.py	(original)
+++ python/branches/pep-3151/Lib/test/test_class.py	Sat Feb 26 08:16:32 2011
@@ -436,7 +436,7 @@
         del testme
         import gc
         gc.collect()
-        self.assertEquals(["crab people, crab people"], x)
+        self.assertEqual(["crab people, crab people"], x)
 
     def testBadTypeReturned(self):
         # return values of some method are type-checked
@@ -529,17 +529,17 @@
 
         a1 = A(1)
         a2 = A(2)
-        self.assertEquals(a1.f, a1.f)
-        self.assertNotEquals(a1.f, a2.f)
-        self.assertNotEquals(a1.f, a1.g)
-        self.assertEquals(a1.f, A(1).f)
-        self.assertEquals(hash(a1.f), hash(a1.f))
-        self.assertEquals(hash(a1.f), hash(A(1).f))
-
-        self.assertNotEquals(A.f, a1.f)
-        self.assertNotEquals(A.f, A.g)
-        self.assertEquals(B.f, A.f)
-        self.assertEquals(hash(B.f), hash(A.f))
+        self.assertEqual(a1.f, a1.f)
+        self.assertNotEqual(a1.f, a2.f)
+        self.assertNotEqual(a1.f, a1.g)
+        self.assertEqual(a1.f, A(1).f)
+        self.assertEqual(hash(a1.f), hash(a1.f))
+        self.assertEqual(hash(a1.f), hash(A(1).f))
+
+        self.assertNotEqual(A.f, a1.f)
+        self.assertNotEqual(A.f, A.g)
+        self.assertEqual(B.f, A.f)
+        self.assertEqual(hash(B.f), hash(A.f))
 
         # the following triggers a SystemError in 2.4
         a = A(hash(A.f)^(-1))

Modified: python/branches/pep-3151/Lib/test/test_cmath.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_cmath.py	(original)
+++ python/branches/pep-3151/Lib/test/test_cmath.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,5 @@
-from test.support import run_unittest
-from test.test_math import parse_testfile, test_file, requires_IEEE_754
+from test.support import run_unittest, requires_IEEE_754
+from test.test_math import parse_testfile, test_file
 import unittest
 import cmath, math
 from cmath import phase, polar, rect, pi
@@ -312,10 +312,8 @@
                 self.rAssertAlmostEqual(math.log(v, base), z.real)
                 self.assertEqual(0., z.imag)
 
+    @requires_IEEE_754
     def test_specific_values(self):
-        if not float.__getformat__("double").startswith("IEEE"):
-            return
-
         def rect_complex(z):
             """Wrapped version of rect that accepts a complex number instead of
             two float arguments."""
@@ -460,9 +458,11 @@
         self.assertEqual(abs(complex(INF, NAN)), INF)
         self.assertTrue(math.isnan(abs(complex(NAN, NAN))))
 
+
+    @requires_IEEE_754
+    def test_abs_overflows(self):
         # result overflows
-        if float.__getformat__("double").startswith("IEEE"):
-            self.assertRaises(OverflowError, abs, complex(1.4e308, 1.4e308))
+        self.assertRaises(OverflowError, abs, complex(1.4e308, 1.4e308))
 
     def assertCEqual(self, a, b):
         eps = 1E-7
@@ -511,10 +511,26 @@
     @unittest.skipIf(sysconfig.get_config_var('TANH_PRESERVES_ZERO_SIGN') == 0,
                      "system tanh() function doesn't copy the sign")
     def testTanhSign(self):
-        self.assertComplexIdentical(cmath.tanh(complex(0., .0j)), complex(0., .0j))
-        self.assertComplexIdentical(cmath.tanh(complex(0., -.0j)), complex(0., -.0j))
-        self.assertComplexIdentical(cmath.tanh(complex(-0., .0j)), complex(-0., .0j))
-        self.assertComplexIdentical(cmath.tanh(complex(-0., -.0j)), complex(-0., -.0j))
+        for z in complex_zeros:
+            self.assertComplexIdentical(cmath.tanh(z), z)
+
+    # The algorithm used for atan and atanh makes use of the system
+    # log1p function; If that system function doesn't respect the sign
+    # of zero, then atan and atanh will also have difficulties with
+    # the sign of complex zeros.
+    @requires_IEEE_754
+    @unittest.skipIf(sysconfig.get_config_var('LOG1P_DROPS_ZERO_SIGN'),
+                     "system log1p() function doesn't preserve the sign")
+    def testAtanSign(self):
+        for z in complex_zeros:
+            self.assertComplexIdentical(cmath.atan(z), z)
+
+    @requires_IEEE_754
+    @unittest.skipIf(sysconfig.get_config_var('LOG1P_DROPS_ZERO_SIGN'),
+                     "system log1p() function doesn't preserve the sign")
+    def testAtanhSign(self):
+        for z in complex_zeros:
+            self.assertComplexIdentical(cmath.atanh(z), z)
 
 
 def test_main():

Modified: python/branches/pep-3151/Lib/test/test_cmd_line.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_cmd_line.py	(original)
+++ python/branches/pep-3151/Lib/test/test_cmd_line.py	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,7 @@
 import os
 import sys
 import subprocess
+import tempfile
 from test.script_helper import spawn_python, kill_python, assert_python_ok, assert_python_failure
 
 
@@ -150,7 +151,7 @@
     @unittest.skipUnless(sys.platform == 'darwin', 'test specific to Mac OS X')
     def test_osx_utf8(self):
         def check_output(text):
-            decoded = text.decode('utf8', 'surrogateescape')
+            decoded = text.decode('utf-8', 'surrogateescape')
             expected = ascii(decoded).encode('ascii') + b'\n'
 
             env = os.environ.copy()
@@ -221,6 +222,49 @@
         self.assertIn(path1.encode('ascii'), out)
         self.assertIn(path2.encode('ascii'), out)
 
+    def test_displayhook_unencodable(self):
+        for encoding in ('ascii', 'latin-1', 'utf-8'):
+            env = os.environ.copy()
+            env['PYTHONIOENCODING'] = encoding
+            p = subprocess.Popen(
+                [sys.executable, '-i'],
+                stdin=subprocess.PIPE,
+                stdout=subprocess.PIPE,
+                stderr=subprocess.STDOUT,
+                env=env)
+            # non-ascii, surrogate, non-BMP printable, non-BMP unprintable
+            text = "a=\xe9 b=\uDC80 c=\U00010000 d=\U0010FFFF"
+            p.stdin.write(ascii(text).encode('ascii') + b"\n")
+            p.stdin.write(b'exit()\n')
+            data = kill_python(p)
+            escaped = repr(text).encode(encoding, 'backslashreplace')
+            self.assertIn(escaped, data)
+
+    def check_input(self, code, expected):
+        with tempfile.NamedTemporaryFile("wb+") as stdin:
+            sep = os.linesep.encode('ASCII')
+            stdin.write(sep.join((b'abc', b'def')))
+            stdin.flush()
+            stdin.seek(0)
+            with subprocess.Popen(
+                (sys.executable, "-c", code),
+                stdin=stdin, stdout=subprocess.PIPE) as proc:
+                stdout, stderr = proc.communicate()
+        self.assertEqual(stdout.rstrip(), expected)
+
+    def test_stdin_readline(self):
+        # Issue #11272: check that sys.stdin.readline() replaces '\r\n' by '\n'
+        # on Windows (sys.stdin is opened in binary mode)
+        self.check_input(
+            "import sys; print(repr(sys.stdin.readline()))",
+            b"'abc\\n'")
+
+    def test_builtin_input(self):
+        # Issue #11272: check that input() strips newlines ('\n' or '\r\n')
+        self.check_input(
+            "print(repr(input()))",
+            b"'abc'")
+
 
 def test_main():
     test.support.run_unittest(CmdLineTest)

Modified: python/branches/pep-3151/Lib/test/test_code.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_code.py	(original)
+++ python/branches/pep-3151/Lib/test/test_code.py	Sat Feb 26 08:16:32 2011
@@ -128,9 +128,9 @@
 
     def test_newempty(self):
         co = _testcapi.code_newempty("filename", "funcname", 15)
-        self.assertEquals(co.co_filename, "filename")
-        self.assertEquals(co.co_name, "funcname")
-        self.assertEquals(co.co_firstlineno, 15)
+        self.assertEqual(co.co_filename, "filename")
+        self.assertEqual(co.co_name, "funcname")
+        self.assertEqual(co.co_firstlineno, 15)
 
 
 class CodeWeakRefTest(unittest.TestCase):

Modified: python/branches/pep-3151/Lib/test/test_codeccallbacks.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_codeccallbacks.py	(original)
+++ python/branches/pep-3151/Lib/test/test_codeccallbacks.py	Sat Feb 26 08:16:32 2011
@@ -186,7 +186,7 @@
         charmap = dict((ord(c), bytes(2*c.upper(), 'ascii')) for c in "abcdefgh")
         sin = "abc"
         sout = b"AABBCC"
-        self.assertEquals(codecs.charmap_encode(sin, "strict", charmap)[0], sout)
+        self.assertEqual(codecs.charmap_encode(sin, "strict", charmap)[0], sout)
 
         sin = "abcA"
         self.assertRaises(UnicodeError, codecs.charmap_encode, sin, "strict", charmap)
@@ -194,7 +194,7 @@
         charmap[ord("?")] = b"XYZ"
         sin = "abcDEF"
         sout = b"AABBCCXYZXYZXYZ"
-        self.assertEquals(codecs.charmap_encode(sin, "replace", charmap)[0], sout)
+        self.assertEqual(codecs.charmap_encode(sin, "replace", charmap)[0], sout)
 
         charmap[ord("?")] = "XYZ" # wrong type in mapping
         self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap)
@@ -327,7 +327,7 @@
 
         # check with the correct number and type of arguments
         exc = exctype(*args)
-        self.assertEquals(str(exc), msg)
+        self.assertEqual(str(exc), msg)
 
     def test_unicodeencodeerror(self):
         self.check_exceptionobjectargs(
@@ -437,17 +437,17 @@
            UnicodeError("ouch")
         )
         # If the correct exception is passed in, "ignore" returns an empty replacement
-        self.assertEquals(
+        self.assertEqual(
             codecs.ignore_errors(
                 UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
             ("", 1)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.ignore_errors(
                 UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
             ("", 1)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.ignore_errors(
                 UnicodeTranslateError("\u3042", 0, 1, "ouch")),
             ("", 1)
@@ -477,17 +477,17 @@
             BadObjectUnicodeDecodeError()
         )
         # With the correct exception, "replace" returns an "?" or "\ufffd" replacement
-        self.assertEquals(
+        self.assertEqual(
             codecs.replace_errors(
                 UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
             ("?", 1)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.replace_errors(
                 UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
             ("\ufffd", 1)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.replace_errors(
                 UnicodeTranslateError("\u3042", 0, 1, "ouch")),
             ("\ufffd", 1)
@@ -520,7 +520,7 @@
         # Use the correct exception
         cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 0x3042)
         s = "".join(chr(c) for c in cs)
-        self.assertEquals(
+        self.assertEqual(
             codecs.xmlcharrefreplace_errors(
                 UnicodeEncodeError("ascii", s, 0, len(s), "ouch")
             ),
@@ -552,52 +552,52 @@
             UnicodeTranslateError("\u3042", 0, 1, "ouch")
         )
         # Use the correct exception
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors(
                 UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
             ("\\u3042", 1)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors(
                 UnicodeEncodeError("ascii", "\x00", 0, 1, "ouch")),
             ("\\x00", 1)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors(
                 UnicodeEncodeError("ascii", "\xff", 0, 1, "ouch")),
             ("\\xff", 1)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors(
                 UnicodeEncodeError("ascii", "\u0100", 0, 1, "ouch")),
             ("\\u0100", 1)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors(
                 UnicodeEncodeError("ascii", "\uffff", 0, 1, "ouch")),
             ("\\uffff", 1)
         )
         # 1 on UCS-4 builds, 2 on UCS-2
         len_wide = len("\U00010000")
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors(
                 UnicodeEncodeError("ascii", "\U00010000",
                                    0, len_wide, "ouch")),
             ("\\U00010000", len_wide)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors(
                 UnicodeEncodeError("ascii", "\U0010ffff",
                                    0, len_wide, "ouch")),
             ("\\U0010ffff", len_wide)
         )
         # Lone surrogates (regardless of unicode width)
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors(
                 UnicodeEncodeError("ascii", "\ud800", 0, 1, "ouch")),
             ("\\ud800", 1)
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors(
                 UnicodeEncodeError("ascii", "\udfff", 0, 1, "ouch")),
             ("\\udfff", 1)
@@ -630,14 +630,14 @@
                 )
 
     def test_lookup(self):
-        self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict"))
-        self.assertEquals(codecs.ignore_errors, codecs.lookup_error("ignore"))
-        self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict"))
-        self.assertEquals(
+        self.assertEqual(codecs.strict_errors, codecs.lookup_error("strict"))
+        self.assertEqual(codecs.ignore_errors, codecs.lookup_error("ignore"))
+        self.assertEqual(codecs.strict_errors, codecs.lookup_error("strict"))
+        self.assertEqual(
             codecs.xmlcharrefreplace_errors,
             codecs.lookup_error("xmlcharrefreplace")
         )
-        self.assertEquals(
+        self.assertEqual(
             codecs.backslashreplace_errors,
             codecs.lookup_error("backslashreplace")
         )
@@ -713,11 +713,11 @@
 
         # Valid negative position
         handler.pos = -1
-        self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?>0")
+        self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?>0")
 
         # Valid negative position
         handler.pos = -2
-        self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?><?>")
+        self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?><?>")
 
         # Negative position out of bounds
         handler.pos = -3
@@ -725,11 +725,11 @@
 
         # Valid positive position
         handler.pos = 1
-        self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?>0")
+        self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?>0")
 
         # Largest valid positive position (one beyond end of input)
         handler.pos = 2
-        self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?>")
+        self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?>")
 
         # Invalid positive position
         handler.pos = 3
@@ -737,7 +737,7 @@
 
         # Restart at the "0"
         handler.pos = 6
-        self.assertEquals(b"\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), "<?>0")
+        self.assertEqual(b"\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), "<?>0")
 
         class D(dict):
             def __getitem__(self, key):
@@ -767,11 +767,11 @@
 
         # Valid negative position
         handler.pos = -1
-        self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?>0")
+        self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?>0")
 
         # Valid negative position
         handler.pos = -2
-        self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?><?>")
+        self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?><?>")
 
         # Negative position out of bounds
         handler.pos = -3
@@ -779,11 +779,11 @@
 
         # Valid positive position
         handler.pos = 1
-        self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?>0")
+        self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?>0")
 
         # Largest valid positive position (one beyond end of input
         handler.pos = 2
-        self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?>")
+        self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?>")
 
         # Invalid positive position
         handler.pos = 3

Modified: python/branches/pep-3151/Lib/test/test_codecs.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_codecs.py	(original)
+++ python/branches/pep-3151/Lib/test/test_codecs.py	Sat Feb 26 08:16:32 2011
@@ -299,7 +299,7 @@
         # try to read it back
         s = io.BytesIO(d)
         f = reader(s)
-        self.assertEquals(f.read(), "spamspam")
+        self.assertEqual(f.read(), "spamspam")
 
     def test_badbom(self):
         s = io.BytesIO(4*b"\xff")
@@ -463,7 +463,7 @@
         # try to read it back
         s = io.BytesIO(d)
         f = reader(s)
-        self.assertEquals(f.read(), "spamspam")
+        self.assertEqual(f.read(), "spamspam")
 
     def test_badbom(self):
         s = io.BytesIO(b"\xff\xff")
@@ -544,6 +544,12 @@
         self.assertRaises(UnicodeDecodeError, codecs.utf_16_le_decode,
                           b"\xff", "strict", True)
 
+    def test_nonbmp(self):
+        self.assertEqual("\U00010203".encode(self.encoding),
+                         b'\x00\xd8\x03\xde')
+        self.assertEqual(b'\x00\xd8\x03\xde'.decode(self.encoding),
+                         "\U00010203")
+
 class UTF16BETest(ReadTest):
     encoding = "utf-16-be"
 
@@ -566,6 +572,12 @@
         self.assertRaises(UnicodeDecodeError, codecs.utf_16_be_decode,
                           b"\xff", "strict", True)
 
+    def test_nonbmp(self):
+        self.assertEqual("\U00010203".encode(self.encoding),
+                         b'\xd8\x00\xde\x03')
+        self.assertEqual(b'\xd8\x00\xde\x03'.decode(self.encoding),
+                         "\U00010203")
+
 class UTF8Test(ReadTest):
     encoding = "utf-8"
 
@@ -607,10 +619,10 @@
                          b'[?]')
 
     def test_surrogatepass_handler(self):
-        self.assertEquals("abc\ud800def".encode("utf-8", "surrogatepass"),
-                          b"abc\xed\xa0\x80def")
-        self.assertEquals(b"abc\xed\xa0\x80def".decode("utf-8", "surrogatepass"),
-                          "abc\ud800def")
+        self.assertEqual("abc\ud800def".encode("utf-8", "surrogatepass"),
+                         b"abc\xed\xa0\x80def")
+        self.assertEqual(b"abc\xed\xa0\x80def".decode("utf-8", "surrogatepass"),
+                         "abc\ud800def")
         self.assertTrue(codecs.lookup_error("surrogatepass"))
 
 class UTF7Test(ReadTest):
@@ -681,7 +693,7 @@
 
     def test_bug1601501(self):
         # SF bug #1601501: check that the codec works with a buffer
-        self.assertEquals(str(b"\xef\xbb\xbf", "utf-8-sig"), "")
+        self.assertEqual(str(b"\xef\xbb\xbf", "utf-8-sig"), "")
 
     def test_bom(self):
         d = codecs.getincrementaldecoder("utf-8-sig")()
@@ -734,7 +746,7 @@
 
 class EscapeDecodeTest(unittest.TestCase):
     def test_empty(self):
-        self.assertEquals(codecs.escape_decode(""), ("", 0))
+        self.assertEqual(codecs.escape_decode(""), ("", 0))
 
 class RecodingTest(unittest.TestCase):
     def test_recoding(self):
@@ -861,16 +873,16 @@
             # code produces only lower case. Converting just puny to
             # lower is also insufficient, since some of the input characters
             # are upper case.
-            self.assertEquals(
+            self.assertEqual(
                 str(uni.encode("punycode"), "ascii").lower(),
                 str(puny, "ascii").lower()
             )
 
     def test_decode(self):
         for uni, puny in punycode_testcases:
-            self.assertEquals(uni, puny.decode("punycode"))
+            self.assertEqual(uni, puny.decode("punycode"))
             puny = puny.decode("ascii").encode("ascii")
-            self.assertEquals(uni, puny.decode("punycode"))
+            self.assertEqual(uni, puny.decode("punycode"))
 
 class UnicodeInternalTest(unittest.TestCase):
     def test_bug1251300(self):
@@ -892,7 +904,7 @@
             for internal, uni in ok:
                 if sys.byteorder == "little":
                     internal = bytes(reversed(internal))
-                self.assertEquals(uni, internal.decode("unicode_internal"))
+                self.assertEqual(uni, internal.decode("unicode_internal"))
             for internal in not_ok:
                 if sys.byteorder == "little":
                     internal = bytes(reversed(internal))
@@ -904,10 +916,10 @@
             try:
                 b"\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal")
             except UnicodeDecodeError as ex:
-                self.assertEquals("unicode_internal", ex.encoding)
-                self.assertEquals(b"\x00\x00\x00\x00\x00\x11\x11\x00", ex.object)
-                self.assertEquals(4, ex.start)
-                self.assertEquals(8, ex.end)
+                self.assertEqual("unicode_internal", ex.encoding)
+                self.assertEqual(b"\x00\x00\x00\x00\x00\x11\x11\x00", ex.object)
+                self.assertEqual(4, ex.start)
+                self.assertEqual(8, ex.end)
             else:
                 self.fail()
 
@@ -919,15 +931,15 @@
             ignored = decoder(bytes("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]),
                                     "ascii"),
                               "UnicodeInternalTest")
-            self.assertEquals(("ab", 12), ignored)
+            self.assertEqual(("ab", 12), ignored)
 
     def test_encode_length(self):
         # Issue 3739
         encoder = codecs.getencoder("unicode_internal")
-        self.assertEquals(encoder("a")[1], 1)
-        self.assertEquals(encoder("\xe9\u0142")[1], 2)
+        self.assertEqual(encoder("a")[1], 1)
+        self.assertEqual(encoder("\xe9\u0142")[1], 2)
 
-        self.assertEquals(codecs.escape_encode(br'\x00')[1], 4)
+        self.assertEqual(codecs.escape_encode(br'\x00')[1], 4)
 
 # From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html
 nameprep_tests = [
@@ -1098,101 +1110,101 @@
             else:
                 prepped = str(prepped, "utf-8", "surrogatepass")
                 try:
-                    self.assertEquals(nameprep(orig), prepped)
+                    self.assertEqual(nameprep(orig), prepped)
                 except Exception as e:
                     raise support.TestFailed("Test 3.%d: %s" % (pos+1, str(e)))
 
 class IDNACodecTest(unittest.TestCase):
     def test_builtin_decode(self):
-        self.assertEquals(str(b"python.org", "idna"), "python.org")
-        self.assertEquals(str(b"python.org.", "idna"), "python.org.")
-        self.assertEquals(str(b"xn--pythn-mua.org", "idna"), "pyth\xf6n.org")
-        self.assertEquals(str(b"xn--pythn-mua.org.", "idna"), "pyth\xf6n.org.")
+        self.assertEqual(str(b"python.org", "idna"), "python.org")
+        self.assertEqual(str(b"python.org.", "idna"), "python.org.")
+        self.assertEqual(str(b"xn--pythn-mua.org", "idna"), "pyth\xf6n.org")
+        self.assertEqual(str(b"xn--pythn-mua.org.", "idna"), "pyth\xf6n.org.")
 
     def test_builtin_encode(self):
-        self.assertEquals("python.org".encode("idna"), b"python.org")
-        self.assertEquals("python.org.".encode("idna"), b"python.org.")
-        self.assertEquals("pyth\xf6n.org".encode("idna"), b"xn--pythn-mua.org")
-        self.assertEquals("pyth\xf6n.org.".encode("idna"), b"xn--pythn-mua.org.")
+        self.assertEqual("python.org".encode("idna"), b"python.org")
+        self.assertEqual("python.org.".encode("idna"), b"python.org.")
+        self.assertEqual("pyth\xf6n.org".encode("idna"), b"xn--pythn-mua.org")
+        self.assertEqual("pyth\xf6n.org.".encode("idna"), b"xn--pythn-mua.org.")
 
     def test_stream(self):
         r = codecs.getreader("idna")(io.BytesIO(b"abc"))
         r.read(3)
-        self.assertEquals(r.read(), "")
+        self.assertEqual(r.read(), "")
 
     def test_incremental_decode(self):
-        self.assertEquals(
+        self.assertEqual(
             "".join(codecs.iterdecode((bytes([c]) for c in b"python.org"), "idna")),
             "python.org"
         )
-        self.assertEquals(
+        self.assertEqual(
             "".join(codecs.iterdecode((bytes([c]) for c in b"python.org."), "idna")),
             "python.org."
         )
-        self.assertEquals(
+        self.assertEqual(
             "".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")),
             "pyth\xf6n.org."
         )
-        self.assertEquals(
+        self.assertEqual(
             "".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")),
             "pyth\xf6n.org."
         )
 
         decoder = codecs.getincrementaldecoder("idna")()
-        self.assertEquals(decoder.decode(b"xn--xam", ), "")
-        self.assertEquals(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
-        self.assertEquals(decoder.decode(b"rg"), "")
-        self.assertEquals(decoder.decode(b"", True), "org")
+        self.assertEqual(decoder.decode(b"xn--xam", ), "")
+        self.assertEqual(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
+        self.assertEqual(decoder.decode(b"rg"), "")
+        self.assertEqual(decoder.decode(b"", True), "org")
 
         decoder.reset()
-        self.assertEquals(decoder.decode(b"xn--xam", ), "")
-        self.assertEquals(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
-        self.assertEquals(decoder.decode(b"rg."), "org.")
-        self.assertEquals(decoder.decode(b"", True), "")
+        self.assertEqual(decoder.decode(b"xn--xam", ), "")
+        self.assertEqual(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
+        self.assertEqual(decoder.decode(b"rg."), "org.")
+        self.assertEqual(decoder.decode(b"", True), "")
 
     def test_incremental_encode(self):
-        self.assertEquals(
+        self.assertEqual(
             b"".join(codecs.iterencode("python.org", "idna")),
             b"python.org"
         )
-        self.assertEquals(
+        self.assertEqual(
             b"".join(codecs.iterencode("python.org.", "idna")),
             b"python.org."
         )
-        self.assertEquals(
+        self.assertEqual(
             b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")),
             b"xn--pythn-mua.org."
         )
-        self.assertEquals(
+        self.assertEqual(
             b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")),
             b"xn--pythn-mua.org."
         )
 
         encoder = codecs.getincrementalencoder("idna")()
-        self.assertEquals(encoder.encode("\xe4x"), b"")
-        self.assertEquals(encoder.encode("ample.org"), b"xn--xample-9ta.")
-        self.assertEquals(encoder.encode("", True), b"org")
+        self.assertEqual(encoder.encode("\xe4x"), b"")
+        self.assertEqual(encoder.encode("ample.org"), b"xn--xample-9ta.")
+        self.assertEqual(encoder.encode("", True), b"org")
 
         encoder.reset()
-        self.assertEquals(encoder.encode("\xe4x"), b"")
-        self.assertEquals(encoder.encode("ample.org."), b"xn--xample-9ta.org.")
-        self.assertEquals(encoder.encode("", True), b"")
+        self.assertEqual(encoder.encode("\xe4x"), b"")
+        self.assertEqual(encoder.encode("ample.org."), b"xn--xample-9ta.org.")
+        self.assertEqual(encoder.encode("", True), b"")
 
 class CodecsModuleTest(unittest.TestCase):
 
     def test_decode(self):
-        self.assertEquals(codecs.decode(b'\xe4\xf6\xfc', 'latin-1'),
-                          '\xe4\xf6\xfc')
+        self.assertEqual(codecs.decode(b'\xe4\xf6\xfc', 'latin-1'),
+                         '\xe4\xf6\xfc')
         self.assertRaises(TypeError, codecs.decode)
-        self.assertEquals(codecs.decode(b'abc'), 'abc')
+        self.assertEqual(codecs.decode(b'abc'), 'abc')
         self.assertRaises(UnicodeDecodeError, codecs.decode, b'\xff', 'ascii')
 
     def test_encode(self):
-        self.assertEquals(codecs.encode('\xe4\xf6\xfc', 'latin-1'),
-                          b'\xe4\xf6\xfc')
+        self.assertEqual(codecs.encode('\xe4\xf6\xfc', 'latin-1'),
+                         b'\xe4\xf6\xfc')
         self.assertRaises(TypeError, codecs.encode)
         self.assertRaises(LookupError, codecs.encode, "foo", "__spam__")
-        self.assertEquals(codecs.encode('abc'), b'abc')
+        self.assertEqual(codecs.encode('abc'), b'abc')
         self.assertRaises(UnicodeEncodeError, codecs.encode, '\xffff', 'ascii')
 
     def test_register(self):
@@ -1228,19 +1240,19 @@
 
     def test_readlines(self):
         f = self.reader(self.stream)
-        self.assertEquals(f.readlines(), ['\ud55c\n', '\uae00'])
+        self.assertEqual(f.readlines(), ['\ud55c\n', '\uae00'])
 
 class EncodedFileTest(unittest.TestCase):
 
     def test_basic(self):
         f = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80')
         ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8')
-        self.assertEquals(ef.read(), b'\\\xd5\n\x00\x00\xae')
+        self.assertEqual(ef.read(), b'\\\xd5\n\x00\x00\xae')
 
         f = io.BytesIO()
-        ef = codecs.EncodedFile(f, 'utf-8', 'latin1')
+        ef = codecs.EncodedFile(f, 'utf-8', 'latin-1')
         ef.write(b'\xc3\xbc')
-        self.assertEquals(f.getvalue(), b'\xfc')
+        self.assertEqual(f.getvalue(), b'\xfc')
 
 all_unicode_encodings = [
     "ascii",
@@ -1495,33 +1507,33 @@
 
 class CharmapTest(unittest.TestCase):
     def test_decode_with_string_map(self):
-        self.assertEquals(
+        self.assertEqual(
             codecs.charmap_decode(b"\x00\x01\x02", "strict", "abc"),
             ("abc", 3)
         )
 
-        self.assertEquals(
+        self.assertEqual(
             codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab"),
             ("ab\ufffd", 3)
         )
 
-        self.assertEquals(
+        self.assertEqual(
             codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab\ufffe"),
             ("ab\ufffd", 3)
         )
 
-        self.assertEquals(
+        self.assertEqual(
             codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab"),
             ("ab", 3)
         )
 
-        self.assertEquals(
+        self.assertEqual(
             codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab\ufffe"),
             ("ab", 3)
         )
 
         allbytes = bytes(range(256))
-        self.assertEquals(
+        self.assertEqual(
             codecs.charmap_decode(allbytes, "ignore", ""),
             ("", len(allbytes))
         )
@@ -1530,14 +1542,14 @@
     def test_encodedfile(self):
         f = io.BytesIO(b"\xc3\xbc")
         with codecs.EncodedFile(f, "latin-1", "utf-8") as ef:
-            self.assertEquals(ef.read(), b"\xfc")
+            self.assertEqual(ef.read(), b"\xfc")
 
     def test_streamreaderwriter(self):
         f = io.BytesIO(b"\xc3\xbc")
         info = codecs.lookup("utf-8")
         with codecs.StreamReaderWriter(f, info.streamreader,
                                        info.streamwriter, 'strict') as srw:
-            self.assertEquals(srw.read(), "\xfc")
+            self.assertEqual(srw.read(), "\xfc")
 
 class TypesTest(unittest.TestCase):
     def test_decode_unicode(self):
@@ -1564,10 +1576,10 @@
     def test_unicode_escape(self):
         # Escape-decoding an unicode string is supported ang gives the same
         # result as decoding the equivalent ASCII bytes string.
-        self.assertEquals(codecs.unicode_escape_decode(r"\u1234"), ("\u1234", 6))
-        self.assertEquals(codecs.unicode_escape_decode(br"\u1234"), ("\u1234", 6))
-        self.assertEquals(codecs.raw_unicode_escape_decode(r"\u1234"), ("\u1234", 6))
-        self.assertEquals(codecs.raw_unicode_escape_decode(br"\u1234"), ("\u1234", 6))
+        self.assertEqual(codecs.unicode_escape_decode(r"\u1234"), ("\u1234", 6))
+        self.assertEqual(codecs.unicode_escape_decode(br"\u1234"), ("\u1234", 6))
+        self.assertEqual(codecs.raw_unicode_escape_decode(r"\u1234"), ("\u1234", 6))
+        self.assertEqual(codecs.raw_unicode_escape_decode(br"\u1234"), ("\u1234", 6))
 
 class SurrogateEscapeTest(unittest.TestCase):
 
@@ -1599,7 +1611,7 @@
 
     def test_latin1(self):
         # Issue6373
-        self.assertEqual("\udce4\udceb\udcef\udcf6\udcfc".encode("latin1", "surrogateescape"),
+        self.assertEqual("\udce4\udceb\udcef\udcf6\udcfc".encode("latin-1", "surrogateescape"),
                          b"\xe4\xeb\xef\xf6\xfc")
 
 
@@ -1618,27 +1630,27 @@
                 f.write(data)
                 f.write(data)
                 f.seek(0)
-                self.assertEquals(f.read(), data * 2)
+                self.assertEqual(f.read(), data * 2)
                 f.seek(0)
-                self.assertEquals(f.read(), data * 2)
+                self.assertEqual(f.read(), data * 2)
 
             # Check that the BOM is written after a seek(0)
             with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f:
                 f.write(data[0])
-                self.assertNotEquals(f.tell(), 0)
+                self.assertNotEqual(f.tell(), 0)
                 f.seek(0)
                 f.write(data)
                 f.seek(0)
-                self.assertEquals(f.read(), data)
+                self.assertEqual(f.read(), data)
 
             # (StreamWriter) Check that the BOM is written after a seek(0)
             with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f:
                 f.writer.write(data[0])
-                self.assertNotEquals(f.writer.tell(), 0)
+                self.assertNotEqual(f.writer.tell(), 0)
                 f.writer.seek(0)
                 f.writer.write(data)
                 f.seek(0)
-                self.assertEquals(f.read(), data)
+                self.assertEqual(f.read(), data)
 
             # Check that the BOM is not written after a seek() at a position
             # different than the start
@@ -1647,7 +1659,7 @@
                 f.seek(f.tell())
                 f.write(data)
                 f.seek(0)
-                self.assertEquals(f.read(), data * 2)
+                self.assertEqual(f.read(), data * 2)
 
             # (StreamWriter) Check that the BOM is not written after a seek()
             # at a position different than the start
@@ -1656,7 +1668,55 @@
                 f.writer.seek(f.writer.tell())
                 f.writer.write(data)
                 f.seek(0)
-                self.assertEquals(f.read(), data * 2)
+                self.assertEqual(f.read(), data * 2)
+
+
+bytes_transform_encodings = [
+    "base64_codec",
+    "uu_codec",
+    "quopri_codec",
+    "hex_codec",
+]
+try:
+    import zlib
+except ImportError:
+    pass
+else:
+    bytes_transform_encodings.append("zlib_codec")
+try:
+    import bz2
+except ImportError:
+    pass
+else:
+    bytes_transform_encodings.append("bz2_codec")
+
+class TransformCodecTest(unittest.TestCase):
+
+    def test_basics(self):
+        binput = bytes(range(256))
+        for encoding in bytes_transform_encodings:
+            # generic codecs interface
+            (o, size) = codecs.getencoder(encoding)(binput)
+            self.assertEqual(size, len(binput))
+            (i, size) = codecs.getdecoder(encoding)(o)
+            self.assertEqual(size, len(o))
+            self.assertEqual(i, binput)
+
+    def test_read(self):
+        for encoding in bytes_transform_encodings:
+            sin = codecs.encode(b"\x80", encoding)
+            reader = codecs.getreader(encoding)(io.BytesIO(sin))
+            sout = reader.read()
+            self.assertEqual(sout, b"\x80")
+
+    def test_readline(self):
+        for encoding in bytes_transform_encodings:
+            if encoding in ['uu_codec', 'zlib_codec']:
+                continue
+            sin = codecs.encode(b"\x80", encoding)
+            reader = codecs.getreader(encoding)(io.BytesIO(sin))
+            sout = reader.readline()
+            self.assertEqual(sout, b"\x80")
 
 
 def test_main():
@@ -1686,6 +1746,7 @@
         TypesTest,
         SurrogateEscapeTest,
         BomTest,
+        TransformCodecTest,
     )
 
 

Modified: python/branches/pep-3151/Lib/test/test_codeop.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_codeop.py	(original)
+++ python/branches/pep-3151/Lib/test/test_codeop.py	Sat Feb 26 08:16:32 2011
@@ -37,14 +37,14 @@
                 ctx = {'a': 2}
                 d = { 'value': eval(code,ctx) }
                 r = { 'value': eval(str,ctx) }
-            self.assertEquals(unify_callables(r),unify_callables(d))
+            self.assertEqual(unify_callables(r),unify_callables(d))
         else:
             expected = compile(str, "<input>", symbol, PyCF_DONT_IMPLY_DEDENT)
-            self.assertEquals( compile_command(str, "<input>", symbol), expected)
+            self.assertEqual(compile_command(str, "<input>", symbol), expected)
 
     def assertIncomplete(self, str, symbol='single'):
         '''succeed iff str is the start of a valid piece of code'''
-        self.assertEquals( compile_command(str, symbol=symbol), None)
+        self.assertEqual(compile_command(str, symbol=symbol), None)
 
     def assertInvalid(self, str, symbol='single', is_syntax=1):
         '''succeed iff str is the start of an invalid piece of code'''
@@ -61,12 +61,12 @@
 
         # special case
         if not is_jython:
-            self.assertEquals(compile_command(""),
-                            compile("pass", "<input>", 'single',
-                                    PyCF_DONT_IMPLY_DEDENT))
-            self.assertEquals(compile_command("\n"),
-                            compile("pass", "<input>", 'single',
-                                    PyCF_DONT_IMPLY_DEDENT))
+            self.assertEqual(compile_command(""),
+                             compile("pass", "<input>", 'single',
+                                     PyCF_DONT_IMPLY_DEDENT))
+            self.assertEqual(compile_command("\n"),
+                             compile("pass", "<input>", 'single',
+                                     PyCF_DONT_IMPLY_DEDENT))
         else:
             av("")
             av("\n")
@@ -290,10 +290,10 @@
         ai("[i for i in range(10)] = (1, 2, 3)")
 
     def test_filename(self):
-        self.assertEquals(compile_command("a = 1\n", "abc").co_filename,
-                          compile("a = 1\n", "abc", 'single').co_filename)
-        self.assertNotEquals(compile_command("a = 1\n", "abc").co_filename,
-                             compile("a = 1\n", "def", 'single').co_filename)
+        self.assertEqual(compile_command("a = 1\n", "abc").co_filename,
+                         compile("a = 1\n", "abc", 'single').co_filename)
+        self.assertNotEqual(compile_command("a = 1\n", "abc").co_filename,
+                            compile("a = 1\n", "def", 'single').co_filename)
 
 
 def test_main():

Modified: python/branches/pep-3151/Lib/test/test_collections.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_collections.py	(original)
+++ python/branches/pep-3151/Lib/test/test_collections.py	Sat Feb 26 08:16:32 2011
@@ -3,19 +3,112 @@
 import unittest, doctest, operator
 import inspect
 from test import support
-from collections import namedtuple, Counter, OrderedDict
+from collections import namedtuple, Counter, OrderedDict, _count_elements
 from test import mapping_tests
 import pickle, copy
 from random import randrange, shuffle
 import keyword
 import re
 import sys
-from collections import Hashable, Iterable, Iterator
-from collections import Sized, Container, Callable
-from collections import Set, MutableSet
-from collections import Mapping, MutableMapping, KeysView, ItemsView, UserDict
-from collections import Sequence, MutableSequence
-from collections import ByteString
+from collections import UserDict
+from collections import ChainMap
+from collections.abc import Hashable, Iterable, Iterator
+from collections.abc import Sized, Container, Callable
+from collections.abc import Set, MutableSet
+from collections.abc import Mapping, MutableMapping, KeysView, ItemsView
+from collections.abc import Sequence, MutableSequence
+from collections.abc import ByteString
+
+
+################################################################################
+### ChainMap (helper class for configparser and the string module)
+################################################################################
+
+class TestChainMap(unittest.TestCase):
+
+    def test_basics(self):
+        c = ChainMap()
+        c['a'] = 1
+        c['b'] = 2
+        d = c.new_child()
+        d['b'] = 20
+        d['c'] = 30
+        self.assertEqual(d.maps, [{'b':20, 'c':30}, {'a':1, 'b':2}])  # check internal state
+        self.assertEqual(d.items(), dict(a=1, b=20, c=30).items())    # check items/iter/getitem
+        self.assertEqual(len(d), 3)                                   # check len
+        for key in 'abc':                                             # check contains
+            self.assertIn(key, d)
+        for k, v in dict(a=1, b=20, c=30, z=100).items():             # check get
+            self.assertEqual(d.get(k, 100), v)
+
+        del d['b']                                                    # unmask a value
+        self.assertEqual(d.maps, [{'c':30}, {'a':1, 'b':2}])          # check internal state
+        self.assertEqual(d.items(), dict(a=1, b=2, c=30).items())     # check items/iter/getitem
+        self.assertEqual(len(d), 3)                                   # check len
+        for key in 'abc':                                             # check contains
+            self.assertIn(key, d)
+        for k, v in dict(a=1, b=2, c=30, z=100).items():              # check get
+            self.assertEqual(d.get(k, 100), v)
+        self.assertIn(repr(d), [                                      # check repr
+            type(d).__name__ + "({'c': 30}, {'a': 1, 'b': 2})",
+            type(d).__name__ + "({'c': 30}, {'b': 2, 'a': 1})"
+        ])
+
+        for e in d.copy(), copy.copy(d):                               # check shallow copies
+            self.assertEqual(d, e)
+            self.assertEqual(d.maps, e.maps)
+            self.assertIsNot(d, e)
+            self.assertIsNot(d.maps[0], e.maps[0])
+            for m1, m2 in zip(d.maps[1:], e.maps[1:]):
+                self.assertIs(m1, m2)
+
+        for e in [pickle.loads(pickle.dumps(d)),
+                  copy.deepcopy(d),
+                  eval(repr(d))
+                ]:                                                    # check deep copies
+            self.assertEqual(d, e)
+            self.assertEqual(d.maps, e.maps)
+            self.assertIsNot(d, e)
+            for m1, m2 in zip(d.maps, e.maps):
+                self.assertIsNot(m1, m2, e)
+
+        d.new_child()
+        d['b'] = 5
+        self.assertEqual(d.maps, [{'b': 5}, {'c':30}, {'a':1, 'b':2}])
+        self.assertEqual(d.parents.maps, [{'c':30}, {'a':1, 'b':2}])   # check parents
+        self.assertEqual(d['b'], 5)                                    # find first in chain
+        self.assertEqual(d.parents['b'], 2)                            # look beyond maps[0]
+
+    def test_contructor(self):
+        self.assertEqual(ChainedContext().maps, [{}])                  # no-args --> one new dict
+        self.assertEqual(ChainMap({1:2}).maps, [{1:2}])                # 1 arg --> list
+
+    def test_missing(self):
+        class DefaultChainMap(ChainMap):
+            def __missing__(self, key):
+                return 999
+        d = DefaultChainMap(dict(a=1, b=2), dict(b=20, c=30))
+        for k, v in dict(a=1, b=2, c=30, d=999).items():
+            self.assertEqual(d[k], v)                                  # check __getitem__ w/missing
+        for k, v in dict(a=1, b=2, c=30, d=77).items():
+            self.assertEqual(d.get(k, 77), v)                          # check get() w/ missing
+        for k, v in dict(a=True, b=True, c=True, d=False).items():
+            self.assertEqual(k in d, v)                                # check __contains__ w/missing
+        self.assertEqual(d.pop('a', 1001), 1, d)
+        self.assertEqual(d.pop('a', 1002), 1002)                       # check pop() w/missing
+        self.assertEqual(d.popitem(), ('b', 2))                        # check popitem() w/missing
+        with self.assertRaises(KeyError):
+            d.popitem()
+
+    def test_dict_coercion(self):
+        d = ChainMap(dict(a=1, b=2), dict(b=20, c=30))
+        self.assertEqual(dict(d), dict(a=1, b=2, c=30))
+        self.assertEqual(dict(d.items()), dict(a=1, b=2, c=30))
+
+
+################################################################################
+### Named Tuples
+################################################################################
 
 TestNT = namedtuple('TestNT', 'x y z')    # type used for pickle tests
 
@@ -228,6 +321,10 @@
         self.assertEqual(repr(B(1)), 'B(x=1)')
 
 
+################################################################################
+### Abstract Base Classes
+################################################################################
+
 class ABCTestCase(unittest.TestCase):
 
     def validate_abstract_methods(self, abc, *names):
@@ -356,8 +453,14 @@
         for x in samples:
             self.assertIsInstance(x, Iterator)
             self.assertTrue(issubclass(type(x), Iterator), repr(type(x)))
-        self.validate_abstract_methods(Iterator, '__next__')
-        self.validate_isinstance(Iterator, '__next__')
+        self.validate_abstract_methods(Iterator, '__next__', '__iter__')
+
+        # Issue 10565
+        class NextOnly:
+            def __next__(self):
+                yield 1
+                raise StopIteration
+        self.assertNotIsInstance(NextOnly(), Iterator)
 
     def test_Sized(self):
         non_samples = [None, 42, 3.14, 1j,
@@ -501,7 +604,7 @@
 
     def test_issue_4920(self):
         # MutableSet.pop() method did not work
-        class MySet(collections.MutableSet):
+        class MySet(MutableSet):
             __slots__=['__s']
             def __init__(self,items=None):
                 if items is None:
@@ -547,7 +650,7 @@
             self.assertTrue(issubclass(sample, Mapping))
         self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__',
             '__getitem__')
-        class MyMapping(collections.Mapping):
+        class MyMapping(Mapping):
             def __len__(self):
                 return 0
             def __getitem__(self, i):
@@ -619,6 +722,11 @@
         self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
             '__len__', '__getitem__', '__setitem__', '__delitem__', 'insert')
 
+
+################################################################################
+### Counter
+################################################################################
+
 class TestCounter(unittest.TestCase):
 
     def test_basics(self):
@@ -701,9 +809,9 @@
                     ]):
             msg = (i, dup, words)
             self.assertTrue(dup is not words)
-            self.assertEquals(dup, words)
-            self.assertEquals(len(dup), len(words))
-            self.assertEquals(type(dup), type(words))
+            self.assertEqual(dup, words)
+            self.assertEqual(len(dup), len(words))
+            self.assertEqual(type(dup), type(words))
 
     def test_conversions(self):
         # Convert to: set, list, dict
@@ -769,6 +877,24 @@
         c.subtract('aaaabbcce')
         self.assertEqual(c, Counter(a=-1, b=0, c=-1, d=1, e=-1))
 
+    def test_helper_function(self):
+        # two paths, one for real dicts and one for other mappings
+        elems = list('abracadabra')
+
+        d = dict()
+        _count_elements(d, elems)
+        self.assertEqual(d, {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1})
+
+        m = OrderedDict()
+        _count_elements(m, elems)
+        self.assertEqual(m,
+             OrderedDict([('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]))
+
+
+################################################################################
+### OrderedDict
+################################################################################
+
 class TestOrderedDict(unittest.TestCase):
 
     def test_init(self):
@@ -828,6 +954,10 @@
         self.assertEqual(list(d.items()),
             [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)])
 
+    def test_abc(self):
+        self.assertIsInstance(OrderedDict(), MutableMapping)
+        self.assertTrue(issubclass(OrderedDict, MutableMapping))
+
     def test_clear(self):
         pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
         shuffle(pairs)
@@ -886,6 +1016,17 @@
         self.assertEqual(len(od), 0)
         self.assertEqual(od.pop(k, 12345), 12345)
 
+        # make sure pop still works when __missing__ is defined
+        class Missing(OrderedDict):
+            def __missing__(self, key):
+                return 0
+        m = Missing(a=1)
+        self.assertEqual(m.pop('b', 5), 5)
+        self.assertEqual(m.pop('a', 6), 1)
+        self.assertEqual(m.pop('a', 6), 6)
+        with self.assertRaises(KeyError):
+            m.pop('a')
+
     def test_equality(self):
         pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
         shuffle(pairs)
@@ -922,10 +1063,10 @@
                     OrderedDict(od),
                     ]):
             self.assertTrue(dup is not od)
-            self.assertEquals(dup, od)
-            self.assertEquals(list(dup.items()), list(od.items()))
-            self.assertEquals(len(dup), len(od))
-            self.assertEquals(type(dup), type(od))
+            self.assertEqual(dup, od)
+            self.assertEqual(list(dup.items()), list(od.items()))
+            self.assertEqual(len(dup), len(od))
+            self.assertEqual(type(dup), type(od))
 
     def test_yaml_linkage(self):
         # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.
@@ -970,6 +1111,12 @@
         # make sure 'x' is added to the end
         self.assertEqual(list(od.items())[-1], ('x', 10))
 
+        # make sure setdefault still works when __missing__ is defined
+        class Missing(OrderedDict):
+            def __missing__(self, key):
+                return 0
+        self.assertEqual(Missing().setdefault(5, 9), 9)
+
     def test_reinsert(self):
         # Given insert a, insert b, delete a, re-insert a,
         # verify that a is now later than b.
@@ -1000,6 +1147,14 @@
         od = OrderedDict(**d)
         self.assertGreater(sys.getsizeof(od), sys.getsizeof(d))
 
+    def test_override_update(self):
+        # Verify that subclasses can override update() without breaking __init__()
+        class MyOD(OrderedDict):
+            def update(self, *args, **kwds):
+                raise Exception()
+        items = [('a', 1), ('c', 3), ('b', 2)]
+        self.assertEqual(list(MyOD(items).items()), items)
+
 class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
     type2test = OrderedDict
 
@@ -1018,6 +1173,10 @@
         self.assertRaises(KeyError, d.popitem)
 
 
+################################################################################
+### Run tests
+################################################################################
+
 import doctest, collections
 
 def test_main(verbose=None):

Modified: python/branches/pep-3151/Lib/test/test_compileall.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_compileall.py	(original)
+++ python/branches/pep-3151/Lib/test/test_compileall.py	Sat Feb 26 08:16:32 2011
@@ -7,10 +7,11 @@
 import struct
 import subprocess
 import tempfile
+import time
 import unittest
 import io
 
-from test import support
+from test import support, script_helper
 
 class CompileallTests(unittest.TestCase):
 
@@ -23,6 +24,10 @@
         self.source_path2 = os.path.join(self.directory, '_test2.py')
         self.bc_path2 = imp.cache_from_source(self.source_path2)
         shutil.copyfile(self.source_path, self.source_path2)
+        self.subdirectory = os.path.join(self.directory, '_subdir')
+        os.mkdir(self.subdirectory)
+        self.source_path3 = os.path.join(self.subdirectory, '_test3.py')
+        shutil.copyfile(self.source_path, self.source_path3)
 
     def tearDown(self):
         shutil.rmtree(self.directory)
@@ -87,6 +92,21 @@
         compileall.compile_file(data_file)
         self.assertFalse(os.path.exists(os.path.join(data_dir, '__pycache__')))
 
+    def test_optimize(self):
+        # make sure compiling with different optimization settings than the
+        # interpreter's creates the correct file names
+        optimize = 1 if __debug__ else 0
+        compileall.compile_dir(self.directory, quiet=True, optimize=optimize)
+        cached = imp.cache_from_source(self.source_path,
+                                       debug_override=not optimize)
+        self.assertTrue(os.path.isfile(cached))
+        cached2 = imp.cache_from_source(self.source_path2,
+                                       debug_override=not optimize)
+        self.assertTrue(os.path.isfile(cached2))
+        cached3 = imp.cache_from_source(self.source_path3,
+                                       debug_override=not optimize)
+        self.assertTrue(os.path.isfile(cached3))
+
 
 class EncodingTest(unittest.TestCase):
     """Issue 6716: compileall should escape source code when printing errors
@@ -112,78 +132,221 @@
 
 
 class CommandLineTests(unittest.TestCase):
-    """Test some aspects of compileall's CLI."""
+    """Test compileall's CLI."""
+
+    def assertRunOK(self, *args, **env_vars):
+        rc, out, err = script_helper.assert_python_ok(
+                        '-S', '-m', 'compileall', *args, **env_vars)
+        self.assertEqual(b'', err)
+        return out
+
+    def assertRunNotOK(self, *args, **env_vars):
+        rc, out, err = script_helper.assert_python_failure(
+                        '-S', '-m', 'compileall', *args, **env_vars)
+        return rc, out, err
+
+    def assertCompiled(self, fn):
+        self.assertTrue(os.path.exists(imp.cache_from_source(fn)))
+
+    def assertNotCompiled(self, fn):
+        self.assertFalse(os.path.exists(imp.cache_from_source(fn)))
 
     def setUp(self):
         self.addCleanup(self._cleanup)
         self.directory = tempfile.mkdtemp()
         self.pkgdir = os.path.join(self.directory, 'foo')
         os.mkdir(self.pkgdir)
-        # Touch the __init__.py and a package module.
-        with open(os.path.join(self.pkgdir, '__init__.py'), 'w'):
-            pass
-        with open(os.path.join(self.pkgdir, 'bar.py'), 'w'):
-            pass
-        sys.path.insert(0, self.directory)
+        self.pkgdir_cachedir = os.path.join(self.pkgdir, '__pycache__')
+        # Create the __init__.py and a package module.
+        self.initfn = script_helper.make_script(self.pkgdir, '__init__', '')
+        self.barfn = script_helper.make_script(self.pkgdir, 'bar', '')
 
     def _cleanup(self):
         support.rmtree(self.directory)
-        assert sys.path[0] == self.directory, 'Missing path'
-        del sys.path[0]
+
+    def test_no_args_compiles_path(self):
+        # Note that -l is implied for the no args case.
+        bazfn = script_helper.make_script(self.directory, 'baz', '')
+        self.assertRunOK(PYTHONPATH=self.directory)
+        self.assertCompiled(bazfn)
+        self.assertNotCompiled(self.initfn)
+        self.assertNotCompiled(self.barfn)
 
     # Ensure that the default behavior of compileall's CLI is to create
     # PEP 3147 pyc/pyo files.
     for name, ext, switch in [
         ('normal', 'pyc', []),
         ('optimize', 'pyo', ['-O']),
-        ('doubleoptimize', 'pyo', ['-OO'])
+        ('doubleoptimize', 'pyo', ['-OO']),
     ]:
         def f(self, ext=ext, switch=switch):
-            retcode = subprocess.call(
-                [sys.executable] + switch +
-                ['-m', 'compileall', '-q', self.pkgdir])
-            self.assertEqual(retcode, 0)
+            script_helper.assert_python_ok(*(switch +
+                ['-m', 'compileall', '-q', self.pkgdir]))
             # Verify the __pycache__ directory contents.
-            cachedir = os.path.join(self.pkgdir, '__pycache__')
-            self.assertTrue(os.path.exists(cachedir))
+            self.assertTrue(os.path.exists(self.pkgdir_cachedir))
             expected = sorted(base.format(imp.get_tag(), ext) for base in
                               ('__init__.{}.{}', 'bar.{}.{}'))
-            self.assertEqual(sorted(os.listdir(cachedir)), expected)
+            self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
             # Make sure there are no .pyc files in the source directory.
-            self.assertFalse([pyc_file for pyc_file in os.listdir(self.pkgdir)
-                              if pyc_file.endswith(ext)])
+            self.assertFalse([fn for fn in os.listdir(self.pkgdir)
+                              if fn.endswith(ext)])
         locals()['test_pep3147_paths_' + name] = f
 
     def test_legacy_paths(self):
         # Ensure that with the proper switch, compileall leaves legacy
         # pyc/pyo files, and no __pycache__ directory.
-        retcode = subprocess.call(
-            (sys.executable, '-m', 'compileall', '-b', '-q', self.pkgdir))
-        self.assertEqual(retcode, 0)
+        self.assertRunOK('-b', '-q', self.pkgdir)
         # Verify the __pycache__ directory contents.
-        cachedir = os.path.join(self.pkgdir, '__pycache__')
-        self.assertFalse(os.path.exists(cachedir))
+        self.assertFalse(os.path.exists(self.pkgdir_cachedir))
         expected = sorted(['__init__.py', '__init__.pyc', 'bar.py', 'bar.pyc'])
         self.assertEqual(sorted(os.listdir(self.pkgdir)), expected)
 
     def test_multiple_runs(self):
         # Bug 8527 reported that multiple calls produced empty
         # __pycache__/__pycache__ directories.
-        retcode = subprocess.call(
-            (sys.executable, '-m', 'compileall', '-q', self.pkgdir))
-        self.assertEqual(retcode, 0)
+        self.assertRunOK('-q', self.pkgdir)
         # Verify the __pycache__ directory contents.
-        cachedir = os.path.join(self.pkgdir, '__pycache__')
-        self.assertTrue(os.path.exists(cachedir))
-        cachecachedir = os.path.join(cachedir, '__pycache__')
+        self.assertTrue(os.path.exists(self.pkgdir_cachedir))
+        cachecachedir = os.path.join(self.pkgdir_cachedir, '__pycache__')
         self.assertFalse(os.path.exists(cachecachedir))
         # Call compileall again.
-        retcode = subprocess.call(
-            (sys.executable, '-m', 'compileall', '-q', self.pkgdir))
-        self.assertEqual(retcode, 0)
-        self.assertTrue(os.path.exists(cachedir))
+        self.assertRunOK('-q', self.pkgdir)
+        self.assertTrue(os.path.exists(self.pkgdir_cachedir))
         self.assertFalse(os.path.exists(cachecachedir))
 
+    def test_force(self):
+        self.assertRunOK('-q', self.pkgdir)
+        pycpath = imp.cache_from_source(self.barfn)
+        # set atime/mtime backward to avoid file timestamp resolution issues
+        os.utime(pycpath, (time.time()-60,)*2)
+        mtime = os.stat(pycpath).st_mtime
+        # without force, no recompilation
+        self.assertRunOK('-q', self.pkgdir)
+        mtime2 = os.stat(pycpath).st_mtime
+        self.assertEqual(mtime, mtime2)
+        # now force it.
+        self.assertRunOK('-q', '-f', self.pkgdir)
+        mtime2 = os.stat(pycpath).st_mtime
+        self.assertNotEqual(mtime, mtime2)
+
+    def test_recursion_control(self):
+        subpackage = os.path.join(self.pkgdir, 'spam')
+        os.mkdir(subpackage)
+        subinitfn = script_helper.make_script(subpackage, '__init__', '')
+        hamfn = script_helper.make_script(subpackage, 'ham', '')
+        self.assertRunOK('-q', '-l', self.pkgdir)
+        self.assertNotCompiled(subinitfn)
+        self.assertFalse(os.path.exists(os.path.join(subpackage, '__pycache__')))
+        self.assertRunOK('-q', self.pkgdir)
+        self.assertCompiled(subinitfn)
+        self.assertCompiled(hamfn)
+
+    def test_quiet(self):
+        noisy = self.assertRunOK(self.pkgdir)
+        quiet = self.assertRunOK('-q', self.pkgdir)
+        self.assertNotEqual(b'', noisy)
+        self.assertEqual(b'', quiet)
+
+    def test_regexp(self):
+        self.assertRunOK('-q', '-x', 'ba.*', self.pkgdir)
+        self.assertNotCompiled(self.barfn)
+        self.assertCompiled(self.initfn)
+
+    def test_multiple_dirs(self):
+        pkgdir2 = os.path.join(self.directory, 'foo2')
+        os.mkdir(pkgdir2)
+        init2fn = script_helper.make_script(pkgdir2, '__init__', '')
+        bar2fn = script_helper.make_script(pkgdir2, 'bar2', '')
+        self.assertRunOK('-q', self.pkgdir, pkgdir2)
+        self.assertCompiled(self.initfn)
+        self.assertCompiled(self.barfn)
+        self.assertCompiled(init2fn)
+        self.assertCompiled(bar2fn)
+
+    def test_d_takes_exactly_one_dir(self):
+        rc, out, err = self.assertRunNotOK('-d', 'foo')
+        self.assertEqual(out, b'')
+        self.assertRegex(err, b'-d')
+        rc, out, err = self.assertRunNotOK('-d', 'foo', 'bar')
+        self.assertEqual(out, b'')
+        self.assertRegex(err, b'-d')
+
+    def test_d_compile_error(self):
+        script_helper.make_script(self.pkgdir, 'crunchyfrog', 'bad(syntax')
+        rc, out, err = self.assertRunNotOK('-q', '-d', 'dinsdale', self.pkgdir)
+        self.assertRegex(out, b'File "dinsdale')
+
+    def test_d_runtime_error(self):
+        bazfn = script_helper.make_script(self.pkgdir, 'baz', 'raise Exception')
+        self.assertRunOK('-q', '-d', 'dinsdale', self.pkgdir)
+        fn = script_helper.make_script(self.pkgdir, 'bing', 'import baz')
+        pyc = imp.cache_from_source(bazfn)
+        os.rename(pyc, os.path.join(self.pkgdir, 'baz.pyc'))
+        os.remove(bazfn)
+        rc, out, err = script_helper.assert_python_failure(fn)
+        self.assertRegex(err, b'File "dinsdale')
+
+    def test_include_bad_file(self):
+        rc, out, err = self.assertRunNotOK(
+            '-i', os.path.join(self.directory, 'nosuchfile'), self.pkgdir)
+        self.assertRegex(out, b'rror.*nosuchfile')
+        self.assertNotRegex(err, b'Traceback')
+        self.assertFalse(os.path.exists(imp.cache_from_source(
+                                            self.pkgdir_cachedir)))
+
+    def test_include_file_with_arg(self):
+        f1 = script_helper.make_script(self.pkgdir, 'f1', '')
+        f2 = script_helper.make_script(self.pkgdir, 'f2', '')
+        f3 = script_helper.make_script(self.pkgdir, 'f3', '')
+        f4 = script_helper.make_script(self.pkgdir, 'f4', '')
+        with open(os.path.join(self.directory, 'l1'), 'w') as l1:
+            l1.write(os.path.join(self.pkgdir, 'f1.py')+os.linesep)
+            l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
+        self.assertRunOK('-i', os.path.join(self.directory, 'l1'), f4)
+        self.assertCompiled(f1)
+        self.assertCompiled(f2)
+        self.assertNotCompiled(f3)
+        self.assertCompiled(f4)
+
+    def test_include_file_no_arg(self):
+        f1 = script_helper.make_script(self.pkgdir, 'f1', '')
+        f2 = script_helper.make_script(self.pkgdir, 'f2', '')
+        f3 = script_helper.make_script(self.pkgdir, 'f3', '')
+        f4 = script_helper.make_script(self.pkgdir, 'f4', '')
+        with open(os.path.join(self.directory, 'l1'), 'w') as l1:
+            l1.write(os.path.join(self.pkgdir, 'f2.py')+os.linesep)
+        self.assertRunOK('-i', os.path.join(self.directory, 'l1'))
+        self.assertNotCompiled(f1)
+        self.assertCompiled(f2)
+        self.assertNotCompiled(f3)
+        self.assertNotCompiled(f4)
+
+    def test_include_on_stdin(self):
+        f1 = script_helper.make_script(self.pkgdir, 'f1', '')
+        f2 = script_helper.make_script(self.pkgdir, 'f2', '')
+        f3 = script_helper.make_script(self.pkgdir, 'f3', '')
+        f4 = script_helper.make_script(self.pkgdir, 'f4', '')
+        p = script_helper.spawn_python('-m', 'compileall', '-i', '-')
+        p.stdin.write((f3+os.linesep).encode('ascii'))
+        script_helper.kill_python(p)
+        self.assertNotCompiled(f1)
+        self.assertNotCompiled(f2)
+        self.assertCompiled(f3)
+        self.assertNotCompiled(f4)
+
+    def test_compiles_as_much_as_possible(self):
+        bingfn = script_helper.make_script(self.pkgdir, 'bing', 'syntax(error')
+        rc, out, err = self.assertRunNotOK('nosuchfile', self.initfn,
+                                           bingfn, self.barfn)
+        self.assertRegex(out, b'rror')
+        self.assertNotCompiled(bingfn)
+        self.assertCompiled(self.initfn)
+        self.assertCompiled(self.barfn)
+
+    def test_invalid_arg_produces_message(self):
+        out = self.assertRunOK('badfilename')
+        self.assertRegex(out, b"Can't list 'badfilename'")
+
 
 def test_main():
     support.run_unittest(

Modified: python/branches/pep-3151/Lib/test/test_complex.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_complex.py	(original)
+++ python/branches/pep-3151/Lib/test/test_complex.py	Sat Feb 26 08:16:32 2011
@@ -220,6 +220,7 @@
         self.assertEqual(complex(NS(1+10j)), 1+10j)
         self.assertRaises(TypeError, complex, OS(None))
         self.assertRaises(TypeError, complex, NS(None))
+        self.assertRaises(TypeError, complex, {})
 
         self.assertAlmostEqual(complex("1+10j"), 1+10j)
         self.assertAlmostEqual(complex(10), 10+0j)
@@ -325,6 +326,8 @@
 
         # check that complex accepts long unicode strings
         self.assertEqual(type(complex("1"*500)), complex)
+        # check whitespace processing
+        self.assertEqual(complex('\N{EM SPACE}(\N{EN SPACE}1+1j ) '), 1+1j)
 
         class EvilExc(Exception):
             pass
@@ -378,28 +381,48 @@
         for num in nums:
             self.assertAlmostEqual((num.real**2 + num.imag**2)  ** 0.5, abs(num))
 
-    def test_repr(self):
-        self.assertEqual(repr(1+6j), '(1+6j)')
-        self.assertEqual(repr(1-6j), '(1-6j)')
-
-        self.assertNotEqual(repr(-(1+0j)), '(-1+-0j)')
+    def test_repr_str(self):
+        def test(v, expected, test_fn=self.assertEqual):
+            test_fn(repr(v), expected)
+            test_fn(str(v), expected)
+
+        test(1+6j, '(1+6j)')
+        test(1-6j, '(1-6j)')
+
+        test(-(1+0j), '(-1+-0j)', test_fn=self.assertNotEqual)
+
+        test(complex(1., INF), "(1+infj)")
+        test(complex(1., -INF), "(1-infj)")
+        test(complex(INF, 1), "(inf+1j)")
+        test(complex(-INF, INF), "(-inf+infj)")
+        test(complex(NAN, 1), "(nan+1j)")
+        test(complex(1, NAN), "(1+nanj)")
+        test(complex(NAN, NAN), "(nan+nanj)")
+
+        test(complex(0, INF), "infj")
+        test(complex(0, -INF), "-infj")
+        test(complex(0, NAN), "nanj")
 
         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)))
 
-        self.assertEqual(repr(complex(1., INF)), "(1+infj)")
-        self.assertEqual(repr(complex(1., -INF)), "(1-infj)")
-        self.assertEqual(repr(complex(INF, 1)), "(inf+1j)")
-        self.assertEqual(repr(complex(-INF, INF)), "(-inf+infj)")
-        self.assertEqual(repr(complex(NAN, 1)), "(nan+1j)")
-        self.assertEqual(repr(complex(1, NAN)), "(1+nanj)")
-        self.assertEqual(repr(complex(NAN, NAN)), "(nan+nanj)")
-
-        self.assertEqual(repr(complex(0, INF)), "infj")
-        self.assertEqual(repr(complex(0, -INF)), "-infj")
-        self.assertEqual(repr(complex(0, NAN)), "nanj")
+    @support.requires_IEEE_754
+    def test_negative_zero_repr_str(self):
+        def test(v, expected, test_fn=self.assertEqual):
+            test_fn(repr(v), expected)
+            test_fn(str(v), expected)
+
+        test(complex(0., 1.),   "1j")
+        test(complex(-0., 1.),  "(-0+1j)")
+        test(complex(0., -1.),  "-1j")
+        test(complex(-0., -1.), "(-0-1j)")
+
+        test(complex(0., 0.),   "0j")
+        test(complex(0., -0.),  "-0j")
+        test(complex(-0., 0.),  "(-0+0j)")
+        test(complex(-0., -0.), "(-0-0j)")
 
     def test_neg(self):
         self.assertEqual(-(1+6j), -1-6j)
@@ -428,15 +451,14 @@
         self.assertEqual(complex(0, INF).__getnewargs__(), (0.0, INF))
         self.assertEqual(complex(INF, 0).__getnewargs__(), (INF, 0.0))
 
-    if float.__getformat__("double").startswith("IEEE"):
-        def test_plus_minus_0j(self):
-            # test that -0j and 0j literals are not identified
-            z1, z2 = 0j, -0j
-            self.assertEquals(atan2(z1.imag, -1.), atan2(0., -1.))
-            self.assertEquals(atan2(z2.imag, -1.), atan2(-0., -1.))
+    @support.requires_IEEE_754
+    def test_plus_minus_0j(self):
+        # test that -0j and 0j literals are not identified
+        z1, z2 = 0j, -0j
+        self.assertEqual(atan2(z1.imag, -1.), atan2(0., -1.))
+        self.assertEqual(atan2(z2.imag, -1.), atan2(-0., -1.))
 
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
+    @support.requires_IEEE_754
     def test_negated_imaginary_literal(self):
         z0 = -0j
         z1 = -7j
@@ -452,15 +474,13 @@
         self.assertFloatsAreIdentical(z2.real, -0.0)
         self.assertFloatsAreIdentical(z2.imag, -INF)
 
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
+    @support.requires_IEEE_754
     def test_overflow(self):
         self.assertEqual(complex("1e500"), complex(INF, 0.0))
         self.assertEqual(complex("-1e500j"), complex(0.0, -INF))
         self.assertEqual(complex("-1e500+1.8e308j"), complex(-INF, INF))
 
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
+    @support.requires_IEEE_754
     def test_repr_roundtrip(self):
         vals = [0.0, 1e-500, 1e-315, 1e-200, 0.0123, 3.1415, 1e50, INF, NAN]
         vals += [-v for v in vals]
@@ -555,8 +575,28 @@
         self.assertEqual(format(1.5e21+3j, '^40,.2f'), ' 1,500,000,000,000,000,000,000.00+3.00j ')
         self.assertEqual(format(1.5e21+3000j, ',.2f'), '1,500,000,000,000,000,000,000.00+3,000.00j')
 
-        # alternate is invalid
-        self.assertRaises(ValueError, (1.5+0.5j).__format__, '#f')
+        # Issue 7094: Alternate formatting (specified by #)
+        self.assertEqual(format(1+1j, '.0e'), '1e+00+1e+00j')
+        self.assertEqual(format(1+1j, '#.0e'), '1.e+00+1.e+00j')
+        self.assertEqual(format(1+1j, '.0f'), '1+1j')
+        self.assertEqual(format(1+1j, '#.0f'), '1.+1.j')
+        self.assertEqual(format(1.1+1.1j, 'g'), '1.1+1.1j')
+        self.assertEqual(format(1.1+1.1j, '#g'), '1.10000+1.10000j')
+
+        # Alternate doesn't make a difference for these, they format the same with or without it
+        self.assertEqual(format(1+1j, '.1e'),  '1.0e+00+1.0e+00j')
+        self.assertEqual(format(1+1j, '#.1e'), '1.0e+00+1.0e+00j')
+        self.assertEqual(format(1+1j, '.1f'),  '1.0+1.0j')
+        self.assertEqual(format(1+1j, '#.1f'), '1.0+1.0j')
+
+        # Misc. other alternate tests
+        self.assertEqual(format((-1.5+0.5j), '#f'), '-1.500000+0.500000j')
+        self.assertEqual(format((-1.5+0.5j), '#.0f'), '-2.+0.j')
+        self.assertEqual(format((-1.5+0.5j), '#e'), '-1.500000e+00+5.000000e-01j')
+        self.assertEqual(format((-1.5+0.5j), '#.0e'), '-2.e+00+5.e-01j')
+        self.assertEqual(format((-1.5+0.5j), '#g'), '-1.50000+0.500000j')
+        self.assertEqual(format((-1.5+0.5j), '.0g'), '-2+0.5j')
+        self.assertEqual(format((-1.5+0.5j), '#.0g'), '-2.+0.5j')
 
         # zero padding is invalid
         self.assertRaises(ValueError, (1.5+0.5j).__format__, '010f')

Modified: python/branches/pep-3151/Lib/test/test_concurrent_futures.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_concurrent_futures.py	(original)
+++ python/branches/pep-3151/Lib/test/test_concurrent_futures.py	Sat Feb 26 08:16:32 2011
@@ -9,24 +9,16 @@
 # without thread support.
 test.support.import_module('threading')
 
-import io
-import logging
-import multiprocessing
-import sys
 import threading
 import time
 import unittest
 
-if sys.platform.startswith('win'):
-    import ctypes
-    import ctypes.wintypes
-
 from concurrent import futures
 from concurrent.futures._base import (
-    PENDING, RUNNING, CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED, Future,
-    LOGGER, STDERR_HANDLER, wait)
+    PENDING, RUNNING, CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED, Future)
 import concurrent.futures.process
 
+
 def create_future(state=PENDING, exception=None, result=None):
     f = Future()
     f._state = state
@@ -34,6 +26,7 @@
     f._result = result
     return f
 
+
 PENDING_FUTURE = create_future(state=PENDING)
 RUNNING_FUTURE = create_future(state=RUNNING)
 CANCELLED_FUTURE = create_future(state=CANCELLED)
@@ -41,96 +34,48 @@
 EXCEPTION_FUTURE = create_future(state=FINISHED, exception=IOError())
 SUCCESSFUL_FUTURE = create_future(state=FINISHED, result=42)
 
+
 def mul(x, y):
     return x * y
 
-class Call(object):
-    """A call that can be submitted to a future.Executor for testing.
 
-    The call signals when it is called and waits for an event before finishing.
-    """
-    CALL_LOCKS = {}
-    def _create_event(self):
-        if sys.platform.startswith('win'):
-            class SECURITY_ATTRIBUTES(ctypes.Structure):
-                _fields_ = [("nLength", ctypes.wintypes.DWORD),
-                            ("lpSecurityDescriptor", ctypes.wintypes.LPVOID),
-                            ("bInheritHandle", ctypes.wintypes.BOOL)]
-
-            s = SECURITY_ATTRIBUTES()
-            s.nLength = ctypes.sizeof(s)
-            s.lpSecurityDescriptor = None
-            s.bInheritHandle = True
-
-            handle = ctypes.windll.kernel32.CreateEventA(ctypes.pointer(s),
-                                                         True,
-                                                         False,
-                                                         None)
-            assert handle is not None
-            return handle
-        else:
-            event = multiprocessing.Event()
-            self.CALL_LOCKS[id(event)] = event
-            return id(event)
-
-    def _wait_on_event(self, handle):
-        if sys.platform.startswith('win'):
-            r = ctypes.windll.kernel32.WaitForSingleObject(handle, 5 * 1000)
-            assert r == 0
-        else:
-            self.CALL_LOCKS[handle].wait()
+def sleep_and_raise(t):
+    time.sleep(t)
+    raise Exception('this is an exception')
 
-    def _signal_event(self, handle):
-        if sys.platform.startswith('win'):
-            r = ctypes.windll.kernel32.SetEvent(handle)
-            assert r != 0
-        else:
-            self.CALL_LOCKS[handle].set()
 
-    def __init__(self, manual_finish=False, result=42):
-        self._called_event = self._create_event()
-        self._can_finish = self._create_event()
+class ExecutorMixin:
+    worker_count = 5
+    def _prime_executor(self):
+        # Make sure that the executor is ready to do work before running the
+        # tests. This should reduce the probability of timeouts in the tests.
+        futures = [self.executor.submit(time.sleep, 0.1)
+                   for _ in range(self.worker_count)]
 
-        self._result = result
+        for f in futures:
+            f.result()
 
-        if not manual_finish:
-            self._signal_event(self._can_finish)
 
-    def wait_on_called(self):
-        self._wait_on_event(self._called_event)
+class ThreadPoolMixin(ExecutorMixin):
+    def setUp(self):
+        self.executor = futures.ThreadPoolExecutor(max_workers=5)
+        self._prime_executor()
 
-    def set_can(self):
-        self._signal_event(self._can_finish)
+    def tearDown(self):
+        self.executor.shutdown(wait=True)
 
-    def __call__(self):
-        self._signal_event(self._called_event)
-        self._wait_on_event(self._can_finish)
 
-        return self._result
+class ProcessPoolMixin(ExecutorMixin):
+    def setUp(self):
+        try:
+            self.executor = futures.ProcessPoolExecutor(max_workers=5)
+        except NotImplementedError as e:
+            self.skipTest(str(e))
+        self._prime_executor()
 
-    def close(self):
-        self.set_can()
-        if sys.platform.startswith('win'):
-            ctypes.windll.kernel32.CloseHandle(self._called_event)
-            ctypes.windll.kernel32.CloseHandle(self._can_finish)
-        else:
-            del self.CALL_LOCKS[self._called_event]
-            del self.CALL_LOCKS[self._can_finish]
+    def tearDown(self):
+        self.executor.shutdown(wait=True)
 
-class ExceptionCall(Call):
-    def __call__(self):
-        self._signal_event(self._called_event)
-        self._wait_on_event(self._can_finish)
-        raise ZeroDivisionError()
-
-class MapCall(Call):
-    def __init__(self, result=42):
-        super().__init__(manual_finish=True, result=result)
-
-    def __call__(self, manual_finish):
-        if manual_finish:
-            super().__call__()
-        return self._result
 
 class ExecutorShutdownTest(unittest.TestCase):
     def test_run_after_shutdown(self):
@@ -140,37 +85,14 @@
                           pow, 2, 5)
 
 
-    def _start_some_futures(self):
-        call1 = Call(manual_finish=True)
-        call2 = Call(manual_finish=True)
-        call3 = Call(manual_finish=True)
-
-        try:
-            self.executor.submit(call1)
-            self.executor.submit(call2)
-            self.executor.submit(call3)
-
-            call1.wait_on_called()
-            call2.wait_on_called()
-            call3.wait_on_called()
-
-            call1.set_can()
-            call2.set_can()
-            call3.set_can()
-        finally:
-            call1.close()
-            call2.close()
-            call3.close()
-
-class ThreadPoolShutdownTest(ExecutorShutdownTest):
-    def setUp(self):
-        self.executor = futures.ThreadPoolExecutor(max_workers=5)
-
-    def tearDown(self):
-        self.executor.shutdown(wait=True)
+class ThreadPoolShutdownTest(ThreadPoolMixin, ExecutorShutdownTest):
+    def _prime_executor(self):
+        pass
 
     def test_threads_terminate(self):
-        self._start_some_futures()
+        self.executor.submit(mul, 21, 2)
+        self.executor.submit(mul, 6, 7)
+        self.executor.submit(mul, 3, 14)
         self.assertEqual(len(self.executor._threads), 3)
         self.executor.shutdown()
         for t in self.executor._threads:
@@ -194,15 +116,15 @@
         for t in threads:
             t.join()
 
-class ProcessPoolShutdownTest(ExecutorShutdownTest):
-    def setUp(self):
-        self.executor = futures.ProcessPoolExecutor(max_workers=5)
 
-    def tearDown(self):
-        self.executor.shutdown(wait=True)
+class ProcessPoolShutdownTest(ProcessPoolMixin, ExecutorShutdownTest):
+    def _prime_executor(self):
+        pass
 
     def test_processes_terminate(self):
-        self._start_some_futures()
+        self.executor.submit(mul, 21, 2)
+        self.executor.submit(mul, 6, 7)
+        self.executor.submit(mul, 3, 14)
         self.assertEqual(len(self.executor._processes), 5)
         processes = self.executor._processes
         self.executor.shutdown()
@@ -212,11 +134,11 @@
 
     def test_context_manager_shutdown(self):
         with futures.ProcessPoolExecutor(max_workers=5) as e:
-            executor = e
+            processes = e._processes
             self.assertEqual(list(e.map(abs, range(-5, 5))),
                              [5, 4, 3, 2, 1, 0, 1, 2, 3, 4])
 
-        for p in self.executor._processes:
+        for p in processes:
             p.join()
 
     def test_del_shutdown(self):
@@ -232,315 +154,168 @@
 
 class WaitTests(unittest.TestCase):
     def test_first_completed(self):
-        def wait_test():
-            while not future1._waiters:
-                pass
-            call1.set_can()
-
-        call1 = Call(manual_finish=True)
-        call2 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
-            future2 = self.executor.submit(call2)
+        future1 = self.executor.submit(mul, 21, 2)
+        future2 = self.executor.submit(time.sleep, 5)
 
-            t = threading.Thread(target=wait_test)
-            t.start()
-            done, not_done = futures.wait(
-                    [CANCELLED_FUTURE, future1, future2],
-                     return_when=futures.FIRST_COMPLETED)
-
-            self.assertEquals(set([future1]), done)
-            self.assertEquals(set([CANCELLED_FUTURE, future2]), not_done)
-        finally:
-            call1.close()
-            call2.close()
+        done, not_done = futures.wait(
+                [CANCELLED_FUTURE, future1, future2],
+                 return_when=futures.FIRST_COMPLETED)
+
+        self.assertEqual(set([future1]), done)
+        self.assertEqual(set([CANCELLED_FUTURE, future2]), not_done)
+
+    def test_first_completed_some_already_completed(self):
+        future1 = self.executor.submit(time.sleep, 2)
+
+        finished, pending = futures.wait(
+                 [CANCELLED_AND_NOTIFIED_FUTURE, SUCCESSFUL_FUTURE, future1],
+                 return_when=futures.FIRST_COMPLETED)
 
-    def test_first_completed_one_already_completed(self):
-        call1 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
-
-            finished, pending = futures.wait(
-                     [SUCCESSFUL_FUTURE, future1],
-                     return_when=futures.FIRST_COMPLETED)
-
-            self.assertEquals(set([SUCCESSFUL_FUTURE]), finished)
-            self.assertEquals(set([future1]), pending)
-        finally:
-            call1.close()
+        self.assertEqual(
+                set([CANCELLED_AND_NOTIFIED_FUTURE, SUCCESSFUL_FUTURE]),
+                finished)
+        self.assertEqual(set([future1]), pending)
 
     def test_first_exception(self):
-        def wait_test():
-            while not future1._waiters:
-                pass
-            call1.set_can()
-            call2.set_can()
-
-        call1 = Call(manual_finish=True)
-        call2 = ExceptionCall(manual_finish=True)
-        call3 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
-            future2 = self.executor.submit(call2)
-            future3 = self.executor.submit(call3)
-
-            t = threading.Thread(target=wait_test)
-            t.start()
-            finished, pending = futures.wait(
-                    [future1, future2, future3],
-                    return_when=futures.FIRST_EXCEPTION)
-
-            self.assertEquals(set([future1, future2]), finished)
-            self.assertEquals(set([future3]), pending)
-        finally:
-            call1.close()
-            call2.close()
-            call3.close()
+        future1 = self.executor.submit(mul, 2, 21)
+        future2 = self.executor.submit(sleep_and_raise, 5)
+        future3 = self.executor.submit(time.sleep, 10)
+
+        finished, pending = futures.wait(
+                [future1, future2, future3],
+                return_when=futures.FIRST_EXCEPTION)
 
-    def test_first_exception_some_already_complete(self):
-        def wait_test():
-            while not future1._waiters:
-                pass
-            call1.set_can()
+        self.assertEqual(set([future1, future2]), finished)
+        self.assertEqual(set([future3]), pending)
 
-        call1 = ExceptionCall(manual_finish=True)
-        call2 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
-            future2 = self.executor.submit(call2)
+    def test_first_exception_some_already_complete(self):
+        future1 = self.executor.submit(divmod, 21, 0)
+        future2 = self.executor.submit(time.sleep, 5)
 
-            t = threading.Thread(target=wait_test)
-            t.start()
-            finished, pending = futures.wait(
-                    [SUCCESSFUL_FUTURE,
-                     CANCELLED_FUTURE,
-                     CANCELLED_AND_NOTIFIED_FUTURE,
-                     future1, future2],
-                    return_when=futures.FIRST_EXCEPTION)
-
-            self.assertEquals(set([SUCCESSFUL_FUTURE,
-                                   CANCELLED_AND_NOTIFIED_FUTURE,
-                                   future1]), finished)
-            self.assertEquals(set([CANCELLED_FUTURE, future2]), pending)
-
-
-        finally:
-            call1.close()
-            call2.close()
+        finished, pending = futures.wait(
+                [SUCCESSFUL_FUTURE,
+                 CANCELLED_FUTURE,
+                 CANCELLED_AND_NOTIFIED_FUTURE,
+                 future1, future2],
+                return_when=futures.FIRST_EXCEPTION)
+
+        self.assertEqual(set([SUCCESSFUL_FUTURE,
+                              CANCELLED_AND_NOTIFIED_FUTURE,
+                              future1]), finished)
+        self.assertEqual(set([CANCELLED_FUTURE, future2]), pending)
 
     def test_first_exception_one_already_failed(self):
-        call1 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
+        future1 = self.executor.submit(time.sleep, 2)
 
-            finished, pending = futures.wait(
-                     [EXCEPTION_FUTURE, future1],
-                     return_when=futures.FIRST_EXCEPTION)
-
-            self.assertEquals(set([EXCEPTION_FUTURE]), finished)
-            self.assertEquals(set([future1]), pending)
-        finally:
-            call1.close()
+        finished, pending = futures.wait(
+                 [EXCEPTION_FUTURE, future1],
+                 return_when=futures.FIRST_EXCEPTION)
 
-    def test_all_completed(self):
-        def wait_test():
-            while not future1._waiters:
-                pass
-            call1.set_can()
-            call2.set_can()
+        self.assertEqual(set([EXCEPTION_FUTURE]), finished)
+        self.assertEqual(set([future1]), pending)
 
-        call1 = Call(manual_finish=True)
-        call2 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
-            future2 = self.executor.submit(call2)
+    def test_all_completed(self):
+        future1 = self.executor.submit(divmod, 2, 0)
+        future2 = self.executor.submit(mul, 2, 21)
 
-            t = threading.Thread(target=wait_test)
-            t.start()
-            finished, pending = futures.wait(
-                    [future1, future2],
-                    return_when=futures.ALL_COMPLETED)
-
-            self.assertEquals(set([future1, future2]), finished)
-            self.assertEquals(set(), pending)
-
-
-        finally:
-            call1.close()
-            call2.close()
-
-    def test_all_completed_some_already_completed(self):
-        def wait_test():
-            while not future1._waiters:
-                pass
-
-            future4.cancel()
-            call1.set_can()
-            call2.set_can()
-            call3.set_can()
-
-        self.assertLessEqual(
-                futures.process.EXTRA_QUEUED_CALLS,
-                1,
-               'this test assumes that future4 will be cancelled before it is '
-               'queued to run - which might not be the case if '
-               'ProcessPoolExecutor is too aggresive in scheduling futures')
-        call1 = Call(manual_finish=True)
-        call2 = Call(manual_finish=True)
-        call3 = Call(manual_finish=True)
-        call4 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
-            future2 = self.executor.submit(call2)
-            future3 = self.executor.submit(call3)
-            future4 = self.executor.submit(call4)
-
-            t = threading.Thread(target=wait_test)
-            t.start()
-            finished, pending = futures.wait(
-                    [SUCCESSFUL_FUTURE,
-                     CANCELLED_AND_NOTIFIED_FUTURE,
-                     future1, future2, future3, future4],
-                    return_when=futures.ALL_COMPLETED)
-
-            self.assertEquals(set([SUCCESSFUL_FUTURE,
-                                   CANCELLED_AND_NOTIFIED_FUTURE,
-                                   future1, future2, future3, future4]),
-                              finished)
-            self.assertEquals(set(), pending)
-        finally:
-            call1.close()
-            call2.close()
-            call3.close()
-            call4.close()
+        finished, pending = futures.wait(
+                [SUCCESSFUL_FUTURE,
+                 CANCELLED_AND_NOTIFIED_FUTURE,
+                 EXCEPTION_FUTURE,
+                 future1,
+                 future2],
+                return_when=futures.ALL_COMPLETED)
+
+        self.assertEqual(set([SUCCESSFUL_FUTURE,
+                              CANCELLED_AND_NOTIFIED_FUTURE,
+                              EXCEPTION_FUTURE,
+                              future1,
+                              future2]), finished)
+        self.assertEqual(set(), pending)
 
     def test_timeout(self):
-        def wait_test():
-            while not future1._waiters:
-                pass
-            call1.set_can()
-
-        call1 = Call(manual_finish=True)
-        call2 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
-            future2 = self.executor.submit(call2)
-
-            t = threading.Thread(target=wait_test)
-            t.start()
-            finished, pending = futures.wait(
-                    [CANCELLED_AND_NOTIFIED_FUTURE,
-                     EXCEPTION_FUTURE,
-                     SUCCESSFUL_FUTURE,
-                     future1, future2],
-                    timeout=1,
-                    return_when=futures.ALL_COMPLETED)
-
-            self.assertEquals(set([CANCELLED_AND_NOTIFIED_FUTURE,
-                                   EXCEPTION_FUTURE,
-                                   SUCCESSFUL_FUTURE,
-                                   future1]), finished)
-            self.assertEquals(set([future2]), pending)
-
+        future1 = self.executor.submit(mul, 6, 7)
+        future2 = self.executor.submit(time.sleep, 10)
 
-        finally:
-            call1.close()
-            call2.close()
+        finished, pending = futures.wait(
+                [CANCELLED_AND_NOTIFIED_FUTURE,
+                 EXCEPTION_FUTURE,
+                 SUCCESSFUL_FUTURE,
+                 future1, future2],
+                timeout=5,
+                return_when=futures.ALL_COMPLETED)
+
+        self.assertEqual(set([CANCELLED_AND_NOTIFIED_FUTURE,
+                              EXCEPTION_FUTURE,
+                              SUCCESSFUL_FUTURE,
+                              future1]), finished)
+        self.assertEqual(set([future2]), pending)
 
 
-class ThreadPoolWaitTests(WaitTests):
-    def setUp(self):
-        self.executor = futures.ThreadPoolExecutor(max_workers=1)
+class ThreadPoolWaitTests(ThreadPoolMixin, WaitTests):
+    pass
 
-    def tearDown(self):
-        self.executor.shutdown(wait=True)
 
-class ProcessPoolWaitTests(WaitTests):
-    def setUp(self):
-        self.executor = futures.ProcessPoolExecutor(max_workers=1)
+class ProcessPoolWaitTests(ProcessPoolMixin, WaitTests):
+    pass
 
-    def tearDown(self):
-        self.executor.shutdown(wait=True)
 
 class AsCompletedTests(unittest.TestCase):
     # TODO(brian at sweetapp.com): Should have a test with a non-zero timeout.
     def test_no_timeout(self):
-        def wait_test():
-            while not future1._waiters:
-                pass
-            call1.set_can()
-            call2.set_can()
+        future1 = self.executor.submit(mul, 2, 21)
+        future2 = self.executor.submit(mul, 7, 6)
 
-        call1 = Call(manual_finish=True)
-        call2 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
-            future2 = self.executor.submit(call2)
+        completed = set(futures.as_completed(
+                [CANCELLED_AND_NOTIFIED_FUTURE,
+                 EXCEPTION_FUTURE,
+                 SUCCESSFUL_FUTURE,
+                 future1, future2]))
+        self.assertEqual(set(
+                [CANCELLED_AND_NOTIFIED_FUTURE,
+                 EXCEPTION_FUTURE,
+                 SUCCESSFUL_FUTURE,
+                 future1, future2]),
+                completed)
 
-            t = threading.Thread(target=wait_test)
-            t.start()
-            completed = set(futures.as_completed(
-                    [CANCELLED_AND_NOTIFIED_FUTURE,
-                     EXCEPTION_FUTURE,
-                     SUCCESSFUL_FUTURE,
-                     future1, future2]))
-            self.assertEquals(set(
+    def test_zero_timeout(self):
+        future1 = self.executor.submit(time.sleep, 2)
+        completed_futures = set()
+        try:
+            for future in futures.as_completed(
                     [CANCELLED_AND_NOTIFIED_FUTURE,
                      EXCEPTION_FUTURE,
                      SUCCESSFUL_FUTURE,
-                     future1, future2]),
-                    completed)
-        finally:
-            call1.close()
-            call2.close()
+                     future1],
+                    timeout=0):
+                completed_futures.add(future)
+        except futures.TimeoutError:
+            pass
 
-    def test_zero_timeout(self):
-        call1 = Call(manual_finish=True)
-        try:
-            future1 = self.executor.submit(call1)
-            completed_futures = set()
-            try:
-                for future in futures.as_completed(
-                        [CANCELLED_AND_NOTIFIED_FUTURE,
-                         EXCEPTION_FUTURE,
-                         SUCCESSFUL_FUTURE,
-                         future1],
-                        timeout=0):
-                    completed_futures.add(future)
-            except futures.TimeoutError:
-                pass
-
-            self.assertEquals(set([CANCELLED_AND_NOTIFIED_FUTURE,
-                                   EXCEPTION_FUTURE,
-                                   SUCCESSFUL_FUTURE]),
-                              completed_futures)
-        finally:
-            call1.close()
+        self.assertEqual(set([CANCELLED_AND_NOTIFIED_FUTURE,
+                              EXCEPTION_FUTURE,
+                              SUCCESSFUL_FUTURE]),
+                         completed_futures)
 
-class ThreadPoolAsCompletedTests(AsCompletedTests):
-    def setUp(self):
-        self.executor = futures.ThreadPoolExecutor(max_workers=1)
 
-    def tearDown(self):
-        self.executor.shutdown(wait=True)
+class ThreadPoolAsCompletedTests(ThreadPoolMixin, AsCompletedTests):
+    pass
 
-class ProcessPoolAsCompletedTests(AsCompletedTests):
-    def setUp(self):
-        self.executor = futures.ProcessPoolExecutor(max_workers=1)
 
-    def tearDown(self):
-        self.executor.shutdown(wait=True)
+class ProcessPoolAsCompletedTests(ProcessPoolMixin, AsCompletedTests):
+    pass
+
 
 class ExecutorTest(unittest.TestCase):
     # Executor.shutdown() and context manager usage is tested by
     # ExecutorShutdownTest.
     def test_submit(self):
         future = self.executor.submit(pow, 2, 8)
-        self.assertEquals(256, future.result())
+        self.assertEqual(256, future.result())
 
     def test_submit_keyword(self):
         future = self.executor.submit(mul, 2, y=8)
-        self.assertEquals(16, future.result())
+        self.assertEqual(16, future.result())
 
     def test_map(self):
         self.assertEqual(
@@ -555,35 +330,26 @@
 
     def test_map_timeout(self):
         results = []
-        timeout_call = MapCall()
         try:
-            try:
-                for i in self.executor.map(timeout_call,
-                                           [False, False, True],
-                                           timeout=1):
-                    results.append(i)
-            except futures.TimeoutError:
-                pass
-            else:
-                self.fail('expected TimeoutError')
-        finally:
-            timeout_call.close()
+            for i in self.executor.map(time.sleep,
+                                       [0, 0, 10],
+                                       timeout=5):
+                results.append(i)
+        except futures.TimeoutError:
+            pass
+        else:
+            self.fail('expected TimeoutError')
 
-        self.assertEquals([42, 42], results)
+        self.assertEqual([None, None], results)
 
-class ThreadPoolExecutorTest(ExecutorTest):
-    def setUp(self):
-        self.executor = futures.ThreadPoolExecutor(max_workers=1)
 
-    def tearDown(self):
-        self.executor.shutdown(wait=True)
+class ThreadPoolExecutorTest(ThreadPoolMixin, ExecutorTest):
+    pass
 
-class ProcessPoolExecutorTest(ExecutorTest):
-    def setUp(self):
-        self.executor = futures.ProcessPoolExecutor(max_workers=1)
 
-    def tearDown(self):
-        self.executor.shutdown(wait=True)
+class ProcessPoolExecutorTest(ProcessPoolMixin, ExecutorTest):
+    pass
+
 
 class FutureTests(unittest.TestCase):
     def test_done_callback_with_result(self):
@@ -595,7 +361,7 @@
         f = Future()
         f.add_done_callback(fn)
         f.set_result(5)
-        self.assertEquals(5, callback_result)
+        self.assertEqual(5, callback_result)
 
     def test_done_callback_with_exception(self):
         callback_exception = None
@@ -606,7 +372,7 @@
         f = Future()
         f.add_done_callback(fn)
         f.set_exception(Exception('test'))
-        self.assertEquals(('test',), callback_exception.args)
+        self.assertEqual(('test',), callback_exception.args)
 
     def test_done_callback_with_cancel(self):
         was_cancelled = None
@@ -620,11 +386,7 @@
         self.assertTrue(was_cancelled)
 
     def test_done_callback_raises(self):
-        LOGGER.removeHandler(STDERR_HANDLER)
-        logging_stream = io.StringIO()
-        handler = logging.StreamHandler(logging_stream)
-        LOGGER.addHandler(handler)
-        try:
+        with test.support.captured_stderr() as stderr:
             raising_was_called = False
             fn_was_called = False
 
@@ -643,10 +405,7 @@
             f.set_result(5)
             self.assertTrue(raising_was_called)
             self.assertTrue(fn_was_called)
-            self.assertIn('Exception: doh!', logging_stream.getvalue())
-        finally:
-            LOGGER.removeHandler(handler)
-            LOGGER.addHandler(STDERR_HANDLER)
+            self.assertIn('Exception: doh!', stderr.getvalue())
 
     def test_done_callback_already_successful(self):
         callback_result = None
@@ -657,7 +416,7 @@
         f = Future()
         f.set_result(5)
         f.add_done_callback(fn)
-        self.assertEquals(5, callback_result)
+        self.assertEqual(5, callback_result)
 
     def test_done_callback_already_failed(self):
         callback_exception = None
@@ -668,7 +427,7 @@
         f = Future()
         f.set_exception(Exception('test'))
         f.add_done_callback(fn)
-        self.assertEquals(('test',), callback_exception.args)
+        self.assertEqual(('test',), callback_exception.args)
 
     def test_done_callback_already_cancelled(self):
         was_cancelled = None
@@ -682,18 +441,18 @@
         self.assertTrue(was_cancelled)
 
     def test_repr(self):
-        self.assertRegexpMatches(repr(PENDING_FUTURE),
-                                 '<Future at 0x[0-9a-f]+ state=pending>')
-        self.assertRegexpMatches(repr(RUNNING_FUTURE),
-                                 '<Future at 0x[0-9a-f]+ state=running>')
-        self.assertRegexpMatches(repr(CANCELLED_FUTURE),
-                                 '<Future at 0x[0-9a-f]+ state=cancelled>')
-        self.assertRegexpMatches(repr(CANCELLED_AND_NOTIFIED_FUTURE),
-                                 '<Future at 0x[0-9a-f]+ state=cancelled>')
-        self.assertRegexpMatches(
+        self.assertRegex(repr(PENDING_FUTURE),
+                         '<Future at 0x[0-9a-f]+ state=pending>')
+        self.assertRegex(repr(RUNNING_FUTURE),
+                         '<Future at 0x[0-9a-f]+ state=running>')
+        self.assertRegex(repr(CANCELLED_FUTURE),
+                         '<Future at 0x[0-9a-f]+ state=cancelled>')
+        self.assertRegex(repr(CANCELLED_AND_NOTIFIED_FUTURE),
+                         '<Future at 0x[0-9a-f]+ state=cancelled>')
+        self.assertRegex(
                 repr(EXCEPTION_FUTURE),
                 '<Future at 0x[0-9a-f]+ state=finished raised IOError>')
-        self.assertRegexpMatches(
+        self.assertRegex(
                 repr(SUCCESSFUL_FUTURE),
                 '<Future at 0x[0-9a-f]+ state=finished returned int>')
 
@@ -707,22 +466,22 @@
         f6 = create_future(state=FINISHED, result=5)
 
         self.assertTrue(f1.cancel())
-        self.assertEquals(f1._state, CANCELLED)
+        self.assertEqual(f1._state, CANCELLED)
 
         self.assertFalse(f2.cancel())
-        self.assertEquals(f2._state, RUNNING)
+        self.assertEqual(f2._state, RUNNING)
 
         self.assertTrue(f3.cancel())
-        self.assertEquals(f3._state, CANCELLED)
+        self.assertEqual(f3._state, CANCELLED)
 
         self.assertTrue(f4.cancel())
-        self.assertEquals(f4._state, CANCELLED_AND_NOTIFIED)
+        self.assertEqual(f4._state, CANCELLED_AND_NOTIFIED)
 
         self.assertFalse(f5.cancel())
-        self.assertEquals(f5._state, FINISHED)
+        self.assertEqual(f5._state, FINISHED)
 
         self.assertFalse(f6.cancel())
-        self.assertEquals(f6._state, FINISHED)
+        self.assertEqual(f6._state, FINISHED)
 
     def test_cancelled(self):
         self.assertFalse(PENDING_FUTURE.cancelled())
@@ -771,7 +530,7 @@
         t = threading.Thread(target=notification)
         t.start()
 
-        self.assertEquals(f1.result(timeout=5), 42)
+        self.assertEqual(f1.result(timeout=5), 42)
 
     def test_result_with_cancel(self):
         # TODO(brian at sweetapp.com): This test is timing dependant.

Modified: python/branches/pep-3151/Lib/test/test_contextlib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_contextlib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_contextlib.py	Sat Feb 26 08:16:32 2011
@@ -231,7 +231,7 @@
     def test_contextdecorator_with_exception(self):
         context = mycontext()
 
-        with self.assertRaisesRegexp(NameError, 'foo'):
+        with self.assertRaisesRegex(NameError, 'foo'):
             with context:
                 raise NameError('foo')
         self.assertIsNotNone(context.exc)
@@ -265,7 +265,7 @@
             self.assertTrue(context.started)
             raise NameError('foo')
 
-        with self.assertRaisesRegexp(NameError, 'foo'):
+        with self.assertRaisesRegex(NameError, 'foo'):
             test()
         self.assertIsNotNone(context.exc)
         self.assertIs(context.exc[0], NameError)

Modified: python/branches/pep-3151/Lib/test/test_copyreg.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_copyreg.py	(original)
+++ python/branches/pep-3151/Lib/test/test_copyreg.py	Sat Feb 26 08:16:32 2011
@@ -40,7 +40,7 @@
 
     def test_bool(self):
         import copy
-        self.assertEquals(True, copy.copy(True))
+        self.assertEqual(True, copy.copy(True))
 
     def test_extension_registry(self):
         mod, func, code = 'junk1 ', ' junk2', 0xabcd
@@ -101,16 +101,16 @@
                               mod, func, code)
 
     def test_slotnames(self):
-        self.assertEquals(copyreg._slotnames(WithoutSlots), [])
-        self.assertEquals(copyreg._slotnames(WithWeakref), [])
+        self.assertEqual(copyreg._slotnames(WithoutSlots), [])
+        self.assertEqual(copyreg._slotnames(WithWeakref), [])
         expected = ['_WithPrivate__spam']
-        self.assertEquals(copyreg._slotnames(WithPrivate), expected)
-        self.assertEquals(copyreg._slotnames(WithSingleString), ['spam'])
+        self.assertEqual(copyreg._slotnames(WithPrivate), expected)
+        self.assertEqual(copyreg._slotnames(WithSingleString), ['spam'])
         expected = ['eggs', 'spam']
         expected.sort()
         result = copyreg._slotnames(WithInherited)
         result.sort()
-        self.assertEquals(result, expected)
+        self.assertEqual(result, expected)
 
 
 def test_main():

Modified: python/branches/pep-3151/Lib/test/test_crypt.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_crypt.py	(original)
+++ python/branches/pep-3151/Lib/test/test_crypt.py	Sat Feb 26 08:16:32 2011
@@ -10,6 +10,25 @@
         if support.verbose:
             print('Test encryption: ', c)
 
+    def test_salt(self):
+        self.assertEqual(len(crypt._saltchars), 64)
+        for method in crypt.methods:
+            salt = crypt.mksalt(method)
+            self.assertEqual(len(salt),
+                    method.salt_chars + (3 if method.ident else 0))
+
+    def test_saltedcrypt(self):
+        for method in crypt.methods:
+            pw = crypt.crypt('assword', method)
+            self.assertEqual(len(pw), method.total_size)
+            pw = crypt.crypt('assword', crypt.mksalt(method))
+            self.assertEqual(len(pw), method.total_size)
+
+    def test_methods(self):
+        # Gurantee that METHOD_CRYPT is the last method in crypt.methods.
+        self.assertTrue(len(crypt.methods) >= 1)
+        self.assertEqual(crypt.METHOD_CRYPT, crypt.methods[-1])
+
 def test_main():
     support.run_unittest(CryptTestCase)
 

Modified: python/branches/pep-3151/Lib/test/test_csv.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_csv.py	(original)
+++ python/branches/pep-3151/Lib/test/test_csv.py	Sat Feb 26 08:16:32 2011
@@ -313,22 +313,17 @@
         expected_dialects = csv.list_dialects() + [name]
         expected_dialects.sort()
         csv.register_dialect(name, myexceltsv)
-        try:
-            self.assertTrue(csv.get_dialect(name).delimiter, '\t')
-            got_dialects = csv.list_dialects()
-            got_dialects.sort()
-            self.assertEqual(expected_dialects, got_dialects)
-        finally:
-            csv.unregister_dialect(name)
+        self.addCleanup(csv.unregister_dialect, name)
+        self.assertEqual(csv.get_dialect(name).delimiter, '\t')
+        got_dialects = sorted(csv.list_dialects())
+        self.assertEqual(expected_dialects, got_dialects)
 
     def test_register_kwargs(self):
         name = 'fedcba'
         csv.register_dialect(name, delimiter=';')
-        try:
-            self.assertTrue(csv.get_dialect(name).delimiter, '\t')
-            self.assertTrue(list(csv.reader('X;Y;Z', name)), ['X', 'Y', 'Z'])
-        finally:
-            csv.unregister_dialect(name)
+        self.addCleanup(csv.unregister_dialect, name)
+        self.assertEqual(csv.get_dialect(name).delimiter, ';')
+        self.assertEqual([['X', 'Y', 'Z']], list(csv.reader(['X;Y;Z'], name)))
 
     def test_incomplete_dialect(self):
         class myexceltsv(csv.Dialect):

Modified: python/branches/pep-3151/Lib/test/test_dbm.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_dbm.py	(original)
+++ python/branches/pep-3151/Lib/test/test_dbm.py	Sat Feb 26 08:16:32 2011
@@ -123,7 +123,7 @@
             name = module.__name__
             if name == 'dbm.dumb':
                 continue   # whichdb can't support dbm.dumb
-            test.support.unlink(_fname)
+            delete_files()
             f = module.open(_fname, 'c')
             f.close()
             self.assertEqual(name, dbm.whichdb(_fname))

Modified: python/branches/pep-3151/Lib/test/test_dbm_gnu.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_dbm_gnu.py	(original)
+++ python/branches/pep-3151/Lib/test/test_dbm_gnu.py	Sat Feb 26 08:16:32 2011
@@ -32,6 +32,10 @@
             key_set.remove(key)
             key = self.g.nextkey(key)
         self.assertRaises(KeyError, lambda: self.g['xxx'])
+        # get() and setdefault() work as in the dict interface
+        self.assertEqual(self.g.get(b'xxx', b'foo'), b'foo')
+        self.assertEqual(self.g.setdefault(b'xxx', b'foo'), b'foo')
+        self.assertEqual(self.g[b'xxx'], b'foo')
 
     def test_error_conditions(self):
         # Try to open a non-existent database.

Modified: python/branches/pep-3151/Lib/test/test_decimal.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_decimal.py	(original)
+++ python/branches/pep-3151/Lib/test/test_decimal.py	Sat Feb 26 08:16:32 2011
@@ -32,7 +32,8 @@
 import unittest
 from decimal import *
 import numbers
-from test.support import run_unittest, run_doctest, is_resource_enabled
+from test.support import (run_unittest, run_doctest, is_resource_enabled,
+                          requires_IEEE_754)
 from test.support import check_warnings
 import random
 try:
@@ -61,11 +62,6 @@
         )
     setcontext(DefaultTestContext)
 
-# decorator for skipping tests on non-IEEE 754 platforms
-requires_IEEE_754 = unittest.skipUnless(
-    float.__getformat__("double").startswith("IEEE"),
-    "test requires IEEE 754 doubles")
-
 TESTDATADIR = 'decimaltestdata'
 if __name__ == '__main__':
     file = sys.argv[0]
@@ -818,6 +814,18 @@
 
             # issue 6850
             ('a=-7.0', '0.12345', 'aaaa0.1'),
+
+            # Issue 7094: Alternate formatting (specified by #)
+            ('.0e', '1.0', '1e+0'),
+            ('#.0e', '1.0', '1.e+0'),
+            ('.0f', '1.0', '1'),
+            ('#.0f', '1.0', '1.'),
+            ('g', '1.1', '1.1'),
+            ('#g', '1.1', '1.1'),
+            ('.0g', '1', '1'),
+            ('#.0g', '1', '1.'),
+            ('.0%', '1.0', '100%'),
+            ('#.0%', '1.0', '100.%'),
             ]
         for fmt, d, result in test_values:
             self.assertEqual(format(Decimal(d), fmt), result)
@@ -1299,19 +1307,26 @@
         self.assertEqual(id(dc), id(d))
 
     def test_hash_method(self):
+        def hashit(d):
+            a = hash(d)
+            b = d.__hash__()
+            self.assertEqual(a, b)
+            return a
+
         #just that it's hashable
-        hash(Decimal(23))
-        hash(Decimal('Infinity'))
-        hash(Decimal('-Infinity'))
-        hash(Decimal('nan123'))
-        hash(Decimal('-NaN'))
+        hashit(Decimal(23))
+        hashit(Decimal('Infinity'))
+        hashit(Decimal('-Infinity'))
+        hashit(Decimal('nan123'))
+        hashit(Decimal('-NaN'))
 
         test_values = [Decimal(sign*(2**m + n))
                        for m in [0, 14, 15, 16, 17, 30, 31,
-                                 32, 33, 62, 63, 64, 65, 66]
+                                 32, 33, 61, 62, 63, 64, 65, 66]
                        for n in range(-10, 10)
                        for sign in [-1, 1]]
         test_values.extend([
+                Decimal("-1"), # ==> -2
                 Decimal("-0"), # zeros
                 Decimal("0.00"),
                 Decimal("-0.000"),
@@ -1335,13 +1350,13 @@
 
         # check that hash(d) == hash(int(d)) for integral values
         for value in test_values:
-            self.assertEqual(hash(value), hash(int(value)))
+            self.assertEqual(hashit(value), hashit(int(value)))
 
         #the same hash that to an int
-        self.assertEqual(hash(Decimal(23)), hash(23))
+        self.assertEqual(hashit(Decimal(23)), hashit(23))
         self.assertRaises(TypeError, hash, Decimal('sNaN'))
-        self.assertTrue(hash(Decimal('Inf')))
-        self.assertTrue(hash(Decimal('-Inf')))
+        self.assertTrue(hashit(Decimal('Inf')))
+        self.assertTrue(hashit(Decimal('-Inf')))
 
         # check that the hashes of a Decimal float match when they
         # represent exactly the same values
@@ -1350,7 +1365,7 @@
         for s in test_strings:
             f = float(s)
             d = Decimal(s)
-            self.assertEqual(hash(f), hash(d))
+            self.assertEqual(hashit(f), hashit(d))
 
         # check that the value of the hash doesn't depend on the
         # current context (issue #1757)
@@ -1359,11 +1374,11 @@
         x = Decimal("123456789.1")
 
         c.prec = 6
-        h1 = hash(x)
+        h1 = hashit(x)
         c.prec = 10
-        h2 = hash(x)
+        h2 = hashit(x)
         c.prec = 16
-        h3 = hash(x)
+        h3 = hashit(x)
 
         self.assertEqual(h1, h2)
         self.assertEqual(h1, h3)

Modified: python/branches/pep-3151/Lib/test/test_deque.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_deque.py	(original)
+++ python/branches/pep-3151/Lib/test/test_deque.py	Sat Feb 26 08:16:32 2011
@@ -138,6 +138,15 @@
         m.d = d
         self.assertRaises(RuntimeError, d.count, 3)
 
+        # test issue11004
+        # block advance failed after rotation aligned elements on right side of block
+        d = deque([None]*16)
+        for i in range(len(d)):
+            d.rotate(-1)
+        d.rotate(1)
+        self.assertEqual(d.count(1), 0)
+        self.assertEqual(d.count(None), 16)
+
     def test_comparisons(self):
         d = deque('xabc'); d.popleft()
         for e in [d, deque('abc'), deque('ab'), deque(), list(d)]:
@@ -234,7 +243,7 @@
             d = deque(data[:i])
             r = d.reverse()
             self.assertEqual(list(d), list(reversed(data[:i])))
-            self.assert_(r is None)
+            self.assertIs(r, None)
             d.reverse()
             self.assertEqual(list(d), data[:i])
         self.assertRaises(TypeError, d.reverse, 1)          # Arity is zero

Modified: python/branches/pep-3151/Lib/test/test_descr.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_descr.py	(original)
+++ python/branches/pep-3151/Lib/test/test_descr.py	Sat Feb 26 08:16:32 2011
@@ -4205,11 +4205,11 @@
             __getattr__ = descr
 
         self.assertRaises(AttributeError, getattr, A(), "attr")
-        self.assertEquals(descr.counter, 1)
+        self.assertEqual(descr.counter, 1)
         self.assertRaises(AttributeError, getattr, B(), "attr")
-        self.assertEquals(descr.counter, 2)
+        self.assertEqual(descr.counter, 2)
         self.assertRaises(AttributeError, getattr, C(), "attr")
-        self.assertEquals(descr.counter, 4)
+        self.assertEqual(descr.counter, 4)
 
         import gc
         class EvilGetattribute(object):
@@ -4224,6 +4224,17 @@
 
         self.assertRaises(AttributeError, getattr, EvilGetattribute(), "attr")
 
+    def test_abstractmethods(self):
+        # type pretends not to have __abstractmethods__.
+        self.assertRaises(AttributeError, getattr, type, "__abstractmethods__")
+        class meta(type):
+            pass
+        self.assertRaises(AttributeError, getattr, meta, "__abstractmethods__")
+        class X(object):
+            pass
+        with self.assertRaises(AttributeError):
+            del X.__abstractmethods__
+
 
 class DictProxyTests(unittest.TestCase):
     def setUp(self):
@@ -4232,21 +4243,33 @@
                 pass
         self.C = C
 
+    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
+                        'trace function introduces __local__')
     def test_iter_keys(self):
-        # Testing dict-proxy iterkeys...
-        keys = [ key for key in self.C.__dict__.keys() ]
+        # Testing dict-proxy keys...
+        it = self.C.__dict__.keys()
+        self.assertNotIsInstance(it, list)
+        keys = list(it)
         keys.sort()
-        self.assertEquals(keys, ['__dict__', '__doc__', '__module__',
+        self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
             '__weakref__', 'meth'])
 
+    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
+                        'trace function introduces __local__')
     def test_iter_values(self):
-        # Testing dict-proxy itervalues...
-        values = [ values for values in self.C.__dict__.values() ]
+        # Testing dict-proxy values...
+        it = self.C.__dict__.values()
+        self.assertNotIsInstance(it, list)
+        values = list(it)
         self.assertEqual(len(values), 5)
 
+    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
+                        'trace function introduces __local__')
     def test_iter_items(self):
         # Testing dict-proxy iteritems...
-        keys = [ key for (key, value) in self.C.__dict__.items() ]
+        it = self.C.__dict__.items()
+        self.assertNotIsInstance(it, list)
+        keys = [item[0] for item in it]
         keys.sort()
         self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
             '__weakref__', 'meth'])
@@ -4262,6 +4285,11 @@
             pass
         self.assertEqual(type(C.__dict__), type(B.__dict__))
 
+    def test_repr(self):
+        # Testing dict_proxy.__repr__
+        dict_ = {k: v for k, v in self.C.__dict__.items()}
+        self.assertEqual(repr(self.C.__dict__), 'dict_proxy({!r})'.format(dict_))
+
 
 class PTypesLongInitTest(unittest.TestCase):
     # This is in its own TestCase so that it can be run before any other tests.

Modified: python/branches/pep-3151/Lib/test/test_descrtut.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_descrtut.py	(original)
+++ python/branches/pep-3151/Lib/test/test_descrtut.py	Sat Feb 26 08:16:32 2011
@@ -199,6 +199,8 @@
      '__str__',
      '__subclasshook__',
      'append',
+     'clear',
+     'copy',
      'count',
      'extend',
      'index',

Modified: python/branches/pep-3151/Lib/test/test_dict.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_dict.py	(original)
+++ python/branches/pep-3151/Lib/test/test_dict.py	Sat Feb 26 08:16:32 2011
@@ -8,10 +8,13 @@
 class DictTest(unittest.TestCase):
 
     def test_invalid_keyword_arguments(self):
-        with self.assertRaises(TypeError):
-            dict(**{1 : 2})
-        with self.assertRaises(TypeError):
-            {}.update(**{1 : 2})
+        class Custom(dict):
+            pass
+        for invalid in {1 : 2}, Custom({1 : 2}):
+            with self.assertRaises(TypeError):
+                dict(**invalid)
+            with self.assertRaises(TypeError):
+                {}.update(**invalid)
 
     def test_constructor(self):
         # calling built-in types without argument must return empty

Modified: python/branches/pep-3151/Lib/test/test_difflib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_difflib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_difflib.py	Sat Feb 26 08:16:32 2011
@@ -4,8 +4,64 @@
 import doctest
 import sys
 
-class TestSFbugs(unittest.TestCase):
 
+class TestWithAscii(unittest.TestCase):
+    def test_one_insert(self):
+        sm = difflib.SequenceMatcher(None, 'b' * 100, 'a' + 'b' * 100)
+        self.assertAlmostEqual(sm.ratio(), 0.995, places=3)
+        self.assertEqual(list(sm.get_opcodes()),
+            [   ('insert', 0, 0, 0, 1),
+                ('equal', 0, 100, 1, 101)])
+        self.assertEqual(sm.bpopular, set())
+        sm = difflib.SequenceMatcher(None, 'b' * 100, 'b' * 50 + 'a' + 'b' * 50)
+        self.assertAlmostEqual(sm.ratio(), 0.995, places=3)
+        self.assertEqual(list(sm.get_opcodes()),
+            [   ('equal', 0, 50, 0, 50),
+                ('insert', 50, 50, 50, 51),
+                ('equal', 50, 100, 51, 101)])
+        self.assertEqual(sm.bpopular, set())
+
+    def test_one_delete(self):
+        sm = difflib.SequenceMatcher(None, 'a' * 40 + 'c' + 'b' * 40, 'a' * 40 + 'b' * 40)
+        self.assertAlmostEqual(sm.ratio(), 0.994, places=3)
+        self.assertEqual(list(sm.get_opcodes()),
+            [   ('equal', 0, 40, 0, 40),
+                ('delete', 40, 41, 40, 40),
+                ('equal', 41, 81, 40, 80)])
+
+    def test_bjunk(self):
+        sm = difflib.SequenceMatcher(isjunk=lambda x: x == ' ',
+                a='a' * 40 + 'b' * 40, b='a' * 44 + 'b' * 40)
+        self.assertEqual(sm.bjunk, set())
+
+        sm = difflib.SequenceMatcher(isjunk=lambda x: x == ' ',
+                a='a' * 40 + 'b' * 40, b='a' * 44 + 'b' * 40 + ' ' * 20)
+        self.assertEqual(sm.bjunk, {' '})
+
+        sm = difflib.SequenceMatcher(isjunk=lambda x: x in [' ', 'b'],
+                a='a' * 40 + 'b' * 40, b='a' * 44 + 'b' * 40 + ' ' * 20)
+        self.assertEqual(sm.bjunk, {' ', 'b'})
+
+
+class TestAutojunk(unittest.TestCase):
+    """Tests for the autojunk parameter added in 2.7"""
+    def test_one_insert_homogenous_sequence(self):
+        # By default autojunk=True and the heuristic kicks in for a sequence
+        # of length 200+
+        seq1 = 'b' * 200
+        seq2 = 'a' + 'b' * 200
+
+        sm = difflib.SequenceMatcher(None, seq1, seq2)
+        self.assertAlmostEqual(sm.ratio(), 0, places=3)
+        self.assertEqual(sm.bpopular, {'b'})
+
+        # Now turn the heuristic off
+        sm = difflib.SequenceMatcher(None, seq1, seq2, autojunk=False)
+        self.assertAlmostEqual(sm.ratio(), 0.9975, places=3)
+        self.assertEqual(sm.bpopular, set())
+
+
+class TestSFbugs(unittest.TestCase):
     def test_ratio_for_null_seqn(self):
         # Check clearing of SF bug 763023
         s = difflib.SequenceMatcher(None, [], [])
@@ -184,7 +240,9 @@
 def test_main():
     difflib.HtmlDiff._default_prefix = 0
     Doctests = doctest.DocTestSuite(difflib)
-    run_unittest(TestSFpatches, TestSFbugs, TestOutputFormat, Doctests)
+    run_unittest(
+        TestWithAscii, TestAutojunk, TestSFpatches, TestSFbugs,
+        TestOutputFormat, Doctests)
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/pep-3151/Lib/test/test_dis.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_dis.py	(original)
+++ python/branches/pep-3151/Lib/test/test_dis.py	Sat Feb 26 08:16:32 2011
@@ -354,14 +354,14 @@
     def test_code_info(self):
         self.maxDiff = 1000
         for x, expected in self.test_pairs:
-            self.assertRegexpMatches(dis.code_info(x), expected)
+            self.assertRegex(dis.code_info(x), expected)
 
     def test_show_code(self):
         self.maxDiff = 1000
         for x, expected in self.test_pairs:
             with captured_stdout() as output:
                 dis.show_code(x)
-            self.assertRegexpMatches(output.getvalue(), expected+"\n")
+            self.assertRegex(output.getvalue(), expected+"\n")
 
 def test_main():
     run_unittest(DisTests, CodeInfoTests)

Modified: python/branches/pep-3151/Lib/test/test_doctest.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_doctest.py	(original)
+++ python/branches/pep-3151/Lib/test/test_doctest.py	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,7 @@
 from test import support
 import doctest
 import os
+import sys
 
 
 # NOTE: There are some additional tests relating to interaction with
@@ -373,7 +374,7 @@
     >>> tests = finder.find(sample_func)
 
     >>> print(tests)  # doctest: +ELLIPSIS
-    [<DocTest sample_func from ...:17 (1 example)>]
+    [<DocTest sample_func from ...:18 (1 example)>]
 
 The exact name depends on how test_doctest was invoked, so allow for
 leading path components.
@@ -1686,226 +1687,227 @@
 
 """
 
-def test_pdb_set_trace():
-    """Using pdb.set_trace from a doctest.
-
-    You can use pdb.set_trace from a doctest.  To do so, you must
-    retrieve the set_trace function from the pdb module at the time
-    you use it.  The doctest module changes sys.stdout so that it can
-    capture program output.  It also temporarily replaces pdb.set_trace
-    with a version that restores stdout.  This is necessary for you to
-    see debugger output.
-
-      >>> doc = '''
-      ... >>> x = 42
-      ... >>> raise Exception('clé')
-      ... Traceback (most recent call last):
-      ... Exception: clé
-      ... >>> import pdb; pdb.set_trace()
-      ... '''
-      >>> parser = doctest.DocTestParser()
-      >>> test = parser.get_doctest(doc, {}, "foo-bar at baz", "foo-bar at baz.py", 0)
-      >>> runner = doctest.DocTestRunner(verbose=False)
-
-    To demonstrate this, we'll create a fake standard input that
-    captures our debugger input:
-
-      >>> import tempfile
-      >>> real_stdin = sys.stdin
-      >>> sys.stdin = _FakeInput([
-      ...    'print(x)',  # print data defined by the example
-      ...    'continue', # stop debugging
-      ...    ''])
-
-      >>> try: runner.run(test)
-      ... finally: sys.stdin = real_stdin
-      --Return--
-      > <doctest foo-bar at baz[2]>(1)<module>()->None
-      -> import pdb; pdb.set_trace()
-      (Pdb) print(x)
-      42
-      (Pdb) continue
-      TestResults(failed=0, attempted=3)
-
-      You can also put pdb.set_trace in a function called from a test:
-
-      >>> def calls_set_trace():
-      ...    y=2
-      ...    import pdb; pdb.set_trace()
-
-      >>> doc = '''
-      ... >>> x=1
-      ... >>> calls_set_trace()
-      ... '''
-      >>> test = parser.get_doctest(doc, globals(), "foo-bar at baz", "foo-bar at baz.py", 0)
-      >>> real_stdin = sys.stdin
-      >>> sys.stdin = _FakeInput([
-      ...    'print(y)',  # print data defined in the function
-      ...    'up',       # out of function
-      ...    'print(x)',  # print data defined by the example
-      ...    'continue', # stop debugging
-      ...    ''])
-
-      >>> try:
-      ...     runner.run(test)
-      ... finally:
-      ...     sys.stdin = real_stdin
-      --Return--
-      > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
-      -> import pdb; pdb.set_trace()
-      (Pdb) print(y)
-      2
-      (Pdb) up
-      > <doctest foo-bar at baz[1]>(1)<module>()
-      -> calls_set_trace()
-      (Pdb) print(x)
-      1
-      (Pdb) continue
-      TestResults(failed=0, attempted=2)
-
-    During interactive debugging, source code is shown, even for
-    doctest examples:
-
-      >>> doc = '''
-      ... >>> def f(x):
-      ... ...     g(x*2)
-      ... >>> def g(x):
-      ... ...     print(x+3)
-      ... ...     import pdb; pdb.set_trace()
-      ... >>> f(3)
-      ... '''
-      >>> test = parser.get_doctest(doc, globals(), "foo-bar at baz", "foo-bar at baz.py", 0)
-      >>> real_stdin = sys.stdin
-      >>> sys.stdin = _FakeInput([
-      ...    'list',     # list source from example 2
-      ...    'next',     # return from g()
-      ...    'list',     # list source from example 1
-      ...    'next',     # return from f()
-      ...    'list',     # list source from example 3
-      ...    'continue', # stop debugging
-      ...    ''])
-      >>> try: runner.run(test)
-      ... finally: sys.stdin = real_stdin
-      ... # doctest: +NORMALIZE_WHITESPACE
-      --Return--
-      > <doctest foo-bar at baz[1]>(3)g()->None
-      -> import pdb; pdb.set_trace()
-      (Pdb) list
-        1     def g(x):
-        2         print(x+3)
-        3  ->     import pdb; pdb.set_trace()
-      [EOF]
-      (Pdb) next
-      --Return--
-      > <doctest foo-bar at baz[0]>(2)f()->None
-      -> g(x*2)
-      (Pdb) list
-        1     def f(x):
-        2  ->     g(x*2)
-      [EOF]
-      (Pdb) next
-      --Return--
-      > <doctest foo-bar at baz[2]>(1)<module>()->None
-      -> f(3)
-      (Pdb) list
-        1  -> f(3)
-      [EOF]
-      (Pdb) continue
-      **********************************************************************
-      File "foo-bar at baz.py", line 7, in foo-bar at baz
-      Failed example:
-          f(3)
-      Expected nothing
-      Got:
-          9
-      TestResults(failed=1, attempted=3)
-      """
-
-def test_pdb_set_trace_nested():
-    """This illustrates more-demanding use of set_trace with nested functions.
-
-    >>> class C(object):
-    ...     def calls_set_trace(self):
-    ...         y = 1
-    ...         import pdb; pdb.set_trace()
-    ...         self.f1()
-    ...         y = 2
-    ...     def f1(self):
-    ...         x = 1
-    ...         self.f2()
-    ...         x = 2
-    ...     def f2(self):
-    ...         z = 1
-    ...         z = 2
-
-    >>> calls_set_trace = C().calls_set_trace
-
-    >>> doc = '''
-    ... >>> a = 1
-    ... >>> calls_set_trace()
-    ... '''
-    >>> parser = doctest.DocTestParser()
-    >>> runner = doctest.DocTestRunner(verbose=False)
-    >>> test = parser.get_doctest(doc, globals(), "foo-bar at baz", "foo-bar at baz.py", 0)
-    >>> real_stdin = sys.stdin
-    >>> sys.stdin = _FakeInput([
-    ...    'print(y)',  # print data defined in the function
-    ...    'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
-    ...    'up', 'print(x)',
-    ...    'up', 'print(y)',
-    ...    'up', 'print(foo)',
-    ...    'continue', # stop debugging
-    ...    ''])
-
-    >>> try:
-    ...     runner.run(test)
-    ... finally:
-    ...     sys.stdin = real_stdin
-    ... # doctest: +REPORT_NDIFF
-    > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
-    -> self.f1()
-    (Pdb) print(y)
-    1
-    (Pdb) step
-    --Call--
-    > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
-    -> def f1(self):
-    (Pdb) step
-    > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
-    -> x = 1
-    (Pdb) step
-    > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
-    -> self.f2()
-    (Pdb) step
-    --Call--
-    > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
-    -> def f2(self):
-    (Pdb) step
-    > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
-    -> z = 1
-    (Pdb) step
-    > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
-    -> z = 2
-    (Pdb) print(z)
-    1
-    (Pdb) up
-    > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
-    -> self.f2()
-    (Pdb) print(x)
-    1
-    (Pdb) up
-    > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
-    -> self.f1()
-    (Pdb) print(y)
-    1
-    (Pdb) up
-    > <doctest foo-bar at baz[1]>(1)<module>()
-    -> calls_set_trace()
-    (Pdb) print(foo)
-    *** NameError: name 'foo' is not defined
-    (Pdb) continue
-    TestResults(failed=0, attempted=2)
-"""
+if not hasattr(sys, 'gettrace') or not sys.gettrace():
+    def test_pdb_set_trace():
+        """Using pdb.set_trace from a doctest.
+
+        You can use pdb.set_trace from a doctest.  To do so, you must
+        retrieve the set_trace function from the pdb module at the time
+        you use it.  The doctest module changes sys.stdout so that it can
+        capture program output.  It also temporarily replaces pdb.set_trace
+        with a version that restores stdout.  This is necessary for you to
+        see debugger output.
+
+          >>> doc = '''
+          ... >>> x = 42
+          ... >>> raise Exception('clé')
+          ... Traceback (most recent call last):
+          ... Exception: clé
+          ... >>> import pdb; pdb.set_trace()
+          ... '''
+          >>> parser = doctest.DocTestParser()
+          >>> test = parser.get_doctest(doc, {}, "foo-bar at baz", "foo-bar at baz.py", 0)
+          >>> runner = doctest.DocTestRunner(verbose=False)
+
+        To demonstrate this, we'll create a fake standard input that
+        captures our debugger input:
+
+          >>> import tempfile
+          >>> real_stdin = sys.stdin
+          >>> sys.stdin = _FakeInput([
+          ...    'print(x)',  # print data defined by the example
+          ...    'continue', # stop debugging
+          ...    ''])
+
+          >>> try: runner.run(test)
+          ... finally: sys.stdin = real_stdin
+          --Return--
+          > <doctest foo-bar at baz[2]>(1)<module>()->None
+          -> import pdb; pdb.set_trace()
+          (Pdb) print(x)
+          42
+          (Pdb) continue
+          TestResults(failed=0, attempted=3)
+
+          You can also put pdb.set_trace in a function called from a test:
+
+          >>> def calls_set_trace():
+          ...    y=2
+          ...    import pdb; pdb.set_trace()
+
+          >>> doc = '''
+          ... >>> x=1
+          ... >>> calls_set_trace()
+          ... '''
+          >>> test = parser.get_doctest(doc, globals(), "foo-bar at baz", "foo-bar at baz.py", 0)
+          >>> real_stdin = sys.stdin
+          >>> sys.stdin = _FakeInput([
+          ...    'print(y)',  # print data defined in the function
+          ...    'up',       # out of function
+          ...    'print(x)',  # print data defined by the example
+          ...    'continue', # stop debugging
+          ...    ''])
+
+          >>> try:
+          ...     runner.run(test)
+          ... finally:
+          ...     sys.stdin = real_stdin
+          --Return--
+          > <doctest test.test_doctest.test_pdb_set_trace[8]>(3)calls_set_trace()->None
+          -> import pdb; pdb.set_trace()
+          (Pdb) print(y)
+          2
+          (Pdb) up
+          > <doctest foo-bar at baz[1]>(1)<module>()
+          -> calls_set_trace()
+          (Pdb) print(x)
+          1
+          (Pdb) continue
+          TestResults(failed=0, attempted=2)
+
+        During interactive debugging, source code is shown, even for
+        doctest examples:
+
+          >>> doc = '''
+          ... >>> def f(x):
+          ... ...     g(x*2)
+          ... >>> def g(x):
+          ... ...     print(x+3)
+          ... ...     import pdb; pdb.set_trace()
+          ... >>> f(3)
+          ... '''
+          >>> test = parser.get_doctest(doc, globals(), "foo-bar at baz", "foo-bar at baz.py", 0)
+          >>> real_stdin = sys.stdin
+          >>> sys.stdin = _FakeInput([
+          ...    'list',     # list source from example 2
+          ...    'next',     # return from g()
+          ...    'list',     # list source from example 1
+          ...    'next',     # return from f()
+          ...    'list',     # list source from example 3
+          ...    'continue', # stop debugging
+          ...    ''])
+          >>> try: runner.run(test)
+          ... finally: sys.stdin = real_stdin
+          ... # doctest: +NORMALIZE_WHITESPACE
+          --Return--
+          > <doctest foo-bar at baz[1]>(3)g()->None
+          -> import pdb; pdb.set_trace()
+          (Pdb) list
+            1     def g(x):
+            2         print(x+3)
+            3  ->     import pdb; pdb.set_trace()
+          [EOF]
+          (Pdb) next
+          --Return--
+          > <doctest foo-bar at baz[0]>(2)f()->None
+          -> g(x*2)
+          (Pdb) list
+            1     def f(x):
+            2  ->     g(x*2)
+          [EOF]
+          (Pdb) next
+          --Return--
+          > <doctest foo-bar at baz[2]>(1)<module>()->None
+          -> f(3)
+          (Pdb) list
+            1  -> f(3)
+          [EOF]
+          (Pdb) continue
+          **********************************************************************
+          File "foo-bar at baz.py", line 7, in foo-bar at baz
+          Failed example:
+              f(3)
+          Expected nothing
+          Got:
+              9
+          TestResults(failed=1, attempted=3)
+          """
+
+    def test_pdb_set_trace_nested():
+        """This illustrates more-demanding use of set_trace with nested functions.
+
+        >>> class C(object):
+        ...     def calls_set_trace(self):
+        ...         y = 1
+        ...         import pdb; pdb.set_trace()
+        ...         self.f1()
+        ...         y = 2
+        ...     def f1(self):
+        ...         x = 1
+        ...         self.f2()
+        ...         x = 2
+        ...     def f2(self):
+        ...         z = 1
+        ...         z = 2
+
+        >>> calls_set_trace = C().calls_set_trace
+
+        >>> doc = '''
+        ... >>> a = 1
+        ... >>> calls_set_trace()
+        ... '''
+        >>> parser = doctest.DocTestParser()
+        >>> runner = doctest.DocTestRunner(verbose=False)
+        >>> test = parser.get_doctest(doc, globals(), "foo-bar at baz", "foo-bar at baz.py", 0)
+        >>> real_stdin = sys.stdin
+        >>> sys.stdin = _FakeInput([
+        ...    'print(y)',  # print data defined in the function
+        ...    'step', 'step', 'step', 'step', 'step', 'step', 'print(z)',
+        ...    'up', 'print(x)',
+        ...    'up', 'print(y)',
+        ...    'up', 'print(foo)',
+        ...    'continue', # stop debugging
+        ...    ''])
+
+        >>> try:
+        ...     runner.run(test)
+        ... finally:
+        ...     sys.stdin = real_stdin
+        ... # doctest: +REPORT_NDIFF
+        > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
+        -> self.f1()
+        (Pdb) print(y)
+        1
+        (Pdb) step
+        --Call--
+        > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(7)f1()
+        -> def f1(self):
+        (Pdb) step
+        > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(8)f1()
+        -> x = 1
+        (Pdb) step
+        > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
+        -> self.f2()
+        (Pdb) step
+        --Call--
+        > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(11)f2()
+        -> def f2(self):
+        (Pdb) step
+        > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(12)f2()
+        -> z = 1
+        (Pdb) step
+        > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(13)f2()
+        -> z = 2
+        (Pdb) print(z)
+        1
+        (Pdb) up
+        > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(9)f1()
+        -> self.f2()
+        (Pdb) print(x)
+        1
+        (Pdb) up
+        > <doctest test.test_doctest.test_pdb_set_trace_nested[0]>(5)calls_set_trace()
+        -> self.f1()
+        (Pdb) print(y)
+        1
+        (Pdb) up
+        > <doctest foo-bar at baz[1]>(1)<module>()
+        -> calls_set_trace()
+        (Pdb) print(foo)
+        *** NameError: name 'foo' is not defined
+        (Pdb) continue
+        TestResults(failed=0, attempted=2)
+    """
 
 def test_DocTestSuite():
     """DocTestSuite creates a unittest test suite from a doctest.

Modified: python/branches/pep-3151/Lib/test/test_epoll.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_epoll.py	(original)
+++ python/branches/pep-3151/Lib/test/test_epoll.py	Sat Feb 26 08:16:32 2011
@@ -56,7 +56,7 @@
         try:
             client.connect(('127.0.0.1', self.serverSocket.getsockname()[1]))
         except socket.error as e:
-            self.assertEquals(e.args[0], errno.EINPROGRESS)
+            self.assertEqual(e.args[0], errno.EINPROGRESS)
         else:
             raise AssertionError("Connect should have raised EINPROGRESS")
         server, addr = self.serverSocket.accept()
@@ -162,7 +162,7 @@
                     (server.fileno(), select.EPOLLOUT)]
         expected.sort()
 
-        self.assertEquals(events, expected)
+        self.assertEqual(events, expected)
         self.assertFalse(then - now > 0.01, then - now)
 
         now = time.time()
@@ -183,7 +183,7 @@
                     (server.fileno(), select.EPOLLIN | select.EPOLLOUT)]
         expected.sort()
 
-        self.assertEquals(events, expected)
+        self.assertEqual(events, expected)
 
         ep.unregister(client.fileno())
         ep.modify(server.fileno(), select.EPOLLOUT)
@@ -193,7 +193,7 @@
         self.assertFalse(then - now > 0.01)
 
         expected = [(server.fileno(), select.EPOLLOUT)]
-        self.assertEquals(events, expected)
+        self.assertEqual(events, expected)
 
     def test_errors(self):
         self.assertRaises(ValueError, select.epoll, -2)

Modified: python/branches/pep-3151/Lib/test/test_exceptions.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_exceptions.py	(original)
+++ python/branches/pep-3151/Lib/test/test_exceptions.py	Sat Feb 26 08:16:32 2011
@@ -7,7 +7,7 @@
 import weakref
 
 from test.support import (TESTFN, unlink, run_unittest, captured_output,
-                          gc_collect, cpython_only)
+                          gc_collect, cpython_only, no_tracing)
 
 # XXX This is not really enough, each *operation* should be tested!
 
@@ -22,8 +22,8 @@
             raise exc("spam")
         except exc as err:
             buf2 = str(err)
-        self.assertEquals(buf1, buf2)
-        self.assertEquals(exc.__name__, excname)
+        self.assertEqual(buf1, buf2)
+        self.assertEqual(exc.__name__, excname)
 
     def testRaising(self):
         self.raise_catch(AttributeError, "AttributeError")
@@ -156,7 +156,7 @@
             except TypeError as err:
                 exc, err, tb = sys.exc_info()
                 co = tb.tb_frame.f_code
-                self.assertEquals(co.co_name, "test_capi1")
+                self.assertEqual(co.co_name, "test_capi1")
                 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
             else:
                 self.fail("Expected exception")
@@ -168,10 +168,10 @@
             except RuntimeError as err:
                 exc, err, tb = sys.exc_info()
                 co = tb.tb_frame.f_code
-                self.assertEquals(co.co_name, "__init__")
+                self.assertEqual(co.co_name, "__init__")
                 self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
                 co2 = tb.tb_frame.f_back.f_code
-                self.assertEquals(co2.co_name, "test_capi2")
+                self.assertEqual(co2.co_name, "test_capi2")
             else:
                 self.fail("Expected exception")
 
@@ -314,16 +314,16 @@
                 raise
             else:
                 # Verify module name
-                self.assertEquals(type(e).__module__, 'builtins')
+                self.assertEqual(type(e).__module__, 'builtins')
                 # Verify no ref leaks in Exc_str()
                 s = str(e)
                 for checkArgName in expected:
                     value = getattr(e, checkArgName)
-                    self.assertEquals(repr(value),
-                                      repr(expected[checkArgName]),
-                                      '%r.%s == %r, expected %r' % (
-                                      e, checkArgName,
-                                      value, expected[checkArgName]))
+                    self.assertEqual(repr(value),
+                                     repr(expected[checkArgName]),
+                                     '%r.%s == %r, expected %r' % (
+                                     e, checkArgName,
+                                     value, expected[checkArgName]))
 
                 # test for pickling support
                 for p in [pickle]:
@@ -333,9 +333,9 @@
                         for checkArgName in expected:
                             got = repr(getattr(new, checkArgName))
                             want = repr(expected[checkArgName])
-                            self.assertEquals(got, want,
-                                              'pickled "%r", attribute "%s' %
-                                              (e, checkArgName))
+                            self.assertEqual(got, want,
+                                             'pickled "%r", attribute "%s' %
+                                             (e, checkArgName))
 
     def testWithTraceback(self):
         try:
@@ -410,8 +410,9 @@
                 self.fancy_arg = fancy_arg
 
         x = DerivedException(fancy_arg=42)
-        self.assertEquals(x.fancy_arg, 42)
+        self.assertEqual(x.fancy_arg, 42)
 
+    @no_tracing
     def testInfiniteRecursion(self):
         def f():
             return f()
@@ -571,24 +572,24 @@
                 yield sys.exc_info()[0]
             yield sys.exc_info()[0]
         g = yield_raise()
-        self.assertEquals(next(g), KeyError)
-        self.assertEquals(sys.exc_info()[0], None)
-        self.assertEquals(next(g), KeyError)
-        self.assertEquals(sys.exc_info()[0], None)
-        self.assertEquals(next(g), None)
+        self.assertEqual(next(g), KeyError)
+        self.assertEqual(sys.exc_info()[0], None)
+        self.assertEqual(next(g), KeyError)
+        self.assertEqual(sys.exc_info()[0], None)
+        self.assertEqual(next(g), None)
 
         # Same test, but inside an exception handler
         try:
             raise TypeError("foo")
         except TypeError:
             g = yield_raise()
-            self.assertEquals(next(g), KeyError)
-            self.assertEquals(sys.exc_info()[0], TypeError)
-            self.assertEquals(next(g), KeyError)
-            self.assertEquals(sys.exc_info()[0], TypeError)
-            self.assertEquals(next(g), TypeError)
+            self.assertEqual(next(g), KeyError)
+            self.assertEqual(sys.exc_info()[0], TypeError)
+            self.assertEqual(next(g), KeyError)
+            self.assertEqual(sys.exc_info()[0], TypeError)
+            self.assertEqual(next(g), TypeError)
             del g
-            self.assertEquals(sys.exc_info()[0], TypeError)
+            self.assertEqual(sys.exc_info()[0], TypeError)
 
     def test_generator_finalizing_and_exc_info(self):
         # See #7173
@@ -616,7 +617,7 @@
             raise Exception(MyObject())
         except:
             pass
-        self.assertEquals(e, (None, None, None))
+        self.assertEqual(e, (None, None, None))
 
     def testUnicodeChangeAttributes(self):
         # See issue 7309. This was a crasher.
@@ -655,6 +656,7 @@
         u.start = 1000
         self.assertEqual(str(u), "can't translate characters in position 1000-4: 965230951443685724997")
 
+    @no_tracing
     def test_badisinstance(self):
         # Bug #2542: if issubclass(e, MyException) raises an exception,
         # it should be ignored
@@ -765,6 +767,7 @@
             self.fail("MemoryError not raised")
         self.assertEqual(wr(), None)
 
+    @no_tracing
     def test_recursion_error_cleanup(self):
         # Same test as above, but with "recursion exceeded" errors
         class C:

Modified: python/branches/pep-3151/Lib/test/test_file.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_file.py	(original)
+++ python/branches/pep-3151/Lib/test/test_file.py	Sat Feb 26 08:16:32 2011
@@ -25,7 +25,7 @@
         # verify weak references
         p = proxy(self.f)
         p.write(b'teststring')
-        self.assertEquals(self.f.tell(), p.tell())
+        self.assertEqual(self.f.tell(), p.tell())
         self.f.close()
         self.f = None
         self.assertRaises(ReferenceError, getattr, p, 'tell')
@@ -44,7 +44,7 @@
         a = array('b', b'x'*10)
         self.f = self.open(TESTFN, 'rb')
         n = self.f.readinto(a)
-        self.assertEquals(b'12', a.tobytes()[:n])
+        self.assertEqual(b'12', a.tobytes()[:n])
 
     def testReadinto_text(self):
         # verify readinto refuses text files
@@ -61,7 +61,7 @@
         self.f.close()
         self.f = self.open(TESTFN, 'rb')
         buf = self.f.read()
-        self.assertEquals(buf, b'12')
+        self.assertEqual(buf, b'12')
 
     def testWritelinesIntegers(self):
         # verify writelines with integers
@@ -82,7 +82,7 @@
 
     def testErrors(self):
         f = self.f
-        self.assertEquals(f.name, TESTFN)
+        self.assertEqual(f.name, TESTFN)
         self.assertTrue(not f.isatty())
         self.assertTrue(not f.closed)
 
@@ -118,12 +118,12 @@
             self.assertRaises(ValueError, method, *args)
 
         # file is closed, __exit__ shouldn't do anything
-        self.assertEquals(self.f.__exit__(None, None, None), None)
+        self.assertEqual(self.f.__exit__(None, None, None), None)
         # it must also return None if an exception was given
         try:
             1/0
         except:
-            self.assertEquals(self.f.__exit__(*sys.exc_info()), None)
+            self.assertEqual(self.f.__exit__(*sys.exc_info()), None)
 
     def testReadWhenWriting(self):
         self.assertRaises(IOError, self.f.read)
@@ -189,7 +189,7 @@
                 f.close()
             except IOError as msg:
                 self.fail('error setting buffer size %d: %s' % (s, str(msg)))
-            self.assertEquals(d, s)
+            self.assertEqual(d, s)
 
     def testTruncateOnWindows(self):
         # SF bug <http://www.python.org/sf/801631>

Modified: python/branches/pep-3151/Lib/test/test_fileio.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_fileio.py	(original)
+++ python/branches/pep-3151/Lib/test/test_fileio.py	Sat Feb 26 08:16:32 2011
@@ -27,31 +27,31 @@
         # verify weak references
         p = proxy(self.f)
         p.write(bytes(range(10)))
-        self.assertEquals(self.f.tell(), p.tell())
+        self.assertEqual(self.f.tell(), p.tell())
         self.f.close()
         self.f = None
         self.assertRaises(ReferenceError, getattr, p, 'tell')
 
     def testSeekTell(self):
         self.f.write(bytes(range(20)))
-        self.assertEquals(self.f.tell(), 20)
+        self.assertEqual(self.f.tell(), 20)
         self.f.seek(0)
-        self.assertEquals(self.f.tell(), 0)
+        self.assertEqual(self.f.tell(), 0)
         self.f.seek(10)
-        self.assertEquals(self.f.tell(), 10)
+        self.assertEqual(self.f.tell(), 10)
         self.f.seek(5, 1)
-        self.assertEquals(self.f.tell(), 15)
+        self.assertEqual(self.f.tell(), 15)
         self.f.seek(-5, 1)
-        self.assertEquals(self.f.tell(), 10)
+        self.assertEqual(self.f.tell(), 10)
         self.f.seek(-5, 2)
-        self.assertEquals(self.f.tell(), 15)
+        self.assertEqual(self.f.tell(), 15)
 
     def testAttributes(self):
         # verify expected attributes exist
         f = self.f
 
-        self.assertEquals(f.mode, "wb")
-        self.assertEquals(f.closed, False)
+        self.assertEqual(f.mode, "wb")
+        self.assertEqual(f.closed, False)
 
         # verify the attributes are readonly
         for attr in 'mode', 'closed':
@@ -65,7 +65,7 @@
         a = array('b', b'x'*10)
         self.f = _FileIO(TESTFN, 'r')
         n = self.f.readinto(a)
-        self.assertEquals(array('b', [1, 2]), a[:n])
+        self.assertEqual(array('b', [1, 2]), a[:n])
 
     def test_none_args(self):
         self.f.write(b"hi\nbye\nabc")
@@ -80,19 +80,19 @@
         self.assertRaises(TypeError, self.f.write, "Hello!")
 
     def testRepr(self):
-        self.assertEquals(repr(self.f), "<_io.FileIO name=%r mode=%r>"
+        self.assertEqual(repr(self.f), "<_io.FileIO name=%r mode=%r>"
                                         % (self.f.name, self.f.mode))
         del self.f.name
-        self.assertEquals(repr(self.f), "<_io.FileIO fd=%r mode=%r>"
+        self.assertEqual(repr(self.f), "<_io.FileIO fd=%r mode=%r>"
                                         % (self.f.fileno(), self.f.mode))
         self.f.close()
-        self.assertEquals(repr(self.f), "<_io.FileIO [closed]>")
+        self.assertEqual(repr(self.f), "<_io.FileIO [closed]>")
 
     def testErrors(self):
         f = self.f
         self.assertTrue(not f.isatty())
         self.assertTrue(not f.closed)
-        #self.assertEquals(f.name, TESTFN)
+        #self.assertEqual(f.name, TESTFN)
         self.assertRaises(ValueError, f.read, 10) # Open for reading
         f.close()
         self.assertTrue(f.closed)
@@ -233,22 +233,22 @@
     def testAbles(self):
         try:
             f = _FileIO(TESTFN, "w")
-            self.assertEquals(f.readable(), False)
-            self.assertEquals(f.writable(), True)
-            self.assertEquals(f.seekable(), True)
+            self.assertEqual(f.readable(), False)
+            self.assertEqual(f.writable(), True)
+            self.assertEqual(f.seekable(), True)
             f.close()
 
             f = _FileIO(TESTFN, "r")
-            self.assertEquals(f.readable(), True)
-            self.assertEquals(f.writable(), False)
-            self.assertEquals(f.seekable(), True)
+            self.assertEqual(f.readable(), True)
+            self.assertEqual(f.writable(), False)
+            self.assertEqual(f.seekable(), True)
             f.close()
 
             f = _FileIO(TESTFN, "a+")
-            self.assertEquals(f.readable(), True)
-            self.assertEquals(f.writable(), True)
-            self.assertEquals(f.seekable(), True)
-            self.assertEquals(f.isatty(), False)
+            self.assertEqual(f.readable(), True)
+            self.assertEqual(f.writable(), True)
+            self.assertEqual(f.seekable(), True)
+            self.assertEqual(f.isatty(), False)
             f.close()
 
             if sys.platform != "win32":
@@ -260,14 +260,14 @@
                     # OS'es that don't support /dev/tty.
                     pass
                 else:
-                    self.assertEquals(f.readable(), False)
-                    self.assertEquals(f.writable(), True)
+                    self.assertEqual(f.readable(), False)
+                    self.assertEqual(f.writable(), True)
                     if sys.platform != "darwin" and \
                        'bsd' not in sys.platform and \
                        not sys.platform.startswith('sunos'):
                         # Somehow /dev/tty appears seekable on some BSDs
-                        self.assertEquals(f.seekable(), False)
-                    self.assertEquals(f.isatty(), True)
+                        self.assertEqual(f.seekable(), False)
+                    self.assertEqual(f.isatty(), True)
                     f.close()
         finally:
             os.unlink(TESTFN)
@@ -301,7 +301,7 @@
             f.write(b"abc")
             f.close()
             with open(TESTFN, "rb") as f:
-                self.assertEquals(f.read(), b"abc")
+                self.assertEqual(f.read(), b"abc")
         finally:
             os.unlink(TESTFN)
 

Modified: python/branches/pep-3151/Lib/test/test_float.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_float.py	(original)
+++ python/branches/pep-3151/Lib/test/test_float.py	Sat Feb 26 08:16:32 2011
@@ -16,10 +16,6 @@
                                          "requires __getformat__")
 requires_setformat = unittest.skipUnless(hasattr(float, "__setformat__"),
                                          "requires __setformat__")
-# decorator for skipping tests on non-IEEE 754 platforms
-requires_IEEE_754 = unittest.skipUnless(have_getformat and
-    float.__getformat__("double").startswith("IEEE"),
-    "test requires IEEE 754 doubles")
 
 #locate file with float format test values
 test_dir = os.path.dirname(__file__) or os.curdir
@@ -43,14 +39,30 @@
         self.assertRaises(ValueError, float, "+.inf")
         self.assertRaises(ValueError, float, ".")
         self.assertRaises(ValueError, float, "-.")
+        self.assertRaises(ValueError, float, b"-")
+        self.assertRaises(TypeError, float, {})
+        # Lone surrogate
+        self.assertRaises(UnicodeEncodeError, float, '\uD8F0')
         # check that we don't accept alternate exponent markers
         self.assertRaises(ValueError, float, "-1.7d29")
         self.assertRaises(ValueError, float, "3D-14")
-        self.assertEqual(float(b"  \u0663.\u0661\u0664  ".decode('raw-unicode-escape')), 3.14)
+        self.assertEqual(float("  \u0663.\u0661\u0664  "), 3.14)
+        self.assertEqual(float("\N{EM SPACE}3.14\N{EN SPACE}"), 3.14)
         # extra long strings should not be a problem
         float(b'.' + b'1'*1000)
         float('.' + '1'*1000)
 
+    def test_error_message(self):
+        testlist = ('\xbd', '123\xbd', '  123 456  ')
+        for s in testlist:
+            try:
+                float(s)
+            except ValueError as e:
+                self.assertIn(s.strip(), e.args[0])
+            else:
+                self.fail("Expected int(%r) to raise a ValueError", s)
+
+
     @support.run_with_locale('LC_NUMERIC', 'fr_FR', 'de_DE')
     def test_float_with_comma(self):
         # set locale to something that doesn't use '.' for the decimal point
@@ -76,7 +88,7 @@
         self.assertRaises(ValueError, float, "  -0x3.p-1  ")
         self.assertRaises(ValueError, float, "  +0x3.p-1  ")
         self.assertEqual(float("  25.e-1  "), 2.5)
-        self.assertEqual(support.fcmp(float("  .25e-1  "), .025), 0)
+        self.assertAlmostEqual(float("  .25e-1  "), .025)
 
     def test_floatconversion(self):
         # Make sure that calls to __float__() work properly
@@ -180,7 +192,27 @@
         # distingishes -0.0 and 0.0.
         self.assertEqual((a, copysign(1.0, a)), (b, copysign(1.0, b)))
 
-    @requires_IEEE_754
+    @support.requires_IEEE_754
+    def test_float_mod(self):
+        # Check behaviour of % operator for IEEE 754 special cases.
+        # In particular, check signs of zeros.
+        mod = operator.mod
+
+        self.assertEqualAndEqualSign(mod(-1.0, 1.0), 0.0)
+        self.assertEqualAndEqualSign(mod(-1e-100, 1.0), 1.0)
+        self.assertEqualAndEqualSign(mod(-0.0, 1.0), 0.0)
+        self.assertEqualAndEqualSign(mod(0.0, 1.0), 0.0)
+        self.assertEqualAndEqualSign(mod(1e-100, 1.0), 1e-100)
+        self.assertEqualAndEqualSign(mod(1.0, 1.0), 0.0)
+
+        self.assertEqualAndEqualSign(mod(-1.0, -1.0), -0.0)
+        self.assertEqualAndEqualSign(mod(-1e-100, -1.0), -1e-100)
+        self.assertEqualAndEqualSign(mod(-0.0, -1.0), -0.0)
+        self.assertEqualAndEqualSign(mod(0.0, -1.0), -0.0)
+        self.assertEqualAndEqualSign(mod(1e-100, -1.0), -1.0)
+        self.assertEqualAndEqualSign(mod(1.0, -1.0), -0.0)
+
+    @support.requires_IEEE_754
     def test_float_pow(self):
         # test builtin pow and ** operator for IEEE 754 special cases.
         # Special cases taken from section F.9.4.4 of the C99 specification
@@ -467,7 +499,7 @@
 
 class IEEEFormatTestCase(unittest.TestCase):
 
-    @requires_IEEE_754
+    @support.requires_IEEE_754
     def test_double_specials_do_unpack(self):
         for fmt, data in [('>d', BE_DOUBLE_INF),
                           ('>d', BE_DOUBLE_NAN),
@@ -475,7 +507,7 @@
                           ('<d', LE_DOUBLE_NAN)]:
             struct.unpack(fmt, data)
 
-    @requires_IEEE_754
+    @support.requires_IEEE_754
     def test_float_specials_do_unpack(self):
         for fmt, data in [('>f', BE_FLOAT_INF),
                           ('>f', BE_FLOAT_NAN),
@@ -538,7 +570,7 @@
         self.assertEqual(format(INF, 'f'), 'inf')
         self.assertEqual(format(INF, 'F'), 'INF')
 
-    @requires_IEEE_754
+    @support.requires_IEEE_754
     def test_format_testfile(self):
         with open(format_testfile) as testfile:
             for line in testfile:
@@ -554,9 +586,9 @@
                 self.assertEqual(fmt % -float(arg), '-' + rhs)
 
     def test_issue5864(self):
-        self.assertEquals(format(123.456, '.4'), '123.5')
-        self.assertEquals(format(1234.56, '.4'), '1.235e+03')
-        self.assertEquals(format(12345.6, '.4'), '1.235e+04')
+        self.assertEqual(format(123.456, '.4'), '123.5')
+        self.assertEqual(format(1234.56, '.4'), '1.235e+03')
+        self.assertEqual(format(12345.6, '.4'), '1.235e+04')
 
 class ReprTestCase(unittest.TestCase):
     def test_repr(self):
@@ -622,7 +654,7 @@
             self.assertEqual(repr(float(s)), str(float(s)))
             self.assertEqual(repr(float(negs)), str(float(negs)))
 
- at requires_IEEE_754
+ at support.requires_IEEE_754
 class RoundTestCase(unittest.TestCase):
 
     def test_inf_nan(self):
@@ -706,11 +738,8 @@
         def test(fmt, value, expected):
             # Test with both % and format().
             self.assertEqual(fmt % value, expected, fmt)
-            if not '#' in fmt:
-                # Until issue 7094 is implemented, format() for floats doesn't
-                #  support '#' formatting
-                fmt = fmt[1:] # strip off the %
-                self.assertEqual(format(value, fmt), expected, fmt)
+            fmt = fmt[1:] # strip off the %
+            self.assertEqual(format(value, fmt), expected, fmt)
 
         for fmt in ['%e', '%f', '%g', '%.0e', '%.6f', '%.20g',
                     '%#e', '%#f', '%#g', '%#.20e', '%#.15f', '%#.3g']:

Modified: python/branches/pep-3151/Lib/test/test_fork1.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_fork1.py	(original)
+++ python/branches/pep-3151/Lib/test/test_fork1.py	Sat Feb 26 08:16:32 2011
@@ -8,13 +8,14 @@
 import time
 
 from test.fork_wait import ForkWait
-from test.support import run_unittest, reap_children, get_attribute, import_module
+from test.support import (run_unittest, reap_children, get_attribute,
+                          import_module, verbose)
+
 threading = import_module('threading')
 
 # Skip test if fork does not exist.
 get_attribute(os, 'fork')
 
-
 class ForkTest(ForkWait):
     def wait_impl(self, cpid):
         for i in range(10):
@@ -28,7 +29,8 @@
         self.assertEqual(spid, cpid)
         self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
 
-    def test_import_lock_fork(self):
+    def test_threaded_import_lock_fork(self):
+        """Check fork() in main thread works while a subthread is doing an import"""
         import_started = threading.Event()
         fake_module_name = "fake test module"
         partial_module = "partial"
@@ -45,11 +47,16 @@
         import_started.wait()
         pid = os.fork()
         try:
+            # PyOS_BeforeFork should have waited for the import to complete
+            # before forking, so the child can recreate the import lock
+            # correctly, but also won't see a partially initialised module
             if not pid:
                 m = __import__(fake_module_name)
                 if m == complete_module:
                     os._exit(0)
                 else:
+                    if verbose > 1:
+                        print("Child encountered partial module")
                     os._exit(1)
             else:
                 t.join()
@@ -63,6 +70,39 @@
             except OSError:
                 pass
 
+
+    def test_nested_import_lock_fork(self):
+        """Check fork() in main thread works while the main thread is doing an import"""
+        # Issue 9573: this used to trigger RuntimeError in the child process
+        def fork_with_import_lock(level):
+            release = 0
+            in_child = False
+            try:
+                try:
+                    for i in range(level):
+                        imp.acquire_lock()
+                        release += 1
+                    pid = os.fork()
+                    in_child = not pid
+                finally:
+                    for i in range(release):
+                        imp.release_lock()
+            except RuntimeError:
+                if in_child:
+                    if verbose > 1:
+                        print("RuntimeError in child")
+                    os._exit(1)
+                raise
+            if in_child:
+                os._exit(0)
+            self.wait_impl(pid)
+
+        # Check this works with various levels of nested
+        # import in the main thread
+        for level in range(5):
+            fork_with_import_lock(level)
+
+
 def test_main():
     run_unittest(ForkTest)
     reap_children()

Modified: python/branches/pep-3151/Lib/test/test_fractions.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_fractions.py	(original)
+++ python/branches/pep-3151/Lib/test/test_fractions.py	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,7 @@
 """Tests for Lib/fractions.py."""
 
 from decimal import Decimal
-from test.support import run_unittest
+from test.support import run_unittest, requires_IEEE_754
 import math
 import numbers
 import operator
@@ -12,11 +12,6 @@
 F = fractions.Fraction
 gcd = fractions.gcd
 
-# decorator for skipping tests on non-IEEE 754 platforms
-requires_IEEE_754 = unittest.skipUnless(
-    float.__getformat__("double").startswith("IEEE"),
-    "test requires IEEE 754 doubles")
-
 class DummyFloat(object):
     """Dummy float class for testing comparisons with Fractions"""
 
@@ -84,16 +79,16 @@
 class GcdTest(unittest.TestCase):
 
     def testMisc(self):
-        self.assertEquals(0, gcd(0, 0))
-        self.assertEquals(1, gcd(1, 0))
-        self.assertEquals(-1, gcd(-1, 0))
-        self.assertEquals(1, gcd(0, 1))
-        self.assertEquals(-1, gcd(0, -1))
-        self.assertEquals(1, gcd(7, 1))
-        self.assertEquals(-1, gcd(7, -1))
-        self.assertEquals(1, gcd(-23, 15))
-        self.assertEquals(12, gcd(120, 84))
-        self.assertEquals(-12, gcd(84, -120))
+        self.assertEqual(0, gcd(0, 0))
+        self.assertEqual(1, gcd(1, 0))
+        self.assertEqual(-1, gcd(-1, 0))
+        self.assertEqual(1, gcd(0, 1))
+        self.assertEqual(-1, gcd(0, -1))
+        self.assertEqual(1, gcd(7, 1))
+        self.assertEqual(-1, gcd(7, -1))
+        self.assertEqual(1, gcd(-23, 15))
+        self.assertEqual(12, gcd(120, 84))
+        self.assertEqual(-12, gcd(84, -120))
 
 
 def _components(r):
@@ -104,8 +99,8 @@
 
     def assertTypedEquals(self, expected, actual):
         """Asserts that both the types and values are the same."""
-        self.assertEquals(type(expected), type(actual))
-        self.assertEquals(expected, actual)
+        self.assertEqual(type(expected), type(actual))
+        self.assertEqual(expected, actual)
 
     def assertRaisesMessage(self, exc_type, message,
                             callable, *args, **kwargs):
@@ -113,25 +108,25 @@
         try:
             callable(*args, **kwargs)
         except exc_type as e:
-            self.assertEquals(message, str(e))
+            self.assertEqual(message, str(e))
         else:
             self.fail("%s not raised" % exc_type.__name__)
 
     def testInit(self):
-        self.assertEquals((0, 1), _components(F()))
-        self.assertEquals((7, 1), _components(F(7)))
-        self.assertEquals((7, 3), _components(F(F(7, 3))))
-
-        self.assertEquals((-1, 1), _components(F(-1, 1)))
-        self.assertEquals((-1, 1), _components(F(1, -1)))
-        self.assertEquals((1, 1), _components(F(-2, -2)))
-        self.assertEquals((1, 2), _components(F(5, 10)))
-        self.assertEquals((7, 15), _components(F(7, 15)))
-        self.assertEquals((10**23, 1), _components(F(10**23)))
-
-        self.assertEquals((3, 77), _components(F(F(3, 7), 11)))
-        self.assertEquals((-9, 5), _components(F(2, F(-10, 9))))
-        self.assertEquals((2486, 2485), _components(F(F(22, 7), F(355, 113))))
+        self.assertEqual((0, 1), _components(F()))
+        self.assertEqual((7, 1), _components(F(7)))
+        self.assertEqual((7, 3), _components(F(F(7, 3))))
+
+        self.assertEqual((-1, 1), _components(F(-1, 1)))
+        self.assertEqual((-1, 1), _components(F(1, -1)))
+        self.assertEqual((1, 1), _components(F(-2, -2)))
+        self.assertEqual((1, 2), _components(F(5, 10)))
+        self.assertEqual((7, 15), _components(F(7, 15)))
+        self.assertEqual((10**23, 1), _components(F(10**23)))
+
+        self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
+        self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
+        self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))
 
         self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
                                  F, 12, 0)
@@ -143,41 +138,41 @@
 
     @requires_IEEE_754
     def testInitFromFloat(self):
-        self.assertEquals((5, 2), _components(F(2.5)))
-        self.assertEquals((0, 1), _components(F(-0.0)))
-        self.assertEquals((3602879701896397, 36028797018963968),
-                          _components(F(0.1)))
+        self.assertEqual((5, 2), _components(F(2.5)))
+        self.assertEqual((0, 1), _components(F(-0.0)))
+        self.assertEqual((3602879701896397, 36028797018963968),
+                         _components(F(0.1)))
         self.assertRaises(TypeError, F, float('nan'))
         self.assertRaises(TypeError, F, float('inf'))
         self.assertRaises(TypeError, F, float('-inf'))
 
     def testInitFromDecimal(self):
-        self.assertEquals((11, 10),
-                          _components(F(Decimal('1.1'))))
-        self.assertEquals((7, 200),
-                          _components(F(Decimal('3.5e-2'))))
-        self.assertEquals((0, 1),
-                          _components(F(Decimal('.000e20'))))
+        self.assertEqual((11, 10),
+                         _components(F(Decimal('1.1'))))
+        self.assertEqual((7, 200),
+                         _components(F(Decimal('3.5e-2'))))
+        self.assertEqual((0, 1),
+                         _components(F(Decimal('.000e20'))))
         self.assertRaises(TypeError, F, Decimal('nan'))
         self.assertRaises(TypeError, F, Decimal('snan'))
         self.assertRaises(TypeError, F, Decimal('inf'))
         self.assertRaises(TypeError, F, Decimal('-inf'))
 
     def testFromString(self):
-        self.assertEquals((5, 1), _components(F("5")))
-        self.assertEquals((3, 2), _components(F("3/2")))
-        self.assertEquals((3, 2), _components(F(" \n  +3/2")))
-        self.assertEquals((-3, 2), _components(F("-3/2  ")))
-        self.assertEquals((13, 2), _components(F("    013/02 \n  ")))
-        self.assertEquals((16, 5), _components(F(" 3.2 ")))
-        self.assertEquals((-16, 5), _components(F(" -3.2 ")))
-        self.assertEquals((-3, 1), _components(F(" -3. ")))
-        self.assertEquals((3, 5), _components(F(" .6 ")))
-        self.assertEquals((1, 3125), _components(F("32.e-5")))
-        self.assertEquals((1000000, 1), _components(F("1E+06")))
-        self.assertEquals((-12300, 1), _components(F("-1.23e4")))
-        self.assertEquals((0, 1), _components(F(" .0e+0\t")))
-        self.assertEquals((0, 1), _components(F("-0.000e0")))
+        self.assertEqual((5, 1), _components(F("5")))
+        self.assertEqual((3, 2), _components(F("3/2")))
+        self.assertEqual((3, 2), _components(F(" \n  +3/2")))
+        self.assertEqual((-3, 2), _components(F("-3/2  ")))
+        self.assertEqual((13, 2), _components(F("    013/02 \n  ")))
+        self.assertEqual((16, 5), _components(F(" 3.2 ")))
+        self.assertEqual((-16, 5), _components(F(" -3.2 ")))
+        self.assertEqual((-3, 1), _components(F(" -3. ")))
+        self.assertEqual((3, 5), _components(F(" .6 ")))
+        self.assertEqual((1, 3125), _components(F("32.e-5")))
+        self.assertEqual((1000000, 1), _components(F("1E+06")))
+        self.assertEqual((-12300, 1), _components(F("-1.23e4")))
+        self.assertEqual((0, 1), _components(F(" .0e+0\t")))
+        self.assertEqual((0, 1), _components(F("-0.000e0")))
 
         self.assertRaisesMessage(
             ZeroDivisionError, "Fraction(3, 0)",
@@ -219,33 +214,33 @@
     def testImmutable(self):
         r = F(7, 3)
         r.__init__(2, 15)
-        self.assertEquals((7, 3), _components(r))
+        self.assertEqual((7, 3), _components(r))
 
         self.assertRaises(AttributeError, setattr, r, 'numerator', 12)
         self.assertRaises(AttributeError, setattr, r, 'denominator', 6)
-        self.assertEquals((7, 3), _components(r))
+        self.assertEqual((7, 3), _components(r))
 
         # But if you _really_ need to:
         r._numerator = 4
         r._denominator = 2
-        self.assertEquals((4, 2), _components(r))
+        self.assertEqual((4, 2), _components(r))
         # Which breaks some important operations:
-        self.assertNotEquals(F(4, 2), r)
+        self.assertNotEqual(F(4, 2), r)
 
     def testFromFloat(self):
         self.assertRaises(TypeError, F.from_float, 3+4j)
-        self.assertEquals((10, 1), _components(F.from_float(10)))
+        self.assertEqual((10, 1), _components(F.from_float(10)))
         bigint = 1234567890123456789
-        self.assertEquals((bigint, 1), _components(F.from_float(bigint)))
-        self.assertEquals((0, 1), _components(F.from_float(-0.0)))
-        self.assertEquals((10, 1), _components(F.from_float(10.0)))
-        self.assertEquals((-5, 2), _components(F.from_float(-2.5)))
-        self.assertEquals((99999999999999991611392, 1),
-                          _components(F.from_float(1e23)))
-        self.assertEquals(float(10**23), float(F.from_float(1e23)))
-        self.assertEquals((3602879701896397, 1125899906842624),
-                          _components(F.from_float(3.2)))
-        self.assertEquals(3.2, float(F.from_float(3.2)))
+        self.assertEqual((bigint, 1), _components(F.from_float(bigint)))
+        self.assertEqual((0, 1), _components(F.from_float(-0.0)))
+        self.assertEqual((10, 1), _components(F.from_float(10.0)))
+        self.assertEqual((-5, 2), _components(F.from_float(-2.5)))
+        self.assertEqual((99999999999999991611392, 1),
+                         _components(F.from_float(1e23)))
+        self.assertEqual(float(10**23), float(F.from_float(1e23)))
+        self.assertEqual((3602879701896397, 1125899906842624),
+                         _components(F.from_float(3.2)))
+        self.assertEqual(3.2, float(F.from_float(3.2)))
 
         inf = 1e1000
         nan = inf - inf
@@ -261,13 +256,13 @@
 
     def testFromDecimal(self):
         self.assertRaises(TypeError, F.from_decimal, 3+4j)
-        self.assertEquals(F(10, 1), F.from_decimal(10))
-        self.assertEquals(F(0), F.from_decimal(Decimal("-0")))
-        self.assertEquals(F(5, 10), F.from_decimal(Decimal("0.5")))
-        self.assertEquals(F(5, 1000), F.from_decimal(Decimal("5e-3")))
-        self.assertEquals(F(5000), F.from_decimal(Decimal("5e3")))
-        self.assertEquals(1 - F(1, 10**30),
-                          F.from_decimal(Decimal("0." + "9" * 30)))
+        self.assertEqual(F(10, 1), F.from_decimal(10))
+        self.assertEqual(F(0), F.from_decimal(Decimal("-0")))
+        self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5")))
+        self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3")))
+        self.assertEqual(F(5000), F.from_decimal(Decimal("5e3")))
+        self.assertEqual(1 - F(1, 10**30),
+                         F.from_decimal(Decimal("0." + "9" * 30)))
 
         self.assertRaisesMessage(
             TypeError, "Cannot convert Infinity to Fraction.",
@@ -303,15 +298,15 @@
         self.assertTypedEquals(-2, round(F(-15, 10)))
         self.assertTypedEquals(-1, round(F(-7, 10)))
 
-        self.assertEquals(False, bool(F(0, 1)))
-        self.assertEquals(True, bool(F(3, 2)))
+        self.assertEqual(False, bool(F(0, 1)))
+        self.assertEqual(True, bool(F(3, 2)))
         self.assertTypedEquals(0.1, float(F(1, 10)))
 
         # Check that __float__ isn't implemented by converting the
         # numerator and denominator to float before dividing.
         self.assertRaises(OverflowError, float, int('2'*400+'7'))
-        self.assertAlmostEquals(2.0/3,
-                                float(F(int('2'*400+'7'), int('3'*400+'1'))))
+        self.assertAlmostEqual(2.0/3,
+                               float(F(int('2'*400+'7'), int('3'*400+'1'))))
 
         self.assertTypedEquals(0.1+0j, complex(F(1,10)))
 
@@ -324,19 +319,19 @@
 
 
     def testArithmetic(self):
-        self.assertEquals(F(1, 2), F(1, 10) + F(2, 5))
-        self.assertEquals(F(-3, 10), F(1, 10) - F(2, 5))
-        self.assertEquals(F(1, 25), F(1, 10) * F(2, 5))
-        self.assertEquals(F(1, 4), F(1, 10) / F(2, 5))
+        self.assertEqual(F(1, 2), F(1, 10) + F(2, 5))
+        self.assertEqual(F(-3, 10), F(1, 10) - F(2, 5))
+        self.assertEqual(F(1, 25), F(1, 10) * F(2, 5))
+        self.assertEqual(F(1, 4), F(1, 10) / F(2, 5))
         self.assertTypedEquals(2, F(9, 10) // F(2, 5))
         self.assertTypedEquals(10**23, F(10**23, 1) // F(1))
-        self.assertEquals(F(2, 3), F(-7, 3) % F(3, 2))
-        self.assertEquals(F(8, 27), F(2, 3) ** F(3))
-        self.assertEquals(F(27, 8), F(2, 3) ** F(-3))
+        self.assertEqual(F(2, 3), F(-7, 3) % F(3, 2))
+        self.assertEqual(F(8, 27), F(2, 3) ** F(3))
+        self.assertEqual(F(27, 8), F(2, 3) ** F(-3))
         self.assertTypedEquals(2.0, F(4) ** F(1, 2))
         z = pow(F(-1), F(1, 2))
-        self.assertAlmostEquals(z.real, 0)
-        self.assertEquals(z.imag, 1)
+        self.assertAlmostEqual(z.real, 0)
+        self.assertEqual(z.imag, 1)
 
     def testMixedArithmetic(self):
         self.assertTypedEquals(F(11, 10), F(1, 10) + 1)
@@ -387,8 +382,8 @@
         self.assertTypedEquals(0.1 + 0j, F(1, 10) ** (1.0 + 0j))
         self.assertTypedEquals(4 , 2 ** F(2, 1))
         z = pow(-1, F(1, 2))
-        self.assertAlmostEquals(0, z.real)
-        self.assertEquals(1, z.imag)
+        self.assertAlmostEqual(0, z.real)
+        self.assertEqual(1, z.imag)
         self.assertTypedEquals(F(1, 4) , 2 ** F(-2, 1))
         self.assertTypedEquals(2.0 , 4 ** F(1, 2))
         self.assertTypedEquals(0.25, 2.0 ** F(-2, 1))
@@ -534,18 +529,21 @@
         self.assertFalse(float('-inf') == F(2, 5))
 
     def testStringification(self):
-        self.assertEquals("Fraction(7, 3)", repr(F(7, 3)))
-        self.assertEquals("Fraction(6283185307, 2000000000)",
-                          repr(F('3.1415926535')))
-        self.assertEquals("Fraction(-1, 100000000000000000000)",
-                          repr(F(1, -10**20)))
-        self.assertEquals("7/3", str(F(7, 3)))
-        self.assertEquals("7", str(F(7, 1)))
+        self.assertEqual("Fraction(7, 3)", repr(F(7, 3)))
+        self.assertEqual("Fraction(6283185307, 2000000000)",
+                         repr(F('3.1415926535')))
+        self.assertEqual("Fraction(-1, 100000000000000000000)",
+                         repr(F(1, -10**20)))
+        self.assertEqual("7/3", str(F(7, 3)))
+        self.assertEqual("7", str(F(7, 1)))
 
     def testHash(self):
-        self.assertEquals(hash(2.5), hash(F(5, 2)))
-        self.assertEquals(hash(10**50), hash(F(10**50)))
-        self.assertNotEquals(hash(float(10**23)), hash(F(10**23)))
+        self.assertEqual(hash(2.5), hash(F(5, 2)))
+        self.assertEqual(hash(10**50), hash(F(10**50)))
+        self.assertNotEqual(hash(float(10**23)), hash(F(10**23)))
+        # Check that __hash__ produces the same value as hash(), for
+        # consistency with int and Decimal.  (See issue #10356.)
+        self.assertEqual(hash(F(-1)), F(-1).__hash__())
 
     def testApproximatePi(self):
         # Algorithm borrowed from
@@ -558,7 +556,7 @@
             d, da = d+da, da+32
             t = (t * n) / d
             s += t
-        self.assertAlmostEquals(math.pi, s)
+        self.assertAlmostEqual(math.pi, s)
 
     def testApproximateCos1(self):
         # Algorithm borrowed from
@@ -572,7 +570,7 @@
             num *= x * x
             sign *= -1
             s += num / fact * sign
-        self.assertAlmostEquals(math.cos(1), s)
+        self.assertAlmostEqual(math.cos(1), s)
 
     def test_copy_deepcopy_pickle(self):
         r = F(13, 7)

Modified: python/branches/pep-3151/Lib/test/test_frozen.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_frozen.py	(original)
+++ python/branches/pep-3151/Lib/test/test_frozen.py	Sat Feb 26 08:16:32 2011
@@ -22,7 +22,7 @@
             self.assertEqual(len(dir(__phello__)), 8, dir(__phello__))
         else:
             self.assertEqual(len(dir(__phello__)), 9, dir(__phello__))
-        self.assertEquals(__phello__.__path__, [__phello__.__name__])
+        self.assertEqual(__phello__.__path__, [__phello__.__name__])
 
         try:
             import __phello__.spam

Modified: python/branches/pep-3151/Lib/test/test_functools.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_functools.py	(original)
+++ python/branches/pep-3151/Lib/test/test_functools.py	Sat Feb 26 08:16:32 2011
@@ -146,6 +146,32 @@
         join = self.thetype(''.join)
         self.assertEqual(join(data), '0123456789')
 
+    def test_repr(self):
+        args = (object(), object())
+        args_repr = ', '.join(repr(a) for a in args)
+        kwargs = {'a': object(), 'b': object()}
+        kwargs_repr = ', '.join("%s=%r" % (k, v) for k, v in kwargs.items())
+        if self.thetype is functools.partial:
+            name = 'functools.partial'
+        else:
+            name = self.thetype.__name__
+
+        f = self.thetype(capture)
+        self.assertEqual('{}({!r})'.format(name, capture),
+                         repr(f))
+
+        f = self.thetype(capture, *args)
+        self.assertEqual('{}({!r}, {})'.format(name, capture, args_repr),
+                         repr(f))
+
+        f = self.thetype(capture, **kwargs)
+        self.assertEqual('{}({!r}, {})'.format(name, capture, kwargs_repr),
+                         repr(f))
+
+        f = self.thetype(capture, *args, **kwargs)
+        self.assertEqual('{}({!r}, {}, {})'.format(name, capture, args_repr, kwargs_repr),
+                         repr(f))
+
     def test_pickle(self):
         f = self.thetype(signature, 'asdf', bar=True)
         f.add_something_to__dict__ = True
@@ -163,6 +189,9 @@
 
     thetype = PythonPartial
 
+    # the python version hasn't a nice repr
+    def test_repr(self): pass
+
     # the python version isn't picklable
     def test_pickle(self): pass
 
@@ -428,12 +457,14 @@
                 self.value = value
             def __lt__(self, other):
                 return self.value < other.value
-        self.assert_(A(1) < A(2))
-        self.assert_(A(2) > A(1))
-        self.assert_(A(1) <= A(2))
-        self.assert_(A(2) >= A(1))
-        self.assert_(A(2) <= A(2))
-        self.assert_(A(2) >= A(2))
+            def __eq__(self, other):
+                return self.value == other.value
+        self.assertTrue(A(1) < A(2))
+        self.assertTrue(A(2) > A(1))
+        self.assertTrue(A(1) <= A(2))
+        self.assertTrue(A(2) >= A(1))
+        self.assertTrue(A(2) <= A(2))
+        self.assertTrue(A(2) >= A(2))
 
     def test_total_ordering_le(self):
         @functools.total_ordering
@@ -442,12 +473,14 @@
                 self.value = value
             def __le__(self, other):
                 return self.value <= other.value
-        self.assert_(A(1) < A(2))
-        self.assert_(A(2) > A(1))
-        self.assert_(A(1) <= A(2))
-        self.assert_(A(2) >= A(1))
-        self.assert_(A(2) <= A(2))
-        self.assert_(A(2) >= A(2))
+            def __eq__(self, other):
+                return self.value == other.value
+        self.assertTrue(A(1) < A(2))
+        self.assertTrue(A(2) > A(1))
+        self.assertTrue(A(1) <= A(2))
+        self.assertTrue(A(2) >= A(1))
+        self.assertTrue(A(2) <= A(2))
+        self.assertTrue(A(2) >= A(2))
 
     def test_total_ordering_gt(self):
         @functools.total_ordering
@@ -456,12 +489,14 @@
                 self.value = value
             def __gt__(self, other):
                 return self.value > other.value
-        self.assert_(A(1) < A(2))
-        self.assert_(A(2) > A(1))
-        self.assert_(A(1) <= A(2))
-        self.assert_(A(2) >= A(1))
-        self.assert_(A(2) <= A(2))
-        self.assert_(A(2) >= A(2))
+            def __eq__(self, other):
+                return self.value == other.value
+        self.assertTrue(A(1) < A(2))
+        self.assertTrue(A(2) > A(1))
+        self.assertTrue(A(1) <= A(2))
+        self.assertTrue(A(2) >= A(1))
+        self.assertTrue(A(2) <= A(2))
+        self.assertTrue(A(2) >= A(2))
 
     def test_total_ordering_ge(self):
         @functools.total_ordering
@@ -470,24 +505,26 @@
                 self.value = value
             def __ge__(self, other):
                 return self.value >= other.value
-        self.assert_(A(1) < A(2))
-        self.assert_(A(2) > A(1))
-        self.assert_(A(1) <= A(2))
-        self.assert_(A(2) >= A(1))
-        self.assert_(A(2) <= A(2))
-        self.assert_(A(2) >= A(2))
+            def __eq__(self, other):
+                return self.value == other.value
+        self.assertTrue(A(1) < A(2))
+        self.assertTrue(A(2) > A(1))
+        self.assertTrue(A(1) <= A(2))
+        self.assertTrue(A(2) >= A(1))
+        self.assertTrue(A(2) <= A(2))
+        self.assertTrue(A(2) >= A(2))
 
     def test_total_ordering_no_overwrite(self):
         # new methods should not overwrite existing
         @functools.total_ordering
         class A(int):
             pass
-        self.assert_(A(1) < A(2))
-        self.assert_(A(2) > A(1))
-        self.assert_(A(1) <= A(2))
-        self.assert_(A(2) >= A(1))
-        self.assert_(A(2) <= A(2))
-        self.assert_(A(2) >= A(2))
+        self.assertTrue(A(1) < A(2))
+        self.assertTrue(A(2) > A(1))
+        self.assertTrue(A(1) <= A(2))
+        self.assertTrue(A(2) >= A(1))
+        self.assertTrue(A(2) <= A(2))
+        self.assertTrue(A(2) >= A(2))
 
     def test_no_operations_defined(self):
         with self.assertRaises(ValueError):
@@ -495,34 +532,63 @@
             class A:
                 pass
 
+    def test_bug_10042(self):
+        @functools.total_ordering
+        class TestTO:
+            def __init__(self, value):
+                self.value = value
+            def __eq__(self, other):
+                if isinstance(other, TestTO):
+                    return self.value == other.value
+                return False
+            def __lt__(self, other):
+                if isinstance(other, TestTO):
+                    return self.value < other.value
+                raise TypeError
+        with self.assertRaises(TypeError):
+            TestTO(8) <= ()
+
 class TestLRU(unittest.TestCase):
 
     def test_lru(self):
         def orig(x, y):
             return 3*x+y
         f = functools.lru_cache(maxsize=20)(orig)
+        hits, misses, maxsize, currsize = f.cache_info()
+        self.assertEqual(maxsize, 20)
+        self.assertEqual(currsize, 0)
+        self.assertEqual(hits, 0)
+        self.assertEqual(misses, 0)
 
         domain = range(5)
         for i in range(1000):
             x, y = choice(domain), choice(domain)
             actual = f(x, y)
             expected = orig(x, y)
-            self.assertEquals(actual, expected)
-        self.assert_(f.cache_hits > f.cache_misses)
-        self.assertEquals(f.cache_hits + f.cache_misses, 1000)
+            self.assertEqual(actual, expected)
+        hits, misses, maxsize, currsize = f.cache_info()
+        self.assertTrue(hits > misses)
+        self.assertEqual(hits + misses, 1000)
+        self.assertEqual(currsize, 20)
 
         f.cache_clear()   # test clearing
-        self.assertEqual(f.cache_hits, 0)
-        self.assertEqual(f.cache_misses, 0)
+        hits, misses, maxsize, currsize = f.cache_info()
+        self.assertEqual(hits, 0)
+        self.assertEqual(misses, 0)
+        self.assertEqual(currsize, 0)
         f(x, y)
-        self.assertEqual(f.cache_hits, 0)
-        self.assertEqual(f.cache_misses, 1)
+        hits, misses, maxsize, currsize = f.cache_info()
+        self.assertEqual(hits, 0)
+        self.assertEqual(misses, 1)
+        self.assertEqual(currsize, 1)
 
         # Test bypassing the cache
         self.assertIs(f.__wrapped__, orig)
         f.__wrapped__(x, y)
-        self.assertEqual(f.cache_hits, 0)
-        self.assertEqual(f.cache_misses, 1)
+        hits, misses, maxsize, currsize = f.cache_info()
+        self.assertEqual(hits, 0)
+        self.assertEqual(misses, 1)
+        self.assertEqual(currsize, 1)
 
         # test size zero (which means "never-cache")
         @functools.lru_cache(0)
@@ -530,10 +596,15 @@
             nonlocal f_cnt
             f_cnt += 1
             return 20
+        self.assertEqual(f.cache_info().maxsize, 0)
         f_cnt = 0
         for i in range(5):
             self.assertEqual(f(), 20)
         self.assertEqual(f_cnt, 5)
+        hits, misses, maxsize, currsize = f.cache_info()
+        self.assertEqual(hits, 0)
+        self.assertEqual(misses, 5)
+        self.assertEqual(currsize, 0)
 
         # test size one
         @functools.lru_cache(1)
@@ -541,10 +612,15 @@
             nonlocal f_cnt
             f_cnt += 1
             return 20
+        self.assertEqual(f.cache_info().maxsize, 1)
         f_cnt = 0
         for i in range(5):
             self.assertEqual(f(), 20)
         self.assertEqual(f_cnt, 1)
+        hits, misses, maxsize, currsize = f.cache_info()
+        self.assertEqual(hits, 4)
+        self.assertEqual(misses, 1)
+        self.assertEqual(currsize, 1)
 
         # test size two
         @functools.lru_cache(2)
@@ -552,11 +628,30 @@
             nonlocal f_cnt
             f_cnt += 1
             return x*10
+        self.assertEqual(f.cache_info().maxsize, 2)
         f_cnt = 0
         for x in 7, 9, 7, 9, 7, 9, 8, 8, 8, 9, 9, 9, 8, 8, 8, 7:
             #    *  *              *                          *
             self.assertEqual(f(x), x*10)
         self.assertEqual(f_cnt, 4)
+        hits, misses, maxsize, currsize = f.cache_info()
+        self.assertEqual(hits, 12)
+        self.assertEqual(misses, 4)
+        self.assertEqual(currsize, 2)
+
+    def test_lru_with_maxsize_none(self):
+        @functools.lru_cache(maxsize=None)
+        def fib(n):
+            if n < 2:
+                return n
+            return fib(n-1) + fib(n-2)
+        self.assertEqual([fib(n) for n in range(16)],
+            [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610])
+        self.assertEqual(fib.cache_info(),
+            functools._CacheInfo(hits=28, misses=16, maxsize=None, currsize=16))
+        fib.cache_clear()
+        self.assertEqual(fib.cache_info(),
+            functools._CacheInfo(hits=0, misses=0, maxsize=None, currsize=0))
 
 def test_main(verbose=None):
     test_classes = (

Modified: python/branches/pep-3151/Lib/test/test_gc.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_gc.py	(original)
+++ python/branches/pep-3151/Lib/test/test_gc.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,6 @@
 import unittest
-from test.support import verbose, run_unittest, strip_python_stderr
+from test.support import (verbose, refcount_test, run_unittest,
+                            strip_python_stderr)
 import sys
 import gc
 import weakref
@@ -175,6 +176,7 @@
         del d
         self.assertEqual(gc.collect(), 2)
 
+    @refcount_test
     def test_frame(self):
         def f():
             frame = sys._getframe()
@@ -242,6 +244,7 @@
     # For example:
     # - disposed tuples are not freed, but reused
     # - the call to assertEqual somehow avoids building its args tuple
+    @refcount_test
     def test_get_count(self):
         # Avoid future allocation of method object
         assertEqual = self._baseAssertEqual
@@ -252,6 +255,7 @@
         # the dict, and the tuple returned by get_count()
         assertEqual(gc.get_count(), (2, 0, 0))
 
+    @refcount_test
     def test_collect_generations(self):
         # Avoid future allocation of method object
         assertEqual = self.assertEqual

Modified: python/branches/pep-3151/Lib/test/test_gdb.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_gdb.py	(original)
+++ python/branches/pep-3151/Lib/test/test_gdb.py	Sat Feb 26 08:16:32 2011
@@ -129,7 +129,7 @@
                           '')
 
         # Ensure no unexpected error messages:
-        self.assertEquals(err, '')
+        self.assertEqual(err, '')
 
         return out
 
@@ -159,8 +159,8 @@
 
     def assertEndsWith(self, actual, exp_end):
         '''Ensure that the given "actual" string ends with "exp_end"'''
-        self.assert_(actual.endswith(exp_end),
-                     msg='%r did not end with %r' % (actual, exp_end))
+        self.assertTrue(actual.endswith(exp_end),
+                        msg='%r did not end with %r' % (actual, exp_end))
 
     def assertMultilineMatches(self, actual, pattern):
         m = re.match(pattern, actual, re.DOTALL)
@@ -182,9 +182,9 @@
                                                  cmds_after_breakpoint)
         if not exp_repr:
             exp_repr = repr(val)
-        self.assertEquals(gdb_repr, exp_repr,
-                          ('%r did not equal expected %r; full output was:\n%s'
-                           % (gdb_repr, exp_repr, gdb_output)))
+        self.assertEqual(gdb_repr, exp_repr,
+                         ('%r did not equal expected %r; full output was:\n%s'
+                          % (gdb_repr, exp_repr, gdb_output)))
 
     def test_int(self):
         'Verify the pretty-printing of various "int"/long values'
@@ -274,7 +274,7 @@
         gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
 s.pop()
 id(s)''')
-        self.assertEquals(gdb_repr, "{'b'}")
+        self.assertEqual(gdb_repr, "{'b'}")
 
     def test_frozensets(self):
         'Verify the pretty-printing of frozensets'
@@ -290,8 +290,8 @@
 except RuntimeError as e:
     id(e)
 ''')
-        self.assertEquals(gdb_repr,
-                          "RuntimeError('I am an error',)")
+        self.assertEqual(gdb_repr,
+                         "RuntimeError('I am an error',)")
 
 
         # Test division by zero:
@@ -301,8 +301,8 @@
 except ZeroDivisionError as e:
     id(e)
 ''')
-        self.assertEquals(gdb_repr,
-                          "ZeroDivisionError('division by zero',)")
+        self.assertEqual(gdb_repr,
+                         "ZeroDivisionError('division by zero',)")
 
     def test_modern_class(self):
         'Verify the pretty-printing of new-style class instances'
@@ -382,7 +382,7 @@
                                                      'backtrace'])
             )
 
-        self.assertEquals(gdb_repr, '0x0')
+        self.assertEqual(gdb_repr, '0x0')
 
     def test_NULL_ob_type(self):
         'Ensure that a PyObject* with NULL ob_type is handled gracefully'
@@ -422,11 +422,11 @@
         into an infinite loop:'''
         gdb_repr, gdb_output = \
             self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
-        self.assertEquals(gdb_repr, '[3, 4, 5, [...]]')
+        self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
 
         gdb_repr, gdb_output = \
             self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
-        self.assertEquals(gdb_repr, '[3, 4, 5, [[...]]]')
+        self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
 
     def test_selfreferential_dict(self):
         '''Ensure that a reference loop involving a dict doesn't lead proxyval
@@ -434,7 +434,7 @@
         gdb_repr, gdb_output = \
             self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
 
-        self.assertEquals(gdb_repr, "{'foo': {'bar': {...}}}")
+        self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
 
     def test_selfreferential_old_style_instance(self):
         gdb_repr, gdb_output = \
@@ -479,30 +479,30 @@
     def test_truncation(self):
         'Verify that very long output is truncated'
         gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
-        self.assertEquals(gdb_repr,
-                          "[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, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
-                          "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
-                          "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
-                          "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
-                          "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
-                          "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
-                          "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
-                          "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
-                          "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
-                          "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
-                          "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
-                          "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
-                          "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
-                          "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
-                          "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
-                          "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
-                          "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
-                          "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
-                          "224, 225, 226...(truncated)")
-        self.assertEquals(len(gdb_repr),
-                          1024 + len('...(truncated)'))
+        self.assertEqual(gdb_repr,
+                         "[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, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
+                         "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
+                         "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
+                         "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
+                         "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
+                         "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
+                         "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
+                         "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
+                         "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
+                         "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
+                         "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
+                         "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
+                         "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
+                         "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
+                         "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
+                         "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
+                         "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
+                         "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
+                         "224, 225, 226...(truncated)")
+        self.assertEqual(len(gdb_repr),
+                         1024 + len('...(truncated)'))
 
     def test_builtin_method(self):
         gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')

Modified: python/branches/pep-3151/Lib/test/test_genexps.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_genexps.py	(original)
+++ python/branches/pep-3151/Lib/test/test_genexps.py	Sat Feb 26 08:16:32 2011
@@ -257,11 +257,15 @@
 
 """
 
+import sys
 
-__test__ = {'doctests' : doctests}
+# Trace function can throw off the tuple reuse test.
+if hasattr(sys, 'gettrace') and sys.gettrace():
+    __test__ = {}
+else:
+    __test__ = {'doctests' : doctests}
 
 def test_main(verbose=None):
-    import sys
     from test import support
     from test import test_genexps
     support.run_doctest(test_genexps, verbose)

Modified: python/branches/pep-3151/Lib/test/test_getargs2.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_getargs2.py	(original)
+++ python/branches/pep-3151/Lib/test/test_getargs2.py	Sat Feb 26 08:16:32 2011
@@ -220,7 +220,7 @@
         from _testcapi import getargs_tuple
 
         ret = getargs_tuple(1, (2, 3))
-        self.assertEquals(ret, (1,2,3))
+        self.assertEqual(ret, (1,2,3))
 
         # make sure invalid tuple arguments are handled correctly
         class seq:
@@ -233,28 +233,28 @@
 class Keywords_TestCase(unittest.TestCase):
     def test_positional_args(self):
         # using all positional args
-        self.assertEquals(
+        self.assertEqual(
             getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), 10),
             (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
             )
 
     def test_mixed_args(self):
         # positional and keyword args
-        self.assertEquals(
+        self.assertEqual(
             getargs_keywords((1,2), 3, (4,(5,6)), arg4=(7,8,9), arg5=10),
             (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
             )
 
     def test_keyword_args(self):
         # all keywords
-        self.assertEquals(
+        self.assertEqual(
             getargs_keywords(arg1=(1,2), arg2=3, arg3=(4,(5,6)), arg4=(7,8,9), arg5=10),
             (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
             )
 
     def test_optional_args(self):
         # missing optional keyword args, skipping tuples
-        self.assertEquals(
+        self.assertEqual(
             getargs_keywords(arg1=(1,2), arg2=3, arg5=10),
             (1, 2, 3, -1, -1, -1, -1, -1, -1, 10)
             )
@@ -264,7 +264,7 @@
         try:
             getargs_keywords(arg1=(1,2))
         except TypeError as err:
-            self.assertEquals(str(err), "Required argument 'arg2' (pos 2) not found")
+            self.assertEqual(str(err), "Required argument 'arg2' (pos 2) not found")
         else:
             self.fail('TypeError should have been raised')
 
@@ -272,7 +272,7 @@
         try:
             getargs_keywords((1,2),3,(4,(5,6)),(7,8,9),10,111)
         except TypeError as err:
-            self.assertEquals(str(err), "function takes at most 5 arguments (6 given)")
+            self.assertEqual(str(err), "function takes at most 5 arguments (6 given)")
         else:
             self.fail('TypeError should have been raised')
 
@@ -281,7 +281,7 @@
         try:
             getargs_keywords((1,2),3,arg5=10,arg666=666)
         except TypeError as err:
-            self.assertEquals(str(err), "'arg666' is an invalid keyword argument for this function")
+            self.assertEqual(str(err), "'arg666' is an invalid keyword argument for this function")
         else:
             self.fail('TypeError should have been raised')
 
@@ -289,7 +289,7 @@
         try:
             getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), **{'\uDC80': 10})
         except TypeError as err:
-            self.assertEquals(str(err), "'\udc80' is an invalid keyword argument for this function")
+            self.assertEqual(str(err), "'\udc80' is an invalid keyword argument for this function")
         else:
             self.fail('TypeError should have been raised')
 
@@ -381,8 +381,10 @@
         self.assertRaises(TypeError, getargs_w_star, 'abc\xe9')
         self.assertRaises(TypeError, getargs_w_star, b'bytes')
         self.assertRaises(TypeError, getargs_w_star, b'nul:\0')
+        self.assertRaises(TypeError, getargs_w_star, memoryview(b'bytes'))
         self.assertEqual(getargs_w_star(bytearray(b'bytearray')), b'[ytearra]')
-        self.assertEqual(getargs_w_star(memoryview(b'memoryview')), b'[emoryvie]')
+        self.assertEqual(getargs_w_star(memoryview(bytearray(b'memoryview'))),
+                         b'[emoryvie]')
         self.assertRaises(TypeError, getargs_w_star, None)
 
 

Modified: python/branches/pep-3151/Lib/test/test_getopt.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_getopt.py	(original)
+++ python/branches/pep-3151/Lib/test/test_getopt.py	Sat Feb 26 08:16:32 2011
@@ -175,9 +175,9 @@
 
     def test_issue4629(self):
         longopts, shortopts = getopt.getopt(['--help='], '', ['help='])
-        self.assertEquals(longopts, [('--help', '')])
+        self.assertEqual(longopts, [('--help', '')])
         longopts, shortopts = getopt.getopt(['--help=x'], '', ['help='])
-        self.assertEquals(longopts, [('--help', 'x')])
+        self.assertEqual(longopts, [('--help', 'x')])
         self.assertRaises(getopt.GetoptError, getopt.getopt, ['--help='], '', ['help'])
 
 def test_main():

Modified: python/branches/pep-3151/Lib/test/test_glob.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_glob.py	(original)
+++ python/branches/pep-3151/Lib/test/test_glob.py	Sat Feb 26 08:16:32 2011
@@ -59,8 +59,8 @@
         if set(type(x) for x in tmp) == uniset:
             u1 = glob.glob('*')
             u2 = glob.glob('./*')
-            self.assertEquals(set(type(r) for r in u1), uniset)
-            self.assertEquals(set(type(r) for r in u2), uniset)
+            self.assertEqual(set(type(r) for r in u1), uniset)
+            self.assertEqual(set(type(r) for r in u2), uniset)
 
     def test_glob_one_directory(self):
         eq = self.assertSequencesEqual_noorder

Modified: python/branches/pep-3151/Lib/test/test_grp.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_grp.py	(original)
+++ python/branches/pep-3151/Lib/test/test_grp.py	Sat Feb 26 08:16:32 2011
@@ -33,12 +33,16 @@
             e2 = grp.getgrgid(e.gr_gid)
             self.check_value(e2)
             self.assertEqual(e2.gr_gid, e.gr_gid)
-            e2 = grp.getgrnam(e.gr_name)
+            name = e.gr_name
+            if name.startswith('+') or name.startswith('-'):
+                # NIS-related entry
+                continue
+            e2 = grp.getgrnam(name)
             self.check_value(e2)
             # There are instances where getgrall() returns group names in
             # lowercase while getgrgid() returns proper casing.
             # Discovered on Ubuntu 5.04 (custom).
-            self.assertEqual(e2.gr_name.lower(), e.gr_name.lower())
+            self.assertEqual(e2.gr_name.lower(), name.lower())
 
     def test_errors(self):
         self.assertRaises(TypeError, grp.getgrgid)

Modified: python/branches/pep-3151/Lib/test/test_gzip.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_gzip.py	(original)
+++ python/branches/pep-3151/Lib/test/test_gzip.py	Sat Feb 26 08:16:32 2011
@@ -113,7 +113,7 @@
                 ztxt = zgfile.read(8192)
                 contents += ztxt
                 if not ztxt: break
-        self.assertEquals(contents, b'a'*201)
+        self.assertEqual(contents, b'a'*201)
 
     def test_buffered_reader(self):
         # Issue #7471: a GzipFile can be wrapped in a BufferedReader for
@@ -177,7 +177,7 @@
             f.read(10)
             f.seek(10, whence=1)
             y = f.read(10)
-        self.assertEquals(y, data1[20:30])
+        self.assertEqual(y, data1[20:30])
 
     def test_seek_write(self):
         # Try seek, write test
@@ -197,6 +197,12 @@
                 self.assertTrue(hasattr(f, "name"))
                 self.assertEqual(f.name, self.filename)
 
+    def test_paddedfile_getattr(self):
+        self.test_write()
+        with gzip.GzipFile(self.filename, 'rb') as f:
+            self.assertTrue(hasattr(f.fileobj, "name"))
+            self.assertEqual(f.fileobj.name, self.filename)
+
     def test_mtime(self):
         mtime = 123456789
         with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite:

Modified: python/branches/pep-3151/Lib/test/test_hashlib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_hashlib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_hashlib.py	Sat Feb 26 08:16:32 2011
@@ -103,7 +103,7 @@
 
     def test_algorithms_guaranteed(self):
         self.assertEqual(hashlib.algorithms_guaranteed,
-            tuple(_algo for _algo in self.supported_hash_names
+            set(_algo for _algo in self.supported_hash_names
                   if _algo.islower()))
 
     def test_algorithms_available(self):
@@ -310,10 +310,10 @@
         m.update(b'1')
         m.update(b'#' * gil_minsize)
         m.update(b'1')
-        self.assertEquals(m.hexdigest(), 'cb1e1a2cbc80be75e19935d621fb9b21')
+        self.assertEqual(m.hexdigest(), 'cb1e1a2cbc80be75e19935d621fb9b21')
 
         m = hashlib.md5(b'x' * gil_minsize)
-        self.assertEquals(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958')
+        self.assertEqual(m.hexdigest(), 'cfb767f225d58469c5de3632a8803958')
 
     @unittest.skipUnless(threading, 'Threading required for this test.')
     @support.reap_threads

Modified: python/branches/pep-3151/Lib/test/test_htmlparser.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_htmlparser.py	(original)
+++ python/branches/pep-3151/Lib/test/test_htmlparser.py	Sat Feb 26 08:16:32 2011
@@ -8,10 +8,10 @@
 
 class EventCollector(html.parser.HTMLParser):
 
-    def __init__(self):
+    def __init__(self, *args, **kw):
         self.events = []
         self.append = self.events.append
-        html.parser.HTMLParser.__init__(self)
+        html.parser.HTMLParser.__init__(self, *args, **kw)
 
     def get_events(self):
         # Normalize the list of events so that buffer artefacts don't
@@ -72,8 +72,10 @@
 
 class TestCaseBase(unittest.TestCase):
 
-    def _run_check(self, source, expected_events, collector=EventCollector):
-        parser = collector()
+    def _run_check(self, source, expected_events, collector=None):
+        if collector is None:
+            collector = EventCollector()
+        parser = collector
         for s in source:
             parser.feed(s)
         parser.close()
@@ -84,7 +86,7 @@
                       "\nReceived:\n" + pprint.pformat(events))
 
     def _run_check_extra(self, source, events):
-        self._run_check(source, events, EventCollectorExtra)
+        self._run_check(source, events, EventCollectorExtra())
 
     def _parse_error(self, source):
         def parse(source=source):
@@ -321,8 +323,47 @@
                 ])
 
 
+class HTMLParserTolerantTestCase(TestCaseBase):
+
+    def setUp(self):
+        self.collector = EventCollector(strict=False)
+
+    def test_tolerant_parsing(self):
+        self._run_check('<html <html>te>>xt&a<<bc</a></html>\n'
+                        '<img src="URL><//img></html</html>', [
+                             ('data', '<html '),
+                             ('starttag', 'html', []),
+                             ('data', 'te>>xt'),
+                             ('entityref', 'a'),
+                             ('data', '<<bc'),
+                             ('endtag', 'a'),
+                             ('endtag', 'html'),
+                             ('data', '\n<img src="URL><//img></html'),
+                             ('endtag', 'html')],
+                        collector = self.collector)
+
+    def test_comma_between_attributes(self):
+        self._run_check('<form action="/xxx.php?a=1&amp;b=2&amp", '
+                        'method="post">', [
+                            ('starttag', 'form',
+                                [('action', '/xxx.php?a=1&b=2&amp'),
+                                 ('method', 'post')])],
+                        collector = self.collector)
+
+    def test_weird_chars_in_unquoted_attribute_values(self):
+        self._run_check('<form action=bogus|&#()value>', [
+                            ('starttag', 'form',
+                                [('action', 'bogus|&#()value')])],
+                        collector = self.collector)
+
+    def test_unescape_function(self):
+        p = html.parser.HTMLParser()
+        self.assertEqual(p.unescape('&#bad;'),'&#bad;')
+        self.assertEqual(p.unescape('&#0038;'),'&')
+
+
 def test_main():
-    support.run_unittest(HTMLParserTestCase)
+    support.run_unittest(HTMLParserTestCase, HTMLParserTolerantTestCase)
 
 
 if __name__ == "__main__":

Modified: python/branches/pep-3151/Lib/test/test_http_cookiejar.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_http_cookiejar.py	(original)
+++ python/branches/pep-3151/Lib/test/test_http_cookiejar.py	Sat Feb 26 08:16:32 2011
@@ -20,28 +20,28 @@
     def test_time2isoz(self):
         base = 1019227000
         day = 24*3600
-        self.assertEquals(time2isoz(base), "2002-04-19 14:36:40Z")
-        self.assertEquals(time2isoz(base+day), "2002-04-20 14:36:40Z")
-        self.assertEquals(time2isoz(base+2*day), "2002-04-21 14:36:40Z")
-        self.assertEquals(time2isoz(base+3*day), "2002-04-22 14:36:40Z")
+        self.assertEqual(time2isoz(base), "2002-04-19 14:36:40Z")
+        self.assertEqual(time2isoz(base+day), "2002-04-20 14:36:40Z")
+        self.assertEqual(time2isoz(base+2*day), "2002-04-21 14:36:40Z")
+        self.assertEqual(time2isoz(base+3*day), "2002-04-22 14:36:40Z")
 
         az = time2isoz()
         bz = time2isoz(500000)
         for text in (az, bz):
             self.assertTrue(re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$", text),
-                         "bad time2isoz format: %s %s" % (az, bz))
+                            "bad time2isoz format: %s %s" % (az, bz))
 
     def test_http2time(self):
         def parse_date(text):
             return time.gmtime(http2time(text))[:6]
 
-        self.assertEquals(parse_date("01 Jan 2001"), (2001, 1, 1, 0, 0, 0.0))
+        self.assertEqual(parse_date("01 Jan 2001"), (2001, 1, 1, 0, 0, 0.0))
 
         # this test will break around year 2070
-        self.assertEquals(parse_date("03-Feb-20"), (2020, 2, 3, 0, 0, 0.0))
+        self.assertEqual(parse_date("03-Feb-20"), (2020, 2, 3, 0, 0, 0.0))
 
         # this test will break around year 2048
-        self.assertEquals(parse_date("03-Feb-98"), (1998, 2, 3, 0, 0, 0.0))
+        self.assertEqual(parse_date("03-Feb-98"), (1998, 2, 3, 0, 0, 0.0))
 
     def test_http2time_formats(self):
         # test http2time for supported dates.  Test cases with 2 digit year
@@ -69,8 +69,8 @@
         test_t = 760233600  # assume broken POSIX counting of seconds
         result = time2isoz(test_t)
         expected = "1994-02-03 00:00:00Z"
-        self.assertEquals(result, expected,
-                          "%s  =>  '%s' (%s)" % (test_t, result, expected))
+        self.assertEqual(result, expected,
+                         "%s  =>  '%s' (%s)" % (test_t, result, expected))
 
         for s in tests:
             t = http2time(s)
@@ -108,7 +108,7 @@
             'foo=bar; expires=01 Jan 2040 22:23:32 GMT',
             'foo=bar; expires="01 Jan 2040 22:23:32 GMT"',
             ]:
-            self.assertEquals(parse_ns_headers([hdr]), expected)
+            self.assertEqual(parse_ns_headers([hdr]), expected)
 
     def test_parse_ns_headers_version(self):
 
@@ -118,7 +118,7 @@
             'foo=bar; version="1"',
             'foo=bar; Version="1"',
             ]:
-            self.assertEquals(parse_ns_headers([hdr]), expected)
+            self.assertEqual(parse_ns_headers([hdr]), expected)
 
     def test_parse_ns_headers_special_names(self):
         # names such as 'expires' are not special in first name=value pair
@@ -126,13 +126,13 @@
         # Cookie with name 'expires'
         hdr = 'expires=01 Jan 2040 22:23:32 GMT'
         expected = [[("expires", "01 Jan 2040 22:23:32 GMT"), ("version", "0")]]
-        self.assertEquals(parse_ns_headers([hdr]), expected)
+        self.assertEqual(parse_ns_headers([hdr]), expected)
 
     def test_join_header_words(self):
         joined = join_header_words([[("foo", None), ("bar", "baz")]])
-        self.assertEquals(joined, "foo; bar=baz")
+        self.assertEqual(joined, "foo; bar=baz")
 
-        self.assertEquals(join_header_words([[]]), "")
+        self.assertEqual(join_header_words([[]]), "")
 
     def test_split_header_words(self):
         tests = [
@@ -162,7 +162,7 @@
                 f = io.StringIO()
                 traceback.print_exc(None, f)
                 result = "(error -- traceback follows)\n\n%s" % f.getvalue()
-            self.assertEquals(result,  expect, """
+            self.assertEqual(result,  expect, """
 When parsing: '%s'
 Expected:     '%s'
 Got:          '%s'
@@ -194,7 +194,7 @@
         for arg, expect in tests:
             input = split_header_words([arg])
             res = join_header_words(input)
-            self.assertEquals(res, expect, """
+            self.assertEqual(res, expect, """
 When parsing: '%s'
 Expected:     '%s'
 Got:          '%s'
@@ -358,11 +358,11 @@
         interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')
         cookie = c._cookies["www.acme.com"]["/"]["eggs"]
         self.assertTrue(cookie.value is None)
-        self.assertEquals(cookie.name, "eggs")
+        self.assertEqual(cookie.name, "eggs")
         cookie = c._cookies["www.acme.com"]['/foo/']['"spam"']
         self.assertTrue(cookie.value is None)
-        self.assertEquals(cookie.name, '"spam"')
-        self.assertEquals(lwp_cookie_str(cookie), (
+        self.assertEqual(cookie.name, '"spam"')
+        self.assertEqual(lwp_cookie_str(cookie), (
             r'"spam"; path="/foo/"; domain="www.acme.com"; '
             'path_spec; discard; version=0'))
         old_str = repr(c)
@@ -373,13 +373,13 @@
         finally:
             os.unlink(c.filename)
         # cookies unchanged apart from lost info re. whether path was specified
-        self.assertEquals(
+        self.assertEqual(
             repr(c),
             re.sub("path_specified=%s" % True, "path_specified=%s" % False,
                    old_str)
             )
-        self.assertEquals(interact_netscape(c, "http://www.acme.com/foo/"),
-                          '"spam"; eggs')
+        self.assertEqual(interact_netscape(c, "http://www.acme.com/foo/"),
+                         '"spam"; eggs')
 
     def test_rfc2109_handling(self):
         # RFC 2109 cookies are handled as RFC 2965 or Netscape cookies,
@@ -423,18 +423,18 @@
                           'expires="Foo Bar 25 33:22:11 3022"')
 
         cookie = c._cookies[".acme.com"]["/"]["spam"]
-        self.assertEquals(cookie.domain, ".acme.com")
+        self.assertEqual(cookie.domain, ".acme.com")
         self.assertTrue(cookie.domain_specified)
-        self.assertEquals(cookie.port, DEFAULT_HTTP_PORT)
+        self.assertEqual(cookie.port, DEFAULT_HTTP_PORT)
         self.assertTrue(not cookie.port_specified)
         # case is preserved
         self.assertTrue(cookie.has_nonstandard_attr("blArgh") and
                      not cookie.has_nonstandard_attr("blargh"))
 
         cookie = c._cookies["www.acme.com"]["/"]["ni"]
-        self.assertEquals(cookie.domain, "www.acme.com")
+        self.assertEqual(cookie.domain, "www.acme.com")
         self.assertTrue(not cookie.domain_specified)
-        self.assertEquals(cookie.port, "80,8080")
+        self.assertEqual(cookie.port, "80,8080")
         self.assertTrue(cookie.port_specified)
 
         cookie = c._cookies["www.acme.com"]["/"]["nini"]
@@ -464,13 +464,13 @@
         future = time2netscape(time.time()+3600)
         interact_netscape(c, "http://www.acme.com/", 'spam="bar"; expires=%s' %
                           future)
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
         now = time2netscape(time.time()-1)
         # ... and if in past or present, discard it
         interact_netscape(c, "http://www.acme.com/", 'foo="eggs"; expires=%s' %
                           now)
         h = interact_netscape(c, "http://www.acme.com/")
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
         self.assertIn('spam="bar"', h)
         self.assertNotIn("foo", h)
 
@@ -480,19 +480,19 @@
                           future)
         interact_netscape(c, "http://www.acme.com/", 'bar="bar"; expires=%s' %
                           future)
-        self.assertEquals(len(c), 3)
+        self.assertEqual(len(c), 3)
         interact_netscape(c, "http://www.acme.com/", 'eggs="bar"; '
                           'expires=%s; max-age=0' % future)
         interact_netscape(c, "http://www.acme.com/", 'bar="bar"; '
                           'max-age=0; expires=%s' % future)
         h = interact_netscape(c, "http://www.acme.com/")
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
 
         # test expiry at end of session for cookies with no expires attribute
         interact_netscape(c, "http://www.rhubarb.net/", 'whum="fizz"')
-        self.assertEquals(len(c), 2)
+        self.assertEqual(len(c), 2)
         c.clear_session_cookies()
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
         self.assertIn('spam="bar"', h)
 
         # XXX RFC 2965 expiry rules (some apply to V0 too)
@@ -545,7 +545,7 @@
         # Default path does not include query, so is "/", not "/?spam".
         self.assertIn("/", cj._cookies["example.com"])
         # Cookie is sent back to the same URI.
-        self.assertEquals(interact_netscape(cj, uri), value)
+        self.assertEqual(interact_netscape(cj, uri), value)
 
     def test_escape_path(self):
         cases = [
@@ -570,31 +570,31 @@
             ("/foo/bar\uabcd", "/foo/bar%EA%AF%8D"),  # UTF-8 encoded
             ]
         for arg, result in cases:
-            self.assertEquals(escape_path(arg), result)
+            self.assertEqual(escape_path(arg), result)
 
     def test_request_path(self):
         # with parameters
         req = urllib.request.Request(
             "http://www.example.com/rheum/rhaponticum;"
             "foo=bar;sing=song?apples=pears&spam=eggs#ni")
-        self.assertEquals(request_path(req),
-                          "/rheum/rhaponticum;foo=bar;sing=song")
+        self.assertEqual(request_path(req),
+                         "/rheum/rhaponticum;foo=bar;sing=song")
         # without parameters
         req = urllib.request.Request(
             "http://www.example.com/rheum/rhaponticum?"
             "apples=pears&spam=eggs#ni")
-        self.assertEquals(request_path(req), "/rheum/rhaponticum")
+        self.assertEqual(request_path(req), "/rheum/rhaponticum")
         # missing final slash
         req = urllib.request.Request("http://www.example.com")
-        self.assertEquals(request_path(req), "/")
+        self.assertEqual(request_path(req), "/")
 
     def test_request_port(self):
         req = urllib.request.Request("http://www.acme.com:1234/",
                                      headers={"Host": "www.acme.com:4321"})
-        self.assertEquals(request_port(req), "1234")
+        self.assertEqual(request_port(req), "1234")
         req = urllib.request.Request("http://www.acme.com/",
                                      headers={"Host": "www.acme.com:4321"})
-        self.assertEquals(request_port(req), DEFAULT_HTTP_PORT)
+        self.assertEqual(request_port(req), DEFAULT_HTTP_PORT)
 
     def test_request_host(self):
         # this request is illegal (RFC2616, 14.2.3)
@@ -602,15 +602,15 @@
                                      headers={"Host": "www.acme.com:80"})
         # libwww-perl wants this response, but that seems wrong (RFC 2616,
         # section 5.2, point 1., and RFC 2965 section 1, paragraph 3)
-        #self.assertEquals(request_host(req), "www.acme.com")
-        self.assertEquals(request_host(req), "1.1.1.1")
+        #self.assertEqual(request_host(req), "www.acme.com")
+        self.assertEqual(request_host(req), "1.1.1.1")
         req = urllib.request.Request("http://www.acme.com/",
                                      headers={"Host": "irrelevant.com"})
-        self.assertEquals(request_host(req), "www.acme.com")
+        self.assertEqual(request_host(req), "www.acme.com")
         # port shouldn't be in request-host
         req = urllib.request.Request("http://www.acme.com:2345/resource.html",
                                      headers={"Host": "www.acme.com:5432"})
-        self.assertEquals(request_host(req), "www.acme.com")
+        self.assertEqual(request_host(req), "www.acme.com")
 
     def test_is_HDN(self):
         self.assertTrue(is_HDN("foo.bar.com"))
@@ -623,14 +623,14 @@
         self.assertTrue(not is_HDN("foo."))
 
     def test_reach(self):
-        self.assertEquals(reach("www.acme.com"), ".acme.com")
-        self.assertEquals(reach("acme.com"), "acme.com")
-        self.assertEquals(reach("acme.local"), ".local")
-        self.assertEquals(reach(".local"), ".local")
-        self.assertEquals(reach(".com"), ".com")
-        self.assertEquals(reach("."), ".")
-        self.assertEquals(reach(""), "")
-        self.assertEquals(reach("192.168.0.1"), "192.168.0.1")
+        self.assertEqual(reach("www.acme.com"), ".acme.com")
+        self.assertEqual(reach("acme.com"), "acme.com")
+        self.assertEqual(reach("acme.local"), ".local")
+        self.assertEqual(reach(".local"), ".local")
+        self.assertEqual(reach(".com"), ".com")
+        self.assertEqual(reach("."), ".")
+        self.assertEqual(reach(""), "")
+        self.assertEqual(reach("192.168.0.1"), "192.168.0.1")
 
     def test_domain_match(self):
         self.assertTrue(domain_match("192.168.1.1", "192.168.1.1"))
@@ -676,7 +676,7 @@
         c = CookieJar()
         interact_2965(c, "http://www.nasty.com/",
                       'foo=bar; domain=friendly.org; Version="1"')
-        self.assertEquals(len(c), 0)
+        self.assertEqual(len(c), 0)
 
     def test_strict_domain(self):
         # Cookies whose domain is a country-code tld like .co.uk should
@@ -686,11 +686,11 @@
         interact_netscape(cj, "http://example.co.uk/", 'no=problemo')
         interact_netscape(cj, "http://example.co.uk/",
                           'okey=dokey; Domain=.example.co.uk')
-        self.assertEquals(len(cj), 2)
+        self.assertEqual(len(cj), 2)
         for pseudo_tld in [".co.uk", ".org.za", ".tx.us", ".name.us"]:
             interact_netscape(cj, "http://example.%s/" % pseudo_tld,
                               'spam=eggs; Domain=.co.uk')
-            self.assertEquals(len(cj), 2)
+            self.assertEqual(len(cj), 2)
 
     def test_two_component_domain_ns(self):
         # Netscape: .www.bar.com, www.bar.com, .bar.com, bar.com, no domain
@@ -700,17 +700,17 @@
 
         # two-component V0 domain is OK
         interact_netscape(c, "http://foo.net/", 'ns=bar')
-        self.assertEquals(len(c), 1)
-        self.assertEquals(c._cookies["foo.net"]["/"]["ns"].value, "bar")
-        self.assertEquals(interact_netscape(c, "http://foo.net/"), "ns=bar")
+        self.assertEqual(len(c), 1)
+        self.assertEqual(c._cookies["foo.net"]["/"]["ns"].value, "bar")
+        self.assertEqual(interact_netscape(c, "http://foo.net/"), "ns=bar")
         # *will* be returned to any other domain (unlike RFC 2965)...
-        self.assertEquals(interact_netscape(c, "http://www.foo.net/"),
-                          "ns=bar")
+        self.assertEqual(interact_netscape(c, "http://www.foo.net/"),
+                         "ns=bar")
         # ...unless requested otherwise
         pol = DefaultCookiePolicy(
             strict_ns_domain=DefaultCookiePolicy.DomainStrictNonDomain)
         c.set_policy(pol)
-        self.assertEquals(interact_netscape(c, "http://www.foo.net/"), "")
+        self.assertEqual(interact_netscape(c, "http://www.foo.net/"), "")
 
         # unlike RFC 2965, even explicit two-component domain is OK,
         # because .foo.net matches foo.net
@@ -719,17 +719,17 @@
         # even if starts with a dot -- in NS rules, .foo.net matches foo.net!
         interact_netscape(c, "http://foo.net/foo/bar/",
                           'spam2=eggs; domain=.foo.net')
-        self.assertEquals(len(c), 3)
-        self.assertEquals(c._cookies[".foo.net"]["/foo"]["spam1"].value,
-                          "eggs")
-        self.assertEquals(c._cookies[".foo.net"]["/foo/bar"]["spam2"].value,
-                          "eggs")
-        self.assertEquals(interact_netscape(c, "http://foo.net/foo/bar/"),
-                          "spam2=eggs; spam1=eggs; ns=bar")
+        self.assertEqual(len(c), 3)
+        self.assertEqual(c._cookies[".foo.net"]["/foo"]["spam1"].value,
+                         "eggs")
+        self.assertEqual(c._cookies[".foo.net"]["/foo/bar"]["spam2"].value,
+                         "eggs")
+        self.assertEqual(interact_netscape(c, "http://foo.net/foo/bar/"),
+                         "spam2=eggs; spam1=eggs; ns=bar")
 
         # top-level domain is too general
         interact_netscape(c, "http://foo.net/", 'nini="ni"; domain=.net')
-        self.assertEquals(len(c), 3)
+        self.assertEqual(len(c), 3)
 
 ##         # Netscape protocol doesn't allow non-special top level domains (such
 ##         # as co.uk) in the domain attribute unless there are at least three
@@ -737,8 +737,8 @@
         # Oh yes it does!  Real implementations don't check this, and real
         # cookies (of course) rely on that behaviour.
         interact_netscape(c, "http://foo.co.uk", 'nasty=trick; domain=.co.uk')
-##         self.assertEquals(len(c), 2)
-        self.assertEquals(len(c), 4)
+##         self.assertEqual(len(c), 2)
+        self.assertEqual(len(c), 4)
 
     def test_two_component_domain_rfc2965(self):
         pol = DefaultCookiePolicy(rfc2965=True)
@@ -746,43 +746,43 @@
 
         # two-component V1 domain is OK
         interact_2965(c, "http://foo.net/", 'foo=bar; Version="1"')
-        self.assertEquals(len(c), 1)
-        self.assertEquals(c._cookies["foo.net"]["/"]["foo"].value, "bar")
-        self.assertEquals(interact_2965(c, "http://foo.net/"),
-                          "$Version=1; foo=bar")
+        self.assertEqual(len(c), 1)
+        self.assertEqual(c._cookies["foo.net"]["/"]["foo"].value, "bar")
+        self.assertEqual(interact_2965(c, "http://foo.net/"),
+                         "$Version=1; foo=bar")
         # won't be returned to any other domain (because domain was implied)
-        self.assertEquals(interact_2965(c, "http://www.foo.net/"), "")
+        self.assertEqual(interact_2965(c, "http://www.foo.net/"), "")
 
         # unless domain is given explicitly, because then it must be
         # rewritten to start with a dot: foo.net --> .foo.net, which does
         # not domain-match foo.net
         interact_2965(c, "http://foo.net/foo",
                       'spam=eggs; domain=foo.net; path=/foo; Version="1"')
-        self.assertEquals(len(c), 1)
-        self.assertEquals(interact_2965(c, "http://foo.net/foo"),
-                          "$Version=1; foo=bar")
+        self.assertEqual(len(c), 1)
+        self.assertEqual(interact_2965(c, "http://foo.net/foo"),
+                         "$Version=1; foo=bar")
 
         # explicit foo.net from three-component domain www.foo.net *does* get
         # set, because .foo.net domain-matches .foo.net
         interact_2965(c, "http://www.foo.net/foo/",
                       'spam=eggs; domain=foo.net; Version="1"')
-        self.assertEquals(c._cookies[".foo.net"]["/foo/"]["spam"].value,
-                          "eggs")
-        self.assertEquals(len(c), 2)
-        self.assertEquals(interact_2965(c, "http://foo.net/foo/"),
-                          "$Version=1; foo=bar")
-        self.assertEquals(interact_2965(c, "http://www.foo.net/foo/"),
-                          '$Version=1; spam=eggs; $Domain="foo.net"')
+        self.assertEqual(c._cookies[".foo.net"]["/foo/"]["spam"].value,
+                         "eggs")
+        self.assertEqual(len(c), 2)
+        self.assertEqual(interact_2965(c, "http://foo.net/foo/"),
+                         "$Version=1; foo=bar")
+        self.assertEqual(interact_2965(c, "http://www.foo.net/foo/"),
+                         '$Version=1; spam=eggs; $Domain="foo.net"')
 
         # top-level domain is too general
         interact_2965(c, "http://foo.net/",
                       'ni="ni"; domain=".net"; Version="1"')
-        self.assertEquals(len(c), 2)
+        self.assertEqual(len(c), 2)
 
         # RFC 2965 doesn't require blocking this
         interact_2965(c, "http://foo.co.uk/",
                       'nasty=trick; domain=.co.uk; Version="1"')
-        self.assertEquals(len(c), 3)
+        self.assertEqual(len(c), 3)
 
     def test_domain_allow(self):
         c = CookieJar(policy=DefaultCookiePolicy(
@@ -793,24 +793,24 @@
         headers = ["Set-Cookie: CUSTOMER=WILE_E_COYOTE; path=/"]
         res = FakeResponse(headers, "http://acme.com/")
         c.extract_cookies(res, req)
-        self.assertEquals(len(c), 0)
+        self.assertEqual(len(c), 0)
 
         req = urllib.request.Request("http://www.acme.com/")
         res = FakeResponse(headers, "http://www.acme.com/")
         c.extract_cookies(res, req)
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
 
         req = urllib.request.Request("http://www.coyote.com/")
         res = FakeResponse(headers, "http://www.coyote.com/")
         c.extract_cookies(res, req)
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
 
         # set a cookie with non-allowed domain...
         req = urllib.request.Request("http://www.coyote.com/")
         res = FakeResponse(headers, "http://www.coyote.com/")
         cookies = c.make_cookies(res, req)
         c.set_cookie(cookies[0])
-        self.assertEquals(len(c), 2)
+        self.assertEqual(len(c), 2)
         # ... and check is doesn't get returned
         c.add_cookie_header(req)
         self.assertTrue(not req.has_header("Cookie"))
@@ -824,17 +824,17 @@
         req = urllib.request.Request("http://www.acme.com/")
         res = FakeResponse(headers, "http://www.acme.com/")
         c.extract_cookies(res, req)
-        self.assertEquals(len(c), 0)
+        self.assertEqual(len(c), 0)
 
         p = pol.set_blocked_domains(["acme.com"])
         c.extract_cookies(res, req)
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
 
         c.clear()
         req = urllib.request.Request("http://www.roadrunner.net/")
         res = FakeResponse(headers, "http://www.roadrunner.net/")
         c.extract_cookies(res, req)
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
         req = urllib.request.Request("http://www.roadrunner.net/")
         c.add_cookie_header(req)
         self.assertTrue((req.has_header("Cookie") and
@@ -843,14 +843,14 @@
         c.clear()
         pol.set_blocked_domains([".acme.com"])
         c.extract_cookies(res, req)
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
 
         # set a cookie with blocked domain...
         req = urllib.request.Request("http://www.acme.com/")
         res = FakeResponse(headers, "http://www.acme.com/")
         cookies = c.make_cookies(res, req)
         c.set_cookie(cookies[0])
-        self.assertEquals(len(c), 2)
+        self.assertEqual(len(c), 2)
         # ... and check is doesn't get returned
         c.add_cookie_header(req)
         self.assertTrue(not req.has_header("Cookie"))
@@ -882,7 +882,7 @@
         c = CookieJar(policy=DefaultCookiePolicy(rfc2965=True))
         interact_2965(c, "http://www.acme.com/", r'foo=\b"a"r; Version=1')
         h = interact_2965(c, "http://www.acme.com/")
-        self.assertEquals(h, r'$Version=1; foo=\\b\"a\"r')
+        self.assertEqual(h, r'$Version=1; foo=\\b\"a\"r')
 
     def test_missing_final_slash(self):
         # Missing slash from request URL's abs_path should be assumed present.
@@ -890,7 +890,7 @@
         c = CookieJar(DefaultCookiePolicy(rfc2965=True))
         interact_2965(c, url, "foo=bar; Version=1")
         req = urllib.request.Request(url)
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
         c.add_cookie_header(req)
         self.assertTrue(req.has_header("Cookie"))
 
@@ -1000,31 +1000,31 @@
             i = 0
             for c in cs:
                 self.assertTrue(isinstance(c, Cookie))
-                self.assertEquals(c.version, versions[i])
-                self.assertEquals(c.name, names[i])
-                self.assertEquals(c.domain, domains[i])
-                self.assertEquals(c.path, paths[i])
+                self.assertEqual(c.version, versions[i])
+                self.assertEqual(c.name, names[i])
+                self.assertEqual(c.domain, domains[i])
+                self.assertEqual(c.path, paths[i])
                 i = i + 1
 
     def test_parse_ns_headers(self):
         # missing domain value (invalid cookie)
-        self.assertEquals(
+        self.assertEqual(
             parse_ns_headers(["foo=bar; path=/; domain"]),
             [[("foo", "bar"),
               ("path", "/"), ("domain", None), ("version", "0")]]
             )
         # invalid expires value
-        self.assertEquals(
+        self.assertEqual(
             parse_ns_headers(["foo=bar; expires=Foo Bar 12 33:22:11 2000"]),
             [[("foo", "bar"), ("expires", None), ("version", "0")]]
             )
         # missing cookie value (valid cookie)
-        self.assertEquals(
+        self.assertEqual(
             parse_ns_headers(["foo"]),
             [[("foo", None), ("version", "0")]]
             )
         # shouldn't add version if header is empty
-        self.assertEquals(parse_ns_headers([""]), [])
+        self.assertEqual(parse_ns_headers([""]), [])
 
     def test_bad_cookie_header(self):
 
@@ -1048,7 +1048,7 @@
             ]:
             c = cookiejar_from_cookie_headers(headers)
             # these bad cookies shouldn't be set
-            self.assertEquals(len(c), 0)
+            self.assertEqual(len(c), 0)
 
         # cookie with invalid expires is treated as session cookie
         headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"]
@@ -1187,8 +1187,8 @@
         req = urllib.request.Request("http://www.acme.com/")
         c.add_cookie_header(req)
 
-        self.assertEquals(req.get_header("Cookie"),
-                          "PART_NUMBER=ROCKET_LAUNCHER_0001")
+        self.assertEqual(req.get_header("Cookie"),
+                         "PART_NUMBER=ROCKET_LAUNCHER_0001")
 
         headers.append(
             "Set-Cookie: PART_NUMBER=RIDING_ROCKET_0023; path=/ammo")
@@ -1386,40 +1386,40 @@
         # legal domain
         cookie = interact_2965(c, "http://www.acme.com",
                                'ping=pong; domain="acme.com"; version=1')
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
 
         # illegal domain (host prefix "www.a" contains a dot)
         cookie = interact_2965(c, "http://www.a.acme.com",
                                'whiz=bang; domain="acme.com"; version=1')
-        self.assertEquals(len(c), 1)
+        self.assertEqual(len(c), 1)
 
         # legal domain
         cookie = interact_2965(c, "http://www.a.acme.com",
                                'wow=flutter; domain=".a.acme.com"; version=1')
-        self.assertEquals(len(c), 2)
+        self.assertEqual(len(c), 2)
 
         # can't partially match an IP-address
         cookie = interact_2965(c, "http://125.125.125.125",
                                'zzzz=ping; domain="125.125.125"; version=1')
-        self.assertEquals(len(c), 2)
+        self.assertEqual(len(c), 2)
 
         # illegal path (must be prefix of request path)
         cookie = interact_2965(c, "http://www.sol.no",
                                'blah=rhubarb; domain=".sol.no"; path="/foo"; '
                                'version=1')
-        self.assertEquals(len(c), 2)
+        self.assertEqual(len(c), 2)
 
         # legal path
         cookie = interact_2965(c, "http://www.sol.no/foo/bar",
                                'bing=bong; domain=".sol.no"; path="/foo"; '
                                'version=1')
-        self.assertEquals(len(c), 3)
+        self.assertEqual(len(c), 3)
 
         # illegal port (request-port not in list)
         cookie = interact_2965(c, "http://www.sol.no",
                                'whiz=ffft; domain=".sol.no"; port="90,100"; '
                                'version=1')
-        self.assertEquals(len(c), 3)
+        self.assertEqual(len(c), 3)
 
         # legal port
         cookie = interact_2965(
@@ -1427,13 +1427,13 @@
             r'bang=wallop; version=1; domain=".sol.no"; '
             r'port="90,100, 80,8080"; '
             r'max-age=100; Comment = "Just kidding! (\"|\\\\) "')
-        self.assertEquals(len(c), 4)
+        self.assertEqual(len(c), 4)
 
         # port attribute without any value (current port)
         cookie = interact_2965(c, "http://www.sol.no",
                                'foo9=bar; version=1; domain=".sol.no"; port; '
                                'max-age=100;')
-        self.assertEquals(len(c), 5)
+        self.assertEqual(len(c), 5)
 
         # encoded path
         # LWP has this test, but unescaping allowed path characters seems
@@ -1444,7 +1444,7 @@
         # character:
         cookie = interact_2965(c, "http://www.sol.no/<oo/",
                                r'foo8=bar; version=1; path="/%3coo"')
-        self.assertEquals(len(c), 6)
+        self.assertEqual(len(c), 6)
 
         # save and restore
         filename = test.support.TESTFN
@@ -1459,7 +1459,7 @@
             try: os.unlink(filename)
             except OSError: pass
 
-        self.assertEquals(old, repr(c))
+        self.assertEqual(old, repr(c))
 
     def test_url_encoding(self):
         # Try some URL encodings of the PATHs.
@@ -1517,11 +1517,11 @@
             return new_c
 
         new_c = save_and_restore(c, True)
-        self.assertEquals(len(new_c), 6)  # none discarded
+        self.assertEqual(len(new_c), 6)  # none discarded
         self.assertIn("name='foo1', value='bar'", repr(new_c))
 
         new_c = save_and_restore(c, False)
-        self.assertEquals(len(new_c), 4)  # 2 of them discarded on save
+        self.assertEqual(len(new_c), 4)  # 2 of them discarded on save
         self.assertIn("name='foo1', value='bar'", repr(new_c))
 
     def test_netscape_misc(self):
@@ -1559,19 +1559,19 @@
         interact_2965(c, "http://example/", 'foo3=bar; Version=1')
         cookie = interact_2965(c, "http://example/")
         self.assertIn("foo2=bar", cookie)
-        self.assertEquals(len(c), 3)
+        self.assertEqual(len(c), 3)
 
     def test_intranet_domains_ns(self):
         c = CookieJar(DefaultCookiePolicy(rfc2965 = False))
         interact_netscape(c, "http://example/", "foo1=bar")
         cookie = interact_netscape(c, "http://example/",
                                    'foo2=bar; domain=.local')
-        self.assertEquals(len(c), 2)
+        self.assertEqual(len(c), 2)
         self.assertIn("foo1=bar", cookie)
 
         cookie = interact_netscape(c, "http://example/")
         self.assertIn("foo2=bar", cookie)
-        self.assertEquals(len(c), 2)
+        self.assertEqual(len(c), 2)
 
     def test_empty_path(self):
         # Test for empty path
@@ -1592,17 +1592,17 @@
         req = urllib.request.Request("http://www.ants.com/")
         c.add_cookie_header(req)
 
-        self.assertEquals(req.get_header("Cookie"),
-                          "JSESSIONID=ABCDERANDOM123")
-        self.assertEquals(req.get_header("Cookie2"), '$Version="1"')
+        self.assertEqual(req.get_header("Cookie"),
+                         "JSESSIONID=ABCDERANDOM123")
+        self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
 
         # missing path in the request URI
         req = urllib.request.Request("http://www.ants.com:8080")
         c.add_cookie_header(req)
 
-        self.assertEquals(req.get_header("Cookie"),
-                          "JSESSIONID=ABCDERANDOM123")
-        self.assertEquals(req.get_header("Cookie2"), '$Version="1"')
+        self.assertEqual(req.get_header("Cookie"),
+                         "JSESSIONID=ABCDERANDOM123")
+        self.assertEqual(req.get_header("Cookie2"), '$Version="1"')
 
     def test_session_cookies(self):
         year_plus_one = time.localtime()[0] + 1

Modified: python/branches/pep-3151/Lib/test/test_http_cookies.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_http_cookies.py	(original)
+++ python/branches/pep-3151/Lib/test/test_http_cookies.py	Sat Feb 26 08:16:32 2011
@@ -69,6 +69,14 @@
         </script>
         """)
 
+    def test_extended_encode(self):
+        # Issue 9824: some browsers don't follow the standard; we now
+        # encode , and ; to keep them from tripping up.
+        C = cookies.SimpleCookie()
+        C['val'] = "some,funky;stuff"
+        self.assertEqual(C.output(['val']),
+            'Set-Cookie: val="some\\054funky\\073stuff"')
+
     def test_special_attrs(self):
         # 'expires'
         C = cookies.SimpleCookie('Customer="WILE_E_COYOTE"')

Modified: python/branches/pep-3151/Lib/test/test_httplib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_httplib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_httplib.py	Sat Feb 26 08:16:32 2011
@@ -106,6 +106,25 @@
         conn.putheader('Content-length', 42)
         self.assertTrue(b'Content-length: 42' in conn._buffer)
 
+    def test_ipv6host_header(self):
+        # Default host header on IPv6 transaction should wrapped by [] if
+        # its actual IPv6 address
+        expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
+                   b'Accept-Encoding: identity\r\n\r\n'
+        conn = client.HTTPConnection('[2001::]:81')
+        sock = FakeSocket('')
+        conn.sock = sock
+        conn.request('GET', '/foo')
+        self.assertTrue(sock.data.startswith(expected))
+
+        expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
+                   b'Accept-Encoding: identity\r\n\r\n'
+        conn = client.HTTPConnection('[2001:102A::]')
+        sock = FakeSocket('')
+        conn.sock = sock
+        conn.request('GET', '/foo')
+        self.assertTrue(sock.data.startswith(expected))
+
 
 class BasicTest(TestCase):
     def test_status_lines(self):
@@ -125,7 +144,7 @@
 
     def test_bad_status_repr(self):
         exc = client.BadStatusLine('')
-        self.assertEquals(repr(exc), '''BadStatusLine("\'\'",)''')
+        self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
 
     def test_partial_reads(self):
         # if we have a lenght, the system knows when to close itself
@@ -203,13 +222,29 @@
         sock = FakeSocket(None)
         conn.sock = sock
         conn.send(expected)
-        self.assertEquals(expected, sock.data)
+        self.assertEqual(expected, sock.data)
         sock.data = b''
         conn.send(array.array('b', expected))
-        self.assertEquals(expected, sock.data)
+        self.assertEqual(expected, sock.data)
         sock.data = b''
         conn.send(io.BytesIO(expected))
-        self.assertEquals(expected, sock.data)
+        self.assertEqual(expected, sock.data)
+
+    def test_send_iter(self):
+        expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
+                   b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
+                   b'\r\nonetwothree'
+
+        def body():
+            yield b"one"
+            yield b"two"
+            yield b"three"
+
+        conn = client.HTTPConnection('example.com')
+        sock = FakeSocket("")
+        conn.sock = sock
+        conn.request('GET', '/foo', body(), {'Content-Length': '11'})
+        self.assertEqual(sock.data, expected)
 
     def test_chunked(self):
         chunked_start = (
@@ -223,7 +258,7 @@
         sock = FakeSocket(chunked_start + '0\r\n')
         resp = client.HTTPResponse(sock, method="GET")
         resp.begin()
-        self.assertEquals(resp.read(), b'hello world')
+        self.assertEqual(resp.read(), b'hello world')
         resp.close()
 
         for x in ('', 'foo\r\n'):
@@ -233,7 +268,7 @@
             try:
                 resp.read()
             except client.IncompleteRead as i:
-                self.assertEquals(i.partial, b'hello world')
+                self.assertEqual(i.partial, b'hello world')
                 self.assertEqual(repr(i),'IncompleteRead(11 bytes read)')
                 self.assertEqual(str(i),'IncompleteRead(11 bytes read)')
             else:
@@ -253,9 +288,9 @@
         sock = FakeSocket(chunked_start + '0\r\n')
         resp = client.HTTPResponse(sock, method="HEAD")
         resp.begin()
-        self.assertEquals(resp.read(), b'')
-        self.assertEquals(resp.status, 200)
-        self.assertEquals(resp.reason, 'OK')
+        self.assertEqual(resp.read(), b'')
+        self.assertEqual(resp.status, 200)
+        self.assertEqual(resp.reason, 'OK')
         self.assertTrue(resp.isclosed())
 
     def test_negative_content_length(self):
@@ -263,7 +298,7 @@
             'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
         resp = client.HTTPResponse(sock, method="GET")
         resp.begin()
-        self.assertEquals(resp.read(), b'Hello\r\n')
+        self.assertEqual(resp.read(), b'Hello\r\n')
         resp.close()
 
     def test_incomplete_read(self):
@@ -273,7 +308,7 @@
         try:
             resp.read()
         except client.IncompleteRead as i:
-            self.assertEquals(i.partial, b'Hello\r\n')
+            self.assertEqual(i.partial, b'Hello\r\n')
             self.assertEqual(repr(i),
                              "IncompleteRead(7 bytes read, 3 more expected)")
             self.assertEqual(str(i),
@@ -298,9 +333,36 @@
         self.assertEqual("Basic realm=\"example\"",
                          resp.getheader("www-authenticate"))
 
+    # Test lines overflowing the max line size (_MAXLINE in http.client)
+
+    def test_overflowing_status_line(self):
+        body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
+        resp = client.HTTPResponse(FakeSocket(body))
+        self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
+
+    def test_overflowing_header_line(self):
+        body = (
+            'HTTP/1.1 200 OK\r\n'
+            'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
+        )
+        resp = client.HTTPResponse(FakeSocket(body))
+        self.assertRaises(client.LineTooLong, resp.begin)
+
+    def test_overflowing_chunked_line(self):
+        body = (
+            'HTTP/1.1 200 OK\r\n'
+            'Transfer-Encoding: chunked\r\n\r\n'
+            + '0' * 65536 + 'a\r\n'
+            'hello world\r\n'
+            '0\r\n'
+        )
+        resp = client.HTTPResponse(FakeSocket(body))
+        resp.begin()
+        self.assertRaises(client.LineTooLong, resp.read)
+
 class OfflineTest(TestCase):
     def test_responses(self):
-        self.assertEquals(client.responses[client.NOT_FOUND], "Not Found")
+        self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
 
 
 class SourceAddressTest(TestCase):
@@ -498,7 +560,7 @@
         self.conn.request("PUT", "/url", "body")
         message, f = self.get_headers_and_fp()
         self.assertEqual("text/plain", message.get_content_type())
-        self.assertEqual(None, message.get_charset())
+        self.assertIsNone(message.get_charset())
         self.assertEqual("4", message.get("content-length"))
         self.assertEqual(b'body', f.read())
 
@@ -506,7 +568,7 @@
         self.conn.request("PUT", "/url", "body\xc1")
         message, f = self.get_headers_and_fp()
         self.assertEqual("text/plain", message.get_content_type())
-        self.assertEqual(None, message.get_charset())
+        self.assertIsNone(message.get_charset())
         self.assertEqual("5", message.get("content-length"))
         self.assertEqual(b'body\xc1', f.read())
 
@@ -514,7 +576,7 @@
         self.conn.request("PUT", "/url", b"body\xc1")
         message, f = self.get_headers_and_fp()
         self.assertEqual("text/plain", message.get_content_type())
-        self.assertEqual(None, message.get_charset())
+        self.assertIsNone(message.get_charset())
         self.assertEqual("5", message.get("content-length"))
         self.assertEqual(b'body\xc1', f.read())
 
@@ -525,7 +587,7 @@
             self.conn.request("PUT", "/url", f)
             message, f = self.get_headers_and_fp()
             self.assertEqual("text/plain", message.get_content_type())
-            self.assertEqual(None, message.get_charset())
+            self.assertIsNone(message.get_charset())
             self.assertEqual("4", message.get("content-length"))
             self.assertEqual(b'body', f.read())
 
@@ -536,7 +598,7 @@
             self.conn.request("PUT", "/url", f)
             message, f = self.get_headers_and_fp()
             self.assertEqual("text/plain", message.get_content_type())
-            self.assertEqual(None, message.get_charset())
+            self.assertIsNone(message.get_charset())
             self.assertEqual("5", message.get("content-length"))
             self.assertEqual(b'body\xc1', f.read())
 

Modified: python/branches/pep-3151/Lib/test/test_httpservers.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_httpservers.py	(original)
+++ python/branches/pep-3151/Lib/test/test_httpservers.py	Sat Feb 26 08:16:32 2011
@@ -97,6 +97,14 @@
             self.send_header('Connection', 'close')
             self.end_headers()
 
+        def do_LATINONEHEADER(self):
+            self.send_response(999)
+            self.send_header('X-Special', 'Dängerous Mind')
+            self.send_header('Connection', 'close')
+            self.end_headers()
+            body = self.headers['x-special-incoming'].encode('utf-8')
+            self.wfile.write(body)
+
     def setUp(self):
         BaseTestCase.setUp(self)
         self.con = http.client.HTTPConnection('localhost', self.PORT)
@@ -194,6 +202,14 @@
         res = self.con.getresponse()
         self.assertEqual(res.status, 999)
 
+    def test_latin1_header(self):
+        self.con.request('LATINONEHEADER', '/', headers={
+            'X-Special-Incoming':       'Ärger mit Unicode'
+        })
+        res = self.con.getresponse()
+        self.assertEqual(res.getheader('X-Special'), 'Dängerous Mind')
+        self.assertEqual(res.read(), 'Ärger mit Unicode'.encode('utf-8'))
+
 
 class SimpleHTTPServerTestCase(BaseTestCase):
     class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler):
@@ -511,6 +527,49 @@
         self.verify_get_called()
         self.assertEqual(result[-1], b'<html><body>Data</body></html>\r\n')
 
+    def test_header_buffering(self):
+
+        def _readAndReseek(f):
+            pos = f.tell()
+            f.seek(0)
+            data = f.read()
+            f.seek(pos)
+            return data
+
+        input = BytesIO(b'GET / HTTP/1.1\r\n\r\n')
+        output = BytesIO()
+        self.handler.rfile = input
+        self.handler.wfile = output
+        self.handler.request_version = 'HTTP/1.1'
+
+        self.handler.send_header('Foo', 'foo')
+        self.handler.send_header('bar', 'bar')
+        self.assertEqual(_readAndReseek(output), b'')
+        self.handler.end_headers()
+        self.assertEqual(_readAndReseek(output),
+                         b'Foo: foo\r\nbar: bar\r\n\r\n')
+
+    def test_header_unbuffered_when_continue(self):
+
+        def _readAndReseek(f):
+            pos = f.tell()
+            f.seek(0)
+            data = f.read()
+            f.seek(pos)
+            return data
+
+        input = BytesIO(b'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n')
+        output = BytesIO()
+        self.handler.rfile = input
+        self.handler.wfile = output
+        self.handler.request_version = 'HTTP/1.1'
+
+        self.handler.handle_one_request()
+        self.assertNotEqual(_readAndReseek(output), b'')
+        result = _readAndReseek(output).split(b'\r\n')
+        self.assertEqual(result[0], b'HTTP/1.1 100 Continue')
+        self.assertEqual(result[1], b'HTTP/1.1 200 OK')
+
     def test_with_continue_rejected(self):
         usual_handler = self.handler        # Save to avoid breaking any subsequent tests.
         self.handler = RejectingSocketlessRequestHandler()
@@ -523,6 +582,19 @@
         self.assertEqual(sum(r == b'Connection: close\r\n' for r in result[1:-1]), 1)
         self.handler = usual_handler        # Restore to avoid breaking any subsequent tests.
 
+    def test_request_length(self):
+        # Issue #10714: huge request lines are discarded, to avoid Denial
+        # of Service attacks.
+        result = self.send_typical_request(b'GET ' + b'x' * 65537)
+        self.assertEqual(result[0], b'HTTP/1.1 414 Request-URI Too Long\r\n')
+        self.assertFalse(self.handler.get_called)
+
+    def test_header_length(self):
+        # Issue #6791: same for headers
+        result = self.send_typical_request(
+            b'GET / HTTP/1.1\r\nX-Foo: bar' + b'r' * 65537 + b'\r\n\r\n')
+        self.assertEqual(result[0], b'HTTP/1.1 400 Line too long\r\n')
+        self.assertFalse(self.handler.get_called)
 
 class SimpleHTTPRequestHandlerTestCase(unittest.TestCase):
     """ Test url parsing """

Modified: python/branches/pep-3151/Lib/test/test_imaplib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_imaplib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_imaplib.py	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,7 @@
 import os.path
 import socketserver
 import time
+import calendar
 
 from test.support import reap_threads, verbose, transient_internet
 import unittest
@@ -23,6 +24,18 @@
 
 class TestImaplib(unittest.TestCase):
 
+    def test_Internaldate2tuple(self):
+        t0 = calendar.timegm((2000, 1, 1, 0, 0, 0, -1, -1, -1))
+        tt = imaplib.Internaldate2tuple(
+            b'25 (INTERNALDATE "01-Jan-2000 00:00:00 +0000")')
+        self.assertEqual(time.mktime(tt), t0)
+        tt = imaplib.Internaldate2tuple(
+            b'25 (INTERNALDATE "01-Jan-2000 11:30:00 +1130")')
+        self.assertEqual(time.mktime(tt), t0)
+        tt = imaplib.Internaldate2tuple(
+            b'25 (INTERNALDATE "31-Dec-1999 12:30:00 -1130")')
+        self.assertEqual(time.mktime(tt), t0)
+
     def test_that_Time2Internaldate_returns_a_result(self):
         # We can check only that it successfully produces a result,
         # not the correctness of the result itself, since the result
@@ -60,7 +73,7 @@
     timeout = 1
 
     def _send(self, message):
-        if verbose: print("SENT:", message.strip())
+        if verbose: print("SENT: %r" % message.strip())
         self.wfile.write(message)
 
     def handle(self):
@@ -84,7 +97,7 @@
                 if line.endswith(b'\r\n'):
                     break
 
-            if verbose: print('GOT:', line.strip())
+            if verbose: print('GOT: %r' % line.strip())
             splitline = line.split()
             tag = splitline[0].decode('ASCII')
             cmd = splitline[1].decode('ASCII')
@@ -112,7 +125,7 @@
 
         if verbose: print("creating server")
         server = MyServer(addr, hdlr)
-        self.assertEquals(server.server_address, server.socket.getsockname())
+        self.assertEqual(server.server_address, server.socket.getsockname())
 
         if verbose:
             print("server created")
@@ -135,6 +148,7 @@
     def reap_server(self, server, thread):
         if verbose: print("waiting for server")
         server.shutdown()
+        server.server_close()
         thread.join()
         if verbose: print("done")
 
@@ -208,9 +222,9 @@
             self.server.logout()
 
     def test_logincapa(self):
+        for cap in self.server.capabilities:
+            self.assertIsInstance(cap, str)
         self.assertTrue('LOGINDISABLED' in self.server.capabilities)
-
-    def test_anonlogin(self):
         self.assertTrue('AUTH=ANONYMOUS' in self.server.capabilities)
         rs = self.server.login(self.username, self.password)
         self.assertEqual(rs[0], 'OK')
@@ -222,11 +236,27 @@
 
 
 @unittest.skipUnless(ssl, "SSL not available")
+class RemoteIMAP_STARTTLSTest(RemoteIMAPTest):
+
+    def setUp(self):
+        super().setUp()
+        rs = self.server.starttls()
+        self.assertEqual(rs[0], 'OK')
+
+    def test_logincapa(self):
+        for cap in self.server.capabilities:
+            self.assertIsInstance(cap, str)
+        self.assertFalse('LOGINDISABLED' in self.server.capabilities)
+
+
+ at unittest.skipUnless(ssl, "SSL not available")
 class RemoteIMAP_SSLTest(RemoteIMAPTest):
     port = 993
     imap_class = IMAP4_SSL
 
     def test_logincapa(self):
+        for cap in self.server.capabilities:
+            self.assertIsInstance(cap, str)
         self.assertFalse('LOGINDISABLED' in self.server.capabilities)
         self.assertTrue('AUTH=PLAIN' in self.server.capabilities)
 
@@ -243,7 +273,7 @@
                 raise support.TestFailed("Can't read certificate files!")
         tests.extend([
             ThreadedNetworkedTests, ThreadedNetworkedTestsSSL,
-            RemoteIMAPTest, RemoteIMAP_SSLTest,
+            RemoteIMAPTest, RemoteIMAP_SSLTest, RemoteIMAP_STARTTLSTest,
         ])
 
     support.run_unittest(*tests)

Modified: python/branches/pep-3151/Lib/test/test_imp.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_imp.py	(original)
+++ python/branches/pep-3151/Lib/test/test_imp.py	Sat Feb 26 08:16:32 2011
@@ -85,7 +85,7 @@
                 file.write("# coding: cp1252\nu = 'test.test_imp'\n")
             file, filename, info = imp.find_module(temp_mod_name)
             file.close()
-            self.assertEquals(file.encoding, 'cp1252')
+            self.assertEqual(file.encoding, 'cp1252')
         finally:
             del sys.path[0]
             support.unlink(temp_mod_name + '.py')

Modified: python/branches/pep-3151/Lib/test/test_import.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_import.py	(original)
+++ python/branches/pep-3151/Lib/test/test_import.py	Sat Feb 26 08:16:32 2011
@@ -9,11 +9,13 @@
 import stat
 import sys
 import unittest
+import textwrap
 
 from test.support import (
     EnvironmentVarGuard, TESTFN, check_warnings, forget, is_jython,
     make_legacy_pyc, rmtree, run_unittest, swap_attr, swap_item, temp_umask,
     unlink, unload)
+from test import script_helper
 
 
 def remove_files(name):
@@ -284,6 +286,17 @@
         self.assertEqual("Import by filename is not supported.",
                          c.exception.args[0])
 
+    def test_import_in_del_does_not_crash(self):
+        # Issue 4236
+        testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\
+            import sys
+            class C:
+               def __del__(self):
+                  import imp
+            sys.argv.insert(0, C())
+            """))
+        script_helper.assert_python_ok(testfn)
+
 
 class PycRewritingTests(unittest.TestCase):
     # Test that the `co_filename` attribute on code objects always points

Modified: python/branches/pep-3151/Lib/test/test_inspect.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_inspect.py	(original)
+++ python/branches/pep-3151/Lib/test/test_inspect.py	Sat Feb 26 08:16:32 2011
@@ -6,9 +6,11 @@
 import linecache
 import datetime
 import collections
+import os
+import shutil
 from os.path import normcase
 
-from test.support import run_unittest
+from test.support import run_unittest, TESTFN, DirsOnSysPath
 
 from test import inspect_fodder as mod
 from test import inspect_fodder2 as mod2
@@ -194,12 +196,12 @@
 
 class GetSourceBase(unittest.TestCase):
     # Subclasses must override.
-    fodderFile = None
+    fodderModule = None
 
     def __init__(self, *args, **kwargs):
         unittest.TestCase.__init__(self, *args, **kwargs)
 
-        with open(inspect.getsourcefile(self.fodderFile)) as fp:
+        with open(inspect.getsourcefile(self.fodderModule)) as fp:
             self.source = fp.read()
 
     def sourcerange(self, top, bottom):
@@ -211,7 +213,7 @@
                          self.sourcerange(top, bottom))
 
 class TestRetrievingSourceCode(GetSourceBase):
-    fodderFile = mod
+    fodderModule = mod
 
     def test_getclasses(self):
         classes = inspect.getmembers(mod, inspect.isclass)
@@ -297,7 +299,7 @@
         inspect.getmodule(compile('a=10','','single'))
 
 class TestDecorators(GetSourceBase):
-    fodderFile = mod2
+    fodderModule = mod2
 
     def test_wrapped_decorator(self):
         self.assertSourceEqual(mod2.wrapped, 14, 17)
@@ -306,7 +308,7 @@
         self.assertSourceEqual(mod2.gone, 9, 10)
 
 class TestOneliners(GetSourceBase):
-    fodderFile = mod2
+    fodderModule = mod2
     def test_oneline_lambda(self):
         # Test inspect.getsource with a one-line lambda function.
         self.assertSourceEqual(mod2.oll, 25, 25)
@@ -348,7 +350,7 @@
         self.assertSourceEqual(mod2.anonymous, 55, 55)
 
 class TestBuggyCases(GetSourceBase):
-    fodderFile = mod2
+    fodderModule = mod2
 
     def test_with_comment(self):
         self.assertSourceEqual(mod2.with_comment, 58, 59)
@@ -385,8 +387,26 @@
         self.assertRaises(IOError, inspect.findsource, co)
         self.assertRaises(IOError, inspect.getsource, co)
         linecache.cache[co.co_filename] = (1, None, lines, co.co_filename)
-        self.assertEquals(inspect.findsource(co), (lines,0))
-        self.assertEquals(inspect.getsource(co), lines[0])
+        self.assertEqual(inspect.findsource(co), (lines,0))
+        self.assertEqual(inspect.getsource(co), lines[0])
+
+class TestNoEOL(GetSourceBase):
+    def __init__(self, *args, **kwargs):
+        self.tempdir = TESTFN + '_dir'
+        os.mkdir(self.tempdir)
+        with open(os.path.join(self.tempdir,
+                               'inspect_fodder3%spy' % os.extsep), 'w') as f:
+            f.write("class X:\n    pass # No EOL")
+        with DirsOnSysPath(self.tempdir):
+            import inspect_fodder3 as mod3
+        self.fodderModule = mod3
+        GetSourceBase.__init__(self, *args, **kwargs)
+
+    def tearDown(self):
+        shutil.rmtree(self.tempdir)
+
+    def test_class(self):
+        self.assertSourceEqual(self.fodderModule.X, 1, 2)
 
 # Helper for testing classify_class_attrs.
 def attrs_wo_objs(cls):
@@ -706,12 +726,248 @@
         locs = dict(locs or {}, inst=self.inst)
         return (func, 'inst,' + call_params_string, locs)
 
+
+class TestGetattrStatic(unittest.TestCase):
+
+    def test_basic(self):
+        class Thing(object):
+            x = object()
+
+        thing = Thing()
+        self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
+        self.assertEqual(inspect.getattr_static(thing, 'x', None), Thing.x)
+        with self.assertRaises(AttributeError):
+            inspect.getattr_static(thing, 'y')
+
+        self.assertEqual(inspect.getattr_static(thing, 'y', 3), 3)
+
+    def test_inherited(self):
+        class Thing(object):
+            x = object()
+        class OtherThing(Thing):
+            pass
+
+        something = OtherThing()
+        self.assertEqual(inspect.getattr_static(something, 'x'), Thing.x)
+
+    def test_instance_attr(self):
+        class Thing(object):
+            x = 2
+            def __init__(self, x):
+                self.x = x
+        thing = Thing(3)
+        self.assertEqual(inspect.getattr_static(thing, 'x'), 3)
+        del thing.x
+        self.assertEqual(inspect.getattr_static(thing, 'x'), 2)
+
+    def test_property(self):
+        class Thing(object):
+            @property
+            def x(self):
+                raise AttributeError("I'm pretending not to exist")
+        thing = Thing()
+        self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
+
+    def test_descriptor(self):
+        class descriptor(object):
+            def __get__(*_):
+                raise AttributeError("I'm pretending not to exist")
+        desc = descriptor()
+        class Thing(object):
+            x = desc
+        thing = Thing()
+        self.assertEqual(inspect.getattr_static(thing, 'x'), desc)
+
+    def test_classAttribute(self):
+        class Thing(object):
+            x = object()
+
+        self.assertEqual(inspect.getattr_static(Thing, 'x'), Thing.x)
+
+    def test_inherited_classattribute(self):
+        class Thing(object):
+            x = object()
+        class OtherThing(Thing):
+            pass
+
+        self.assertEqual(inspect.getattr_static(OtherThing, 'x'), Thing.x)
+
+    def test_slots(self):
+        class Thing(object):
+            y = 'bar'
+            __slots__ = ['x']
+            def __init__(self):
+                self.x = 'foo'
+        thing = Thing()
+        self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
+        self.assertEqual(inspect.getattr_static(thing, 'y'), 'bar')
+
+        del thing.x
+        self.assertEqual(inspect.getattr_static(thing, 'x'), Thing.x)
+
+    def test_metaclass(self):
+        class meta(type):
+            attr = 'foo'
+        class Thing(object, metaclass=meta):
+            pass
+        self.assertEqual(inspect.getattr_static(Thing, 'attr'), 'foo')
+
+        class sub(meta):
+            pass
+        class OtherThing(object, metaclass=sub):
+            x = 3
+        self.assertEqual(inspect.getattr_static(OtherThing, 'attr'), 'foo')
+
+        class OtherOtherThing(OtherThing):
+            pass
+        # this test is odd, but it was added as it exposed a bug
+        self.assertEqual(inspect.getattr_static(OtherOtherThing, 'x'), 3)
+
+    def test_no_dict_no_slots(self):
+        self.assertEqual(inspect.getattr_static(1, 'foo', None), None)
+        self.assertNotEqual(inspect.getattr_static('foo', 'lower'), None)
+
+    def test_no_dict_no_slots_instance_member(self):
+        # returns descriptor
+        with open(__file__) as handle:
+            self.assertEqual(inspect.getattr_static(handle, 'name'), type(handle).name)
+
+    def test_inherited_slots(self):
+        # returns descriptor
+        class Thing(object):
+            __slots__ = ['x']
+            def __init__(self):
+                self.x = 'foo'
+
+        class OtherThing(Thing):
+            pass
+        # it would be nice if this worked...
+        # we get the descriptor instead of the instance attribute
+        self.assertEqual(inspect.getattr_static(OtherThing(), 'x'), Thing.x)
+
+    def test_descriptor(self):
+        class descriptor(object):
+            def __get__(self, instance, owner):
+                return 3
+        class Foo(object):
+            d = descriptor()
+
+        foo = Foo()
+
+        # for a non data descriptor we return the instance attribute
+        foo.__dict__['d'] = 1
+        self.assertEqual(inspect.getattr_static(foo, 'd'), 1)
+
+        # if the descriptor is a data-desciptor we should return the
+        # descriptor
+        descriptor.__set__ = lambda s, i, v: None
+        self.assertEqual(inspect.getattr_static(foo, 'd'), Foo.__dict__['d'])
+
+
+    def test_metaclass_with_descriptor(self):
+        class descriptor(object):
+            def __get__(self, instance, owner):
+                return 3
+        class meta(type):
+            d = descriptor()
+        class Thing(object, metaclass=meta):
+            pass
+        self.assertEqual(inspect.getattr_static(Thing, 'd'), meta.__dict__['d'])
+
+
+    def test_class_as_property(self):
+        class Base(object):
+            foo = 3
+
+        class Something(Base):
+            executed = False
+            @property
+            def __class__(self):
+                self.executed = True
+                return object
+
+        instance = Something()
+        self.assertEqual(inspect.getattr_static(instance, 'foo'), 3)
+        self.assertFalse(instance.executed)
+        self.assertEqual(inspect.getattr_static(Something, 'foo'), 3)
+
+    def test_mro_as_property(self):
+        class Meta(type):
+            @property
+            def __mro__(self):
+                return (object,)
+
+        class Base(object):
+            foo = 3
+
+        class Something(Base, metaclass=Meta):
+            pass
+
+        self.assertEqual(inspect.getattr_static(Something(), 'foo'), 3)
+        self.assertEqual(inspect.getattr_static(Something, 'foo'), 3)
+
+
+class TestGetGeneratorState(unittest.TestCase):
+
+    def setUp(self):
+        def number_generator():
+            for number in range(5):
+                yield number
+        self.generator = number_generator()
+
+    def _generatorstate(self):
+        return inspect.getgeneratorstate(self.generator)
+
+    def test_created(self):
+        self.assertEqual(self._generatorstate(), inspect.GEN_CREATED)
+
+    def test_suspended(self):
+        next(self.generator)
+        self.assertEqual(self._generatorstate(), inspect.GEN_SUSPENDED)
+
+    def test_closed_after_exhaustion(self):
+        for i in self.generator:
+            pass
+        self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED)
+
+    def test_closed_after_immediate_exception(self):
+        with self.assertRaises(RuntimeError):
+            self.generator.throw(RuntimeError)
+        self.assertEqual(self._generatorstate(), inspect.GEN_CLOSED)
+
+    def test_running(self):
+        # As mentioned on issue #10220, checking for the RUNNING state only
+        # makes sense inside the generator itself.
+        # The following generator checks for this by using the closure's
+        # reference to self and the generator state checking helper method
+        def running_check_generator():
+            for number in range(5):
+                self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING)
+                yield number
+                self.assertEqual(self._generatorstate(), inspect.GEN_RUNNING)
+        self.generator = running_check_generator()
+        # Running up to the first yield
+        next(self.generator)
+        # Running after the first yield
+        next(self.generator)
+
+    def test_easy_debugging(self):
+        # repr() and str() of a generator state should contain the state name
+        names = 'GEN_CREATED GEN_RUNNING GEN_SUSPENDED GEN_CLOSED'.split()
+        for name in names:
+            state = getattr(inspect, name)
+            self.assertIn(name, repr(state))
+            self.assertIn(name, str(state))
+
+
 def test_main():
     run_unittest(
         TestDecorators, TestRetrievingSourceCode, TestOneliners, TestBuggyCases,
         TestInterpreterStack, TestClassesAndFunctions, TestPredicates,
         TestGetcallargsFunctions, TestGetcallargsMethods,
-        TestGetcallargsUnboundMethods)
+        TestGetcallargsUnboundMethods, TestGetattrStatic, TestGetGeneratorState,
+        TestNoEOL
+    )
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/pep-3151/Lib/test/test_int.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_int.py	(original)
+++ python/branches/pep-3151/Lib/test/test_int.py	Sat Feb 26 08:16:32 2011
@@ -20,7 +20,8 @@
         ('  1\02  ', ValueError),
         ('', ValueError),
         (' ', ValueError),
-        ('  \t\t  ', ValueError)
+        ('  \t\t  ', ValueError),
+        ("\u0200", ValueError)
 ]
 
 class IntTestCases(unittest.TestCase):
@@ -35,6 +36,8 @@
         self.assertEqual(int(3.5), 3)
         self.assertEqual(int(-3.5), -3)
         self.assertEqual(int("-3"), -3)
+        self.assertEqual(int(" -3 "), -3)
+        self.assertEqual(int("\N{EM SPACE}-3\N{EN SPACE}"), -3)
         # Different base:
         self.assertEqual(int("10",16), 16)
         # Test conversion from strings and various anomalies
@@ -295,13 +298,23 @@
                 try:
                     int(TruncReturnsNonIntegral())
                 except TypeError as e:
-                    self.assertEquals(str(e),
+                    self.assertEqual(str(e),
                                       "__trunc__ returned non-Integral"
                                       " (type NonIntegral)")
                 else:
                     self.fail("Failed to raise TypeError with %s" %
                               ((base, trunc_result_base),))
 
+    def test_error_message(self):
+        testlist = ('\xbd', '123\xbd', '  123 456  ')
+        for s in testlist:
+            try:
+                int(s)
+            except ValueError as e:
+                self.assertIn(s.strip(), e.args[0])
+            else:
+                self.fail("Expected int(%r) to raise a ValueError", s)
+
 def test_main():
     run_unittest(IntTestCases)
 

Modified: python/branches/pep-3151/Lib/test/test_io.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_io.py	(original)
+++ python/branches/pep-3151/Lib/test/test_io.py	Sat Feb 26 08:16:32 2011
@@ -46,7 +46,7 @@
 
 def _default_chunk_size():
     """Get the default TextIOWrapper chunk size"""
-    with open(__file__, "r", encoding="latin1") as f:
+    with open(__file__, "r", encoding="latin-1") as f:
         return f._CHUNK_SIZE
 
 
@@ -630,7 +630,7 @@
         rawio = self.MockRawIO()
         bufio = self.tp(rawio)
 
-        self.assertEquals(42, bufio.fileno())
+        self.assertEqual(42, bufio.fileno())
 
     def test_no_fileno(self):
         # XXX will we always have fileno() function? If so, kill
@@ -730,6 +730,13 @@
         self.assertRaises(self.UnsupportedOperation, bufio.tell)
         self.assertRaises(self.UnsupportedOperation, bufio.seek, 0)
 
+    def test_readonly_attributes(self):
+        raw = self.MockRawIO()
+        buf = self.tp(raw)
+        x = self.MockRawIO()
+        with self.assertRaises(AttributeError):
+            buf.raw = x
+
 
 class BufferedReaderTest(unittest.TestCase, CommonBufferedTests):
     read_mode = "rb"
@@ -740,36 +747,36 @@
         bufio.__init__(rawio)
         bufio.__init__(rawio, buffer_size=1024)
         bufio.__init__(rawio, buffer_size=16)
-        self.assertEquals(b"abc", bufio.read())
+        self.assertEqual(b"abc", bufio.read())
         self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0)
         self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16)
         self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1)
         rawio = self.MockRawIO([b"abc"])
         bufio.__init__(rawio)
-        self.assertEquals(b"abc", bufio.read())
+        self.assertEqual(b"abc", bufio.read())
 
     def test_read(self):
         for arg in (None, 7):
             rawio = self.MockRawIO((b"abc", b"d", b"efg"))
             bufio = self.tp(rawio)
-            self.assertEquals(b"abcdefg", bufio.read(arg))
+            self.assertEqual(b"abcdefg", bufio.read(arg))
         # Invalid args
         self.assertRaises(ValueError, bufio.read, -2)
 
     def test_read1(self):
         rawio = self.MockRawIO((b"abc", b"d", b"efg"))
         bufio = self.tp(rawio)
-        self.assertEquals(b"a", bufio.read(1))
-        self.assertEquals(b"b", bufio.read1(1))
-        self.assertEquals(rawio._reads, 1)
-        self.assertEquals(b"c", bufio.read1(100))
-        self.assertEquals(rawio._reads, 1)
-        self.assertEquals(b"d", bufio.read1(100))
-        self.assertEquals(rawio._reads, 2)
-        self.assertEquals(b"efg", bufio.read1(100))
-        self.assertEquals(rawio._reads, 3)
-        self.assertEquals(b"", bufio.read1(100))
-        self.assertEquals(rawio._reads, 4)
+        self.assertEqual(b"a", bufio.read(1))
+        self.assertEqual(b"b", bufio.read1(1))
+        self.assertEqual(rawio._reads, 1)
+        self.assertEqual(b"c", bufio.read1(100))
+        self.assertEqual(rawio._reads, 1)
+        self.assertEqual(b"d", bufio.read1(100))
+        self.assertEqual(rawio._reads, 2)
+        self.assertEqual(b"efg", bufio.read1(100))
+        self.assertEqual(rawio._reads, 3)
+        self.assertEqual(b"", bufio.read1(100))
+        self.assertEqual(rawio._reads, 4)
         # Invalid args
         self.assertRaises(ValueError, bufio.read1, -1)
 
@@ -777,24 +784,24 @@
         rawio = self.MockRawIO((b"abc", b"d", b"efg"))
         bufio = self.tp(rawio)
         b = bytearray(2)
-        self.assertEquals(bufio.readinto(b), 2)
-        self.assertEquals(b, b"ab")
-        self.assertEquals(bufio.readinto(b), 2)
-        self.assertEquals(b, b"cd")
-        self.assertEquals(bufio.readinto(b), 2)
-        self.assertEquals(b, b"ef")
-        self.assertEquals(bufio.readinto(b), 1)
-        self.assertEquals(b, b"gf")
-        self.assertEquals(bufio.readinto(b), 0)
-        self.assertEquals(b, b"gf")
+        self.assertEqual(bufio.readinto(b), 2)
+        self.assertEqual(b, b"ab")
+        self.assertEqual(bufio.readinto(b), 2)
+        self.assertEqual(b, b"cd")
+        self.assertEqual(bufio.readinto(b), 2)
+        self.assertEqual(b, b"ef")
+        self.assertEqual(bufio.readinto(b), 1)
+        self.assertEqual(b, b"gf")
+        self.assertEqual(bufio.readinto(b), 0)
+        self.assertEqual(b, b"gf")
 
     def test_readlines(self):
         def bufio():
             rawio = self.MockRawIO((b"abc\n", b"d\n", b"ef"))
             return self.tp(rawio)
-        self.assertEquals(bufio().readlines(), [b"abc\n", b"d\n", b"ef"])
-        self.assertEquals(bufio().readlines(5), [b"abc\n", b"d\n"])
-        self.assertEquals(bufio().readlines(None), [b"abc\n", b"d\n", b"ef"])
+        self.assertEqual(bufio().readlines(), [b"abc\n", b"d\n", b"ef"])
+        self.assertEqual(bufio().readlines(5), [b"abc\n", b"d\n"])
+        self.assertEqual(bufio().readlines(None), [b"abc\n", b"d\n", b"ef"])
 
     def test_buffering(self):
         data = b"abcdefghi"
@@ -811,34 +818,34 @@
             bufio = self.tp(rawio, buffer_size=bufsize)
             pos = 0
             for nbytes in buf_read_sizes:
-                self.assertEquals(bufio.read(nbytes), data[pos:pos+nbytes])
+                self.assertEqual(bufio.read(nbytes), data[pos:pos+nbytes])
                 pos += nbytes
             # this is mildly implementation-dependent
-            self.assertEquals(rawio.read_history, raw_read_sizes)
+            self.assertEqual(rawio.read_history, raw_read_sizes)
 
     def test_read_non_blocking(self):
         # Inject some None's in there to simulate EWOULDBLOCK
         rawio = self.MockRawIO((b"abc", b"d", None, b"efg", None, None, None))
         bufio = self.tp(rawio)
 
-        self.assertEquals(b"abcd", bufio.read(6))
-        self.assertEquals(b"e", bufio.read(1))
-        self.assertEquals(b"fg", bufio.read())
-        self.assertEquals(b"", bufio.peek(1))
+        self.assertEqual(b"abcd", bufio.read(6))
+        self.assertEqual(b"e", bufio.read(1))
+        self.assertEqual(b"fg", bufio.read())
+        self.assertEqual(b"", bufio.peek(1))
         self.assertTrue(None is bufio.read())
-        self.assertEquals(b"", bufio.read())
+        self.assertEqual(b"", bufio.read())
 
     def test_read_past_eof(self):
         rawio = self.MockRawIO((b"abc", b"d", b"efg"))
         bufio = self.tp(rawio)
 
-        self.assertEquals(b"abcdefg", bufio.read(9000))
+        self.assertEqual(b"abcdefg", bufio.read(9000))
 
     def test_read_all(self):
         rawio = self.MockRawIO((b"abc", b"d", b"efg"))
         bufio = self.tp(rawio)
 
-        self.assertEquals(b"abcdefg", bufio.read())
+        self.assertEqual(b"abcdefg", bufio.read())
 
     @unittest.skipUnless(threading, 'Threading required for this test.')
     @support.requires_resource('cpu')
@@ -965,15 +972,15 @@
         bufio.__init__(rawio)
         bufio.__init__(rawio, buffer_size=1024)
         bufio.__init__(rawio, buffer_size=16)
-        self.assertEquals(3, bufio.write(b"abc"))
+        self.assertEqual(3, bufio.write(b"abc"))
         bufio.flush()
         self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0)
         self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16)
         self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1)
         bufio.__init__(rawio)
-        self.assertEquals(3, bufio.write(b"ghi"))
+        self.assertEqual(3, bufio.write(b"ghi"))
         bufio.flush()
-        self.assertEquals(b"".join(rawio._write_stack), b"abcghi")
+        self.assertEqual(b"".join(rawio._write_stack), b"abcghi")
 
     def test_detach_flush(self):
         raw = self.MockRawIO()
@@ -1015,11 +1022,11 @@
         sizes = gen_sizes()
         while n < len(contents):
             size = min(next(sizes), len(contents) - n)
-            self.assertEquals(bufio.write(contents[n:n+size]), size)
+            self.assertEqual(bufio.write(contents[n:n+size]), size)
             intermediate_func(bufio)
             n += size
         bufio.flush()
-        self.assertEquals(contents, b"".join(writer._write_stack))
+        self.assertEqual(contents, b"".join(writer._write_stack))
 
     def test_writes(self):
         self.check_writes(lambda bufio: None)
@@ -1048,11 +1055,11 @@
         raw = self.MockNonBlockWriterIO()
         bufio = self.tp(raw, 8)
 
-        self.assertEquals(bufio.write(b"abcd"), 4)
-        self.assertEquals(bufio.write(b"efghi"), 5)
+        self.assertEqual(bufio.write(b"abcd"), 4)
+        self.assertEqual(bufio.write(b"efghi"), 5)
         # 1 byte will be written, the rest will be buffered
         raw.block_on(b"k")
-        self.assertEquals(bufio.write(b"jklmn"), 5)
+        self.assertEqual(bufio.write(b"jklmn"), 5)
 
         # 8 bytes will be written, 8 will be buffered and the rest will be lost
         raw.block_on(b"0")
@@ -1062,11 +1069,11 @@
             written = e.characters_written
         else:
             self.fail("BlockingIOError should have been raised")
-        self.assertEquals(written, 16)
-        self.assertEquals(raw.pop_written(),
+        self.assertEqual(written, 16)
+        self.assertEqual(raw.pop_written(),
             b"abcdefghijklmnopqrwxyz")
 
-        self.assertEquals(bufio.write(b"ABCDEFGHI"), 9)
+        self.assertEqual(bufio.write(b"ABCDEFGHI"), 9)
         s = raw.pop_written()
         # Previously buffered bytes were flushed
         self.assertTrue(s.startswith(b"01234567A"), s)
@@ -1089,7 +1096,7 @@
         bufio = self.tp(writer, 8)
         bufio.write(b"abc")
         bufio.flush()
-        self.assertEquals(b"abc", writer._write_stack[0])
+        self.assertEqual(b"abc", writer._write_stack[0])
 
     def test_destructor(self):
         writer = self.MockRawIO()
@@ -1097,7 +1104,7 @@
         bufio.write(b"abc")
         del bufio
         support.gc_collect()
-        self.assertEquals(b"abc", writer._write_stack[0])
+        self.assertEqual(b"abc", writer._write_stack[0])
 
     def test_truncate(self):
         # Truncate implicitly flushes the buffer.
@@ -1156,7 +1163,7 @@
             with self.open(support.TESTFN, "rb") as f:
                 s = f.read()
             for i in range(256):
-                self.assertEquals(s.count(bytes([i])), N)
+                self.assertEqual(s.count(bytes([i])), N)
         finally:
             support.unlink(support.TESTFN)
 
@@ -1357,45 +1364,45 @@
         rw.write(b"eee")
         self.assertFalse(raw._write_stack) # Buffer writes
         self.assertEqual(b"ghjk", rw.read())
-        self.assertEquals(b"dddeee", raw._write_stack[0])
+        self.assertEqual(b"dddeee", raw._write_stack[0])
 
     def test_seek_and_tell(self):
         raw = self.BytesIO(b"asdfghjkl")
         rw = self.tp(raw)
 
-        self.assertEquals(b"as", rw.read(2))
-        self.assertEquals(2, rw.tell())
+        self.assertEqual(b"as", rw.read(2))
+        self.assertEqual(2, rw.tell())
         rw.seek(0, 0)
-        self.assertEquals(b"asdf", rw.read(4))
+        self.assertEqual(b"asdf", rw.read(4))
 
         rw.write(b"asdf")
         rw.seek(0, 0)
-        self.assertEquals(b"asdfasdfl", rw.read())
-        self.assertEquals(9, rw.tell())
+        self.assertEqual(b"asdfasdfl", rw.read())
+        self.assertEqual(9, rw.tell())
         rw.seek(-4, 2)
-        self.assertEquals(5, rw.tell())
+        self.assertEqual(5, rw.tell())
         rw.seek(2, 1)
-        self.assertEquals(7, rw.tell())
-        self.assertEquals(b"fl", rw.read(11))
+        self.assertEqual(7, rw.tell())
+        self.assertEqual(b"fl", rw.read(11))
         self.assertRaises(TypeError, rw.seek, 0.0)
 
     def check_flush_and_read(self, read_func):
         raw = self.BytesIO(b"abcdefghi")
         bufio = self.tp(raw)
 
-        self.assertEquals(b"ab", read_func(bufio, 2))
+        self.assertEqual(b"ab", read_func(bufio, 2))
         bufio.write(b"12")
-        self.assertEquals(b"ef", read_func(bufio, 2))
-        self.assertEquals(6, bufio.tell())
+        self.assertEqual(b"ef", read_func(bufio, 2))
+        self.assertEqual(6, bufio.tell())
         bufio.flush()
-        self.assertEquals(6, bufio.tell())
-        self.assertEquals(b"ghi", read_func(bufio))
+        self.assertEqual(6, bufio.tell())
+        self.assertEqual(b"ghi", read_func(bufio))
         raw.seek(0, 0)
         raw.write(b"XYZ")
         # flush() resets the read buffer
         bufio.flush()
         bufio.seek(0, 0)
-        self.assertEquals(b"XYZ", read_func(bufio, 3))
+        self.assertEqual(b"XYZ", read_func(bufio, 3))
 
     def test_flush_and_read(self):
         self.check_flush_and_read(lambda bufio, *args: bufio.read(*args))
@@ -1427,8 +1434,8 @@
         bufio.write(b"45")
         bufio.flush()
         bufio.seek(0, 0)
-        self.assertEquals(b"12345fghi", raw.getvalue())
-        self.assertEquals(b"12345fghi", bufio.read())
+        self.assertEqual(b"12345fghi", raw.getvalue())
+        self.assertEqual(b"12345fghi", bufio.read())
 
     def test_threads(self):
         BufferedReaderTest.test_threads(self)
@@ -1656,12 +1663,12 @@
         # Try a few one-shot test cases.
         for input, eof, output in self.test_cases:
             d = StatefulIncrementalDecoder()
-            self.assertEquals(d.decode(input, eof), output)
+            self.assertEqual(d.decode(input, eof), output)
 
         # Also test an unfinished decode, followed by forcing EOF.
         d = StatefulIncrementalDecoder()
-        self.assertEquals(d.decode(b'oiabcd'), '')
-        self.assertEquals(d.decode(b'', 1), 'abcd.')
+        self.assertEqual(d.decode(b'oiabcd'), '')
+        self.assertEqual(d.decode(b'', 1), 'abcd.')
 
 class TextIOWrapperTest(unittest.TestCase):
 
@@ -1677,13 +1684,13 @@
         r = self.BytesIO(b"\xc3\xa9\n\n")
         b = self.BufferedReader(r, 1000)
         t = self.TextIOWrapper(b)
-        t.__init__(b, encoding="latin1", newline="\r\n")
-        self.assertEquals(t.encoding, "latin1")
-        self.assertEquals(t.line_buffering, False)
-        t.__init__(b, encoding="utf8", line_buffering=True)
-        self.assertEquals(t.encoding, "utf8")
-        self.assertEquals(t.line_buffering, True)
-        self.assertEquals("\xe9\n", t.readline())
+        t.__init__(b, encoding="latin-1", newline="\r\n")
+        self.assertEqual(t.encoding, "latin-1")
+        self.assertEqual(t.line_buffering, False)
+        t.__init__(b, encoding="utf-8", line_buffering=True)
+        self.assertEqual(t.encoding, "utf-8")
+        self.assertEqual(t.line_buffering, True)
+        self.assertEqual("\xe9\n", t.readline())
         self.assertRaises(TypeError, t.__init__, b, newline=42)
         self.assertRaises(ValueError, t.__init__, b, newline='xyzzy')
 
@@ -1710,26 +1717,29 @@
         raw.name = "dummy"
         self.assertEqual(repr(t),
                          "<%s.TextIOWrapper name='dummy' encoding='utf-8'>" % modname)
+        t.mode = "r"
+        self.assertEqual(repr(t),
+                         "<%s.TextIOWrapper name='dummy' mode='r' encoding='utf-8'>" % modname)
         raw.name = b"dummy"
         self.assertEqual(repr(t),
-                         "<%s.TextIOWrapper name=b'dummy' encoding='utf-8'>" % modname)
+                         "<%s.TextIOWrapper name=b'dummy' mode='r' encoding='utf-8'>" % modname)
 
     def test_line_buffering(self):
         r = self.BytesIO()
         b = self.BufferedWriter(r, 1000)
         t = self.TextIOWrapper(b, newline="\n", line_buffering=True)
         t.write("X")
-        self.assertEquals(r.getvalue(), b"")  # No flush happened
+        self.assertEqual(r.getvalue(), b"")  # No flush happened
         t.write("Y\nZ")
-        self.assertEquals(r.getvalue(), b"XY\nZ")  # All got flushed
+        self.assertEqual(r.getvalue(), b"XY\nZ")  # All got flushed
         t.write("A\rB")
-        self.assertEquals(r.getvalue(), b"XY\nZA\rB")
+        self.assertEqual(r.getvalue(), b"XY\nZA\rB")
 
     def test_encoding(self):
         # Check the encoding attribute is always set, and valid
         b = self.BytesIO()
-        t = self.TextIOWrapper(b, encoding="utf8")
-        self.assertEqual(t.encoding, "utf8")
+        t = self.TextIOWrapper(b, encoding="utf-8")
+        self.assertEqual(t.encoding, "utf-8")
         t = self.TextIOWrapper(b)
         self.assertTrue(t.encoding is not None)
         codecs.lookup(t.encoding)
@@ -1746,11 +1756,11 @@
         # (3) ignore
         b = self.BytesIO(b"abc\n\xff\n")
         t = self.TextIOWrapper(b, encoding="ascii", errors="ignore")
-        self.assertEquals(t.read(), "abc\n\n")
+        self.assertEqual(t.read(), "abc\n\n")
         # (4) replace
         b = self.BytesIO(b"abc\n\xff\n")
         t = self.TextIOWrapper(b, encoding="ascii", errors="replace")
-        self.assertEquals(t.read(), "abc\n\ufffd\n")
+        self.assertEqual(t.read(), "abc\n\ufffd\n")
 
     def test_encoding_errors_writing(self):
         # (1) default
@@ -1767,14 +1777,14 @@
                              newline="\n")
         t.write("abc\xffdef\n")
         t.flush()
-        self.assertEquals(b.getvalue(), b"abcdef\n")
+        self.assertEqual(b.getvalue(), b"abcdef\n")
         # (4) replace
         b = self.BytesIO()
         t = self.TextIOWrapper(b, encoding="ascii", errors="replace",
                              newline="\n")
         t.write("abc\xffdef\n")
         t.flush()
-        self.assertEquals(b.getvalue(), b"abc?def\n")
+        self.assertEqual(b.getvalue(), b"abc?def\n")
 
     def test_newlines(self):
         input_lines = [ "unix\n", "windows\r\n", "os9\r", "last\n", "nonl" ]
@@ -1809,14 +1819,14 @@
                                 c2 = textio.read(2)
                                 if c2 == '':
                                     break
-                                self.assertEquals(len(c2), 2)
+                                self.assertEqual(len(c2), 2)
                                 got_lines.append(c2 + textio.readline())
                         else:
                             got_lines = list(textio)
 
                         for got_line, exp_line in zip(got_lines, exp_lines):
-                            self.assertEquals(got_line, exp_line)
-                        self.assertEquals(len(got_lines), len(exp_lines))
+                            self.assertEqual(got_line, exp_line)
+                        self.assertEqual(len(got_lines), len(exp_lines))
 
     def test_newlines_input(self):
         testdata = b"AAA\nBB\x00B\nCCC\rDDD\rEEE\r\nFFF\r\nGGG"
@@ -1830,9 +1840,9 @@
             ]:
             buf = self.BytesIO(testdata)
             txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline)
-            self.assertEquals(txt.readlines(), expected)
+            self.assertEqual(txt.readlines(), expected)
             txt.seek(0)
-            self.assertEquals(txt.read(), "".join(expected))
+            self.assertEqual(txt.read(), "".join(expected))
 
     def test_newlines_output(self):
         testdict = {
@@ -1849,8 +1859,8 @@
             txt.write("BB\nCCC\n")
             txt.write("X\rY\r\nZ")
             txt.flush()
-            self.assertEquals(buf.closed, False)
-            self.assertEquals(buf.getvalue(), expected)
+            self.assertEqual(buf.closed, False)
+            self.assertEqual(buf.getvalue(), expected)
 
     def test_destructor(self):
         l = []
@@ -1864,7 +1874,7 @@
         t.write("abc")
         del t
         support.gc_collect()
-        self.assertEquals([b"abc"], l)
+        self.assertEqual([b"abc"], l)
 
     def test_override_destructor(self):
         record = []
@@ -1908,29 +1918,29 @@
 
     def test_basic_io(self):
         for chunksize in (1, 2, 3, 4, 5, 15, 16, 17, 31, 32, 33, 63, 64, 65):
-            for enc in "ascii", "latin1", "utf8" :# , "utf-16-be", "utf-16-le":
+            for enc in "ascii", "latin-1", "utf-8" :# , "utf-16-be", "utf-16-le":
                 f = self.open(support.TESTFN, "w+", encoding=enc)
                 f._CHUNK_SIZE = chunksize
-                self.assertEquals(f.write("abc"), 3)
+                self.assertEqual(f.write("abc"), 3)
                 f.close()
                 f = self.open(support.TESTFN, "r+", encoding=enc)
                 f._CHUNK_SIZE = chunksize
-                self.assertEquals(f.tell(), 0)
-                self.assertEquals(f.read(), "abc")
+                self.assertEqual(f.tell(), 0)
+                self.assertEqual(f.read(), "abc")
                 cookie = f.tell()
-                self.assertEquals(f.seek(0), 0)
-                self.assertEquals(f.read(None), "abc")
+                self.assertEqual(f.seek(0), 0)
+                self.assertEqual(f.read(None), "abc")
                 f.seek(0)
-                self.assertEquals(f.read(2), "ab")
-                self.assertEquals(f.read(1), "c")
-                self.assertEquals(f.read(1), "")
-                self.assertEquals(f.read(), "")
-                self.assertEquals(f.tell(), cookie)
-                self.assertEquals(f.seek(0), 0)
-                self.assertEquals(f.seek(0, 2), cookie)
-                self.assertEquals(f.write("def"), 3)
-                self.assertEquals(f.seek(cookie), cookie)
-                self.assertEquals(f.read(), "def")
+                self.assertEqual(f.read(2), "ab")
+                self.assertEqual(f.read(1), "c")
+                self.assertEqual(f.read(1), "")
+                self.assertEqual(f.read(), "")
+                self.assertEqual(f.tell(), cookie)
+                self.assertEqual(f.seek(0), 0)
+                self.assertEqual(f.seek(0, 2), cookie)
+                self.assertEqual(f.write("def"), 3)
+                self.assertEqual(f.seek(cookie), cookie)
+                self.assertEqual(f.read(), "def")
                 if enc.startswith("utf"):
                     self.multi_line_test(f, enc)
                 f.close()
@@ -1955,26 +1965,26 @@
             if not line:
                 break
             rlines.append((pos, line))
-        self.assertEquals(rlines, wlines)
+        self.assertEqual(rlines, wlines)
 
     def test_telling(self):
-        f = self.open(support.TESTFN, "w+", encoding="utf8")
+        f = self.open(support.TESTFN, "w+", encoding="utf-8")
         p0 = f.tell()
         f.write("\xff\n")
         p1 = f.tell()
         f.write("\xff\n")
         p2 = f.tell()
         f.seek(0)
-        self.assertEquals(f.tell(), p0)
-        self.assertEquals(f.readline(), "\xff\n")
-        self.assertEquals(f.tell(), p1)
-        self.assertEquals(f.readline(), "\xff\n")
-        self.assertEquals(f.tell(), p2)
+        self.assertEqual(f.tell(), p0)
+        self.assertEqual(f.readline(), "\xff\n")
+        self.assertEqual(f.tell(), p1)
+        self.assertEqual(f.readline(), "\xff\n")
+        self.assertEqual(f.tell(), p2)
         f.seek(0)
         for line in f:
-            self.assertEquals(line, "\xff\n")
+            self.assertEqual(line, "\xff\n")
             self.assertRaises(IOError, f.tell)
-        self.assertEquals(f.tell(), p2)
+        self.assertEqual(f.tell(), p2)
         f.close()
 
     def test_seeking(self):
@@ -1982,7 +1992,7 @@
         prefix_size = chunk_size - 2
         u_prefix = "a" * prefix_size
         prefix = bytes(u_prefix.encode("utf-8"))
-        self.assertEquals(len(u_prefix), len(prefix))
+        self.assertEqual(len(u_prefix), len(prefix))
         u_suffix = "\u8888\n"
         suffix = bytes(u_suffix.encode("utf-8"))
         line = prefix + suffix
@@ -1990,9 +2000,9 @@
             f.write(line*2)
         with self.open(support.TESTFN, "r", encoding="utf-8") as f:
             s = f.read(prefix_size)
-            self.assertEquals(s, str(prefix, "ascii"))
-            self.assertEquals(f.tell(), prefix_size)
-            self.assertEquals(f.readline(), u_suffix)
+            self.assertEqual(s, str(prefix, "ascii"))
+            self.assertEqual(f.tell(), prefix_size)
+            self.assertEqual(f.readline(), u_suffix)
 
     def test_seeking_too(self):
         # Regression test for a specific bug
@@ -2024,11 +2034,11 @@
             for i in range(min_pos, len(decoded) + 1): # seek positions
                 for j in [1, 5, len(decoded) - i]: # read lengths
                     f = self.open(support.TESTFN, encoding='test_decoder')
-                    self.assertEquals(f.read(i), decoded[:i])
+                    self.assertEqual(f.read(i), decoded[:i])
                     cookie = f.tell()
-                    self.assertEquals(f.read(j), decoded[i:i + j])
+                    self.assertEqual(f.read(j), decoded[i:i + j])
                     f.seek(cookie)
-                    self.assertEquals(f.read(), decoded[i:])
+                    self.assertEqual(f.read(), decoded[i:])
                     f.close()
 
         # Enable the test decoder.
@@ -2067,10 +2077,10 @@
             f.write(data)
             f.write(data)
             f.seek(0)
-            self.assertEquals(f.read(), data * 2)
+            self.assertEqual(f.read(), data * 2)
             f.seek(0)
-            self.assertEquals(f.read(), data * 2)
-            self.assertEquals(buf.getvalue(), (data * 2).encode(encoding))
+            self.assertEqual(f.read(), data * 2)
+            self.assertEqual(buf.getvalue(), (data * 2).encode(encoding))
 
     def test_unreadable(self):
         class UnReadable(self.BytesIO):
@@ -2087,7 +2097,7 @@
             if not c:
                 break
             reads += c
-        self.assertEquals(reads, "AA\nBB")
+        self.assertEqual(reads, "AA\nBB")
 
     def test_readlines(self):
         txt = self.TextIOWrapper(self.BytesIO(b"AA\nBB\nCC"))
@@ -2107,7 +2117,7 @@
             if not c:
                 break
             reads += c
-        self.assertEquals(reads, "A"*127+"\nB")
+        self.assertEqual(reads, "A"*127+"\nB")
 
     def test_issue1395_1(self):
         txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii")
@@ -2119,7 +2129,7 @@
             if not c:
                 break
             reads += c
-        self.assertEquals(reads, self.normalized)
+        self.assertEqual(reads, self.normalized)
 
     def test_issue1395_2(self):
         txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii")
@@ -2131,7 +2141,7 @@
             if not c:
                 break
             reads += c
-        self.assertEquals(reads, self.normalized)
+        self.assertEqual(reads, self.normalized)
 
     def test_issue1395_3(self):
         txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii")
@@ -2142,7 +2152,7 @@
         reads += txt.readline()
         reads += txt.readline()
         reads += txt.readline()
-        self.assertEquals(reads, self.normalized)
+        self.assertEqual(reads, self.normalized)
 
     def test_issue1395_4(self):
         txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii")
@@ -2150,7 +2160,7 @@
 
         reads = txt.read(4)
         reads += txt.read()
-        self.assertEquals(reads, self.normalized)
+        self.assertEqual(reads, self.normalized)
 
     def test_issue1395_5(self):
         txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii")
@@ -2160,7 +2170,7 @@
         pos = txt.tell()
         txt.seek(0)
         txt.seek(pos)
-        self.assertEquals(txt.read(4), "BBB\n")
+        self.assertEqual(txt.read(4), "BBB\n")
 
     def test_issue2282(self):
         buffer = self.BytesIO(self.testdata)
@@ -2176,12 +2186,12 @@
                 f.write('aaa')
                 pos = f.tell()
             with self.open(filename, 'rb') as f:
-                self.assertEquals(f.read(), 'aaa'.encode(charset))
+                self.assertEqual(f.read(), 'aaa'.encode(charset))
 
             with self.open(filename, 'a', encoding=charset) as f:
                 f.write('xxx')
             with self.open(filename, 'rb') as f:
-                self.assertEquals(f.read(), 'aaaxxx'.encode(charset))
+                self.assertEqual(f.read(), 'aaaxxx'.encode(charset))
 
     def test_seek_bom(self):
         # Same test, but when seeking manually
@@ -2196,7 +2206,7 @@
                 f.seek(0)
                 f.write('bbb')
             with self.open(filename, 'rb') as f:
-                self.assertEquals(f.read(), 'bbbzzz'.encode(charset))
+                self.assertEqual(f.read(), 'bbbzzz'.encode(charset))
 
     def test_errors_property(self):
         with self.open(support.TESTFN, "w") as f:
@@ -2204,6 +2214,7 @@
         with self.open(support.TESTFN, "w", errors="replace") as f:
             self.assertEqual(f.errors, "replace")
 
+    @support.no_tracing
     @unittest.skipUnless(threading, 'Threading required for this test.')
     def test_threads_write(self):
         # Issue6750: concurrent writes could duplicate data
@@ -2224,7 +2235,7 @@
         with self.open(support.TESTFN) as f:
             content = f.read()
             for n in range(20):
-                self.assertEquals(content.count("Thread%03d\n" % n), 1)
+                self.assertEqual(content.count("Thread%03d\n" % n), 1)
 
     def test_flush_error_on_close(self):
         txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii")
@@ -2245,6 +2256,12 @@
         self.assertRaises(self.UnsupportedOperation, txt.tell)
         self.assertRaises(self.UnsupportedOperation, txt.seek, 0)
 
+    def test_readonly_attributes(self):
+        txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii")
+        buf = self.BytesIO(self.testdata)
+        with self.assertRaises(AttributeError):
+            txt.buffer = buf
+
 class CTextIOWrapperTest(TextIOWrapperTest):
 
     def test_initialization(self):
@@ -2283,9 +2300,9 @@
         def _check_decode(b, s, **kwargs):
             # We exercise getstate() / setstate() as well as decode()
             state = decoder.getstate()
-            self.assertEquals(decoder.decode(b, **kwargs), s)
+            self.assertEqual(decoder.decode(b, **kwargs), s)
             decoder.setstate(state)
-            self.assertEquals(decoder.decode(b, **kwargs), s)
+            self.assertEqual(decoder.decode(b, **kwargs), s)
 
         _check_decode(b'\xe8\xa2\x88', "\u8888")
 
@@ -2334,24 +2351,24 @@
                 # Decode one char at a time
                 for c in s:
                     result.append(decoder.decode(c))
-        self.assertEquals(decoder.newlines, None)
+        self.assertEqual(decoder.newlines, None)
         _decode_bytewise("abc\n\r")
-        self.assertEquals(decoder.newlines, '\n')
+        self.assertEqual(decoder.newlines, '\n')
         _decode_bytewise("\nabc")
-        self.assertEquals(decoder.newlines, ('\n', '\r\n'))
+        self.assertEqual(decoder.newlines, ('\n', '\r\n'))
         _decode_bytewise("abc\r")
-        self.assertEquals(decoder.newlines, ('\n', '\r\n'))
+        self.assertEqual(decoder.newlines, ('\n', '\r\n'))
         _decode_bytewise("abc")
-        self.assertEquals(decoder.newlines, ('\r', '\n', '\r\n'))
+        self.assertEqual(decoder.newlines, ('\r', '\n', '\r\n'))
         _decode_bytewise("abc\r")
-        self.assertEquals("".join(result), "abc\n\nabcabc\nabcabc")
+        self.assertEqual("".join(result), "abc\n\nabcabc\nabcabc")
         decoder.reset()
         input = "abc"
         if encoder is not None:
             encoder.reset()
             input = encoder.encode(input)
-        self.assertEquals(decoder.decode(input), "abc")
-        self.assertEquals(decoder.newlines, None)
+        self.assertEqual(decoder.decode(input), "abc")
+        self.assertEqual(decoder.newlines, None)
 
     def test_newline_decoder(self):
         encodings = (
@@ -2372,11 +2389,11 @@
     def test_newline_bytes(self):
         # Issue 5433: Excessive optimization in IncrementalNewlineDecoder
         def _check(dec):
-            self.assertEquals(dec.newlines, None)
-            self.assertEquals(dec.decode("\u0D00"), "\u0D00")
-            self.assertEquals(dec.newlines, None)
-            self.assertEquals(dec.decode("\u0A00"), "\u0A00")
-            self.assertEquals(dec.newlines, None)
+            self.assertEqual(dec.newlines, None)
+            self.assertEqual(dec.decode("\u0D00"), "\u0D00")
+            self.assertEqual(dec.newlines, None)
+            self.assertEqual(dec.decode("\u0A00"), "\u0A00")
+            self.assertEqual(dec.newlines, None)
         dec = self.IncrementalNewlineDecoder(None, translate=False)
         _check(dec)
         dec = self.IncrementalNewlineDecoder(None, translate=True)
@@ -2409,28 +2426,28 @@
 
     def test_attributes(self):
         f = self.open(support.TESTFN, "wb", buffering=0)
-        self.assertEquals(f.mode, "wb")
+        self.assertEqual(f.mode, "wb")
         f.close()
 
         f = self.open(support.TESTFN, "U")
-        self.assertEquals(f.name,            support.TESTFN)
-        self.assertEquals(f.buffer.name,     support.TESTFN)
-        self.assertEquals(f.buffer.raw.name, support.TESTFN)
-        self.assertEquals(f.mode,            "U")
-        self.assertEquals(f.buffer.mode,     "rb")
-        self.assertEquals(f.buffer.raw.mode, "rb")
+        self.assertEqual(f.name,            support.TESTFN)
+        self.assertEqual(f.buffer.name,     support.TESTFN)
+        self.assertEqual(f.buffer.raw.name, support.TESTFN)
+        self.assertEqual(f.mode,            "U")
+        self.assertEqual(f.buffer.mode,     "rb")
+        self.assertEqual(f.buffer.raw.mode, "rb")
         f.close()
 
         f = self.open(support.TESTFN, "w+")
-        self.assertEquals(f.mode,            "w+")
-        self.assertEquals(f.buffer.mode,     "rb+") # Does it really matter?
-        self.assertEquals(f.buffer.raw.mode, "rb+")
+        self.assertEqual(f.mode,            "w+")
+        self.assertEqual(f.buffer.mode,     "rb+") # Does it really matter?
+        self.assertEqual(f.buffer.raw.mode, "rb+")
 
         g = self.open(f.fileno(), "wb", closefd=False)
-        self.assertEquals(g.mode,     "wb")
-        self.assertEquals(g.raw.mode, "wb")
-        self.assertEquals(g.name,     f.fileno())
-        self.assertEquals(g.raw.name, f.fileno())
+        self.assertEqual(g.mode,     "wb")
+        self.assertEqual(g.raw.mode, "wb")
+        self.assertEqual(g.name,     f.fileno())
+        self.assertEqual(g.raw.name, f.fileno())
         f.close()
         g.close()
 
@@ -2606,7 +2623,8 @@
     @unittest.skipUnless(threading, 'Threading required for this test.')
     def check_interrupted_write(self, item, bytes, **fdopen_kwargs):
         """Check that a partial write, when it gets interrupted, properly
-        invokes the signal handler."""
+        invokes the signal handler, and bubbles up the exception raised
+        in the latter."""
         read_results = []
         def _read():
             s = os.read(r, 1)
@@ -2653,12 +2671,143 @@
     def test_interrupted_write_text(self):
         self.check_interrupted_write("xy", b"xy", mode="w", encoding="ascii")
 
+    @support.no_tracing
+    def check_reentrant_write(self, data, **fdopen_kwargs):
+        def on_alarm(*args):
+            # Will be called reentrantly from the same thread
+            wio.write(data)
+            1/0
+        signal.signal(signal.SIGALRM, on_alarm)
+        r, w = os.pipe()
+        wio = self.io.open(w, **fdopen_kwargs)
+        try:
+            signal.alarm(1)
+            # Either the reentrant call to wio.write() fails with RuntimeError,
+            # or the signal handler raises ZeroDivisionError.
+            with self.assertRaises((ZeroDivisionError, RuntimeError)) as cm:
+                while 1:
+                    for i in range(100):
+                        wio.write(data)
+                        wio.flush()
+                    # Make sure the buffer doesn't fill up and block further writes
+                    os.read(r, len(data) * 100)
+            exc = cm.exception
+            if isinstance(exc, RuntimeError):
+                self.assertTrue(str(exc).startswith("reentrant call"), str(exc))
+        finally:
+            wio.close()
+            os.close(r)
+
+    def test_reentrant_write_buffered(self):
+        self.check_reentrant_write(b"xy", mode="wb")
+
+    def test_reentrant_write_text(self):
+        self.check_reentrant_write("xy", mode="w", encoding="ascii")
+
+    def check_interrupted_read_retry(self, decode, **fdopen_kwargs):
+        """Check that a buffered read, when it gets interrupted (either
+        returning a partial result or EINTR), properly invokes the signal
+        handler and retries if the latter returned successfully."""
+        r, w = os.pipe()
+        fdopen_kwargs["closefd"] = False
+        def alarm_handler(sig, frame):
+            os.write(w, b"bar")
+        signal.signal(signal.SIGALRM, alarm_handler)
+        try:
+            rio = self.io.open(r, **fdopen_kwargs)
+            os.write(w, b"foo")
+            signal.alarm(1)
+            # Expected behaviour:
+            # - first raw read() returns partial b"foo"
+            # - second raw read() returns EINTR
+            # - third raw read() returns b"bar"
+            self.assertEqual(decode(rio.read(6)), "foobar")
+        finally:
+            rio.close()
+            os.close(w)
+            os.close(r)
+
+    def test_interrupterd_read_retry_buffered(self):
+        self.check_interrupted_read_retry(lambda x: x.decode('latin1'),
+                                          mode="rb")
+
+    def test_interrupterd_read_retry_text(self):
+        self.check_interrupted_read_retry(lambda x: x,
+                                          mode="r")
+
+    @unittest.skipUnless(threading, 'Threading required for this test.')
+    def check_interrupted_write_retry(self, item, **fdopen_kwargs):
+        """Check that a buffered write, when it gets interrupted (either
+        returning a partial result or EINTR), properly invokes the signal
+        handler and retries if the latter returned successfully."""
+        select = support.import_module("select")
+        # A quantity that exceeds the buffer size of an anonymous pipe's
+        # write end.
+        N = 1024 * 1024
+        r, w = os.pipe()
+        fdopen_kwargs["closefd"] = False
+        # We need a separate thread to read from the pipe and allow the
+        # write() to finish.  This thread is started after the SIGALRM is
+        # received (forcing a first EINTR in write()).
+        read_results = []
+        write_finished = False
+        def _read():
+            while not write_finished:
+                while r in select.select([r], [], [], 1.0)[0]:
+                    s = os.read(r, 1024)
+                    read_results.append(s)
+        t = threading.Thread(target=_read)
+        t.daemon = True
+        def alarm1(sig, frame):
+            signal.signal(signal.SIGALRM, alarm2)
+            signal.alarm(1)
+        def alarm2(sig, frame):
+            t.start()
+        signal.signal(signal.SIGALRM, alarm1)
+        try:
+            wio = self.io.open(w, **fdopen_kwargs)
+            signal.alarm(1)
+            # Expected behaviour:
+            # - first raw write() is partial (because of the limited pipe buffer
+            #   and the first alarm)
+            # - second raw write() returns EINTR (because of the second alarm)
+            # - subsequent write()s are successful (either partial or complete)
+            self.assertEqual(N, wio.write(item * N))
+            wio.flush()
+            write_finished = True
+            t.join()
+            self.assertEqual(N, sum(len(x) for x in read_results))
+        finally:
+            write_finished = True
+            os.close(w)
+            os.close(r)
+            # This is deliberate. If we didn't close the file descriptor
+            # before closing wio, wio would try to flush its internal
+            # buffer, and could block (in case of failure).
+            try:
+                wio.close()
+            except IOError as e:
+                if e.errno != errno.EBADF:
+                    raise
+
+    def test_interrupterd_write_retry_buffered(self):
+        self.check_interrupted_write_retry(b"x", mode="wb")
+
+    def test_interrupterd_write_retry_text(self):
+        self.check_interrupted_write_retry("x", mode="w", encoding="latin1")
+
+
 class CSignalsTest(SignalsTest):
     io = io
 
 class PySignalsTest(SignalsTest):
     io = pyio
 
+    # Handling reentrancy issues would slow down _pyio even more, so the
+    # tests are disabled.
+    test_reentrant_write_buffered = None
+    test_reentrant_write_text = None
+
 
 def test_main():
     tests = (CIOTest, PyIOTest,

Modified: python/branches/pep-3151/Lib/test/test_ioctl.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_ioctl.py	(original)
+++ python/branches/pep-3151/Lib/test/test_ioctl.py	Sat Feb 26 08:16:32 2011
@@ -50,7 +50,7 @@
         with open("/dev/tty", "r") as tty:
             r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1)
         rpgrp = buf[0]
-        self.assertEquals(r, 0)
+        self.assertEqual(r, 0)
         self.assertIn(rpgrp, ids)
 
     def test_ioctl_mutate(self):

Modified: python/branches/pep-3151/Lib/test/test_isinstance.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_isinstance.py	(original)
+++ python/branches/pep-3151/Lib/test/test_isinstance.py	Sat Feb 26 08:16:32 2011
@@ -81,6 +81,20 @@
 
         self.assertRaises(TypeError, isinstance, I(), C())
 
+    # check that we don't mask non AttributeErrors
+    # see: http://bugs.python.org/issue1574217
+    def test_isinstance_dont_mask_non_attribute_error(self):
+        class C(object):
+            def getclass(self):
+                raise RuntimeError
+            __class__ = property(getclass)
+
+        c = C()
+        self.assertRaises(RuntimeError, isinstance, c, bool)
+
+        # test another code path
+        class D: pass
+        self.assertRaises(RuntimeError, isinstance, c, D)
 
 
 # These tests are similar to above, but tickle certain code paths in

Modified: python/branches/pep-3151/Lib/test/test_itertools.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_itertools.py	(original)
+++ python/branches/pep-3151/Lib/test/test_itertools.py	Sat Feb 26 08:16:32 2011
@@ -56,6 +56,24 @@
     return prod(range(1, n+1))
 
 class TestBasicOps(unittest.TestCase):
+
+    def test_accumulate(self):
+        self.assertEqual(list(accumulate(range(10))),               # one positional arg
+                          [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
+        self.assertEqual(list(accumulate(iterable=range(10))),      # kw arg
+                          [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])
+        for typ in int, complex, Decimal, Fraction:                 # multiple types
+            self.assertEqual(
+                list(accumulate(map(typ, range(10)))),
+                list(map(typ, [0, 1, 3, 6, 10, 15, 21, 28, 36, 45])))
+        self.assertEqual(list(accumulate('abc')), ['a', 'ab', 'abc'])   # works with non-numeric
+        self.assertEqual(list(accumulate([])), [])                  # empty iterable
+        self.assertEqual(list(accumulate([7])), [7])                # iterable of length one
+        self.assertRaises(TypeError, accumulate, range(10), 5)      # too many args
+        self.assertRaises(TypeError, accumulate)                    # too few args
+        self.assertRaises(TypeError, accumulate, x=range(10))       # unexpected kwd arg
+        self.assertRaises(TypeError, list, accumulate([1, []]))     # args that don't add
+
     def test_chain(self):
 
         def chain2(*iterables):
@@ -195,7 +213,7 @@
 
                 regular_combs = list(combinations(values, r))           # compare to combs without replacement
                 if n == 0 or r <= 1:
-                    self.assertEquals(result, regular_combs)            # cases that should be identical
+                    self.assertEqual(result, regular_combs)            # cases that should be identical
                 else:
                     self.assertTrue(set(result) >= set(regular_combs))     # rest should be supersets of regular combs
 
@@ -291,20 +309,20 @@
                 comb = list(combinations(s, r))
 
                 # Check size
-                self.assertEquals(len(prod), n**r)
-                self.assertEquals(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r))
-                self.assertEquals(len(perm), 0 if r>n else fact(n) / fact(n-r))
-                self.assertEquals(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r))
+                self.assertEqual(len(prod), n**r)
+                self.assertEqual(len(cwr), (fact(n+r-1) / fact(r)/ fact(n-1)) if n else (not r))
+                self.assertEqual(len(perm), 0 if r>n else fact(n) / fact(n-r))
+                self.assertEqual(len(comb), 0 if r>n else fact(n) / fact(r) / fact(n-r))
 
                 # Check lexicographic order without repeated tuples
-                self.assertEquals(prod, sorted(set(prod)))
-                self.assertEquals(cwr, sorted(set(cwr)))
-                self.assertEquals(perm, sorted(set(perm)))
-                self.assertEquals(comb, sorted(set(comb)))
+                self.assertEqual(prod, sorted(set(prod)))
+                self.assertEqual(cwr, sorted(set(cwr)))
+                self.assertEqual(perm, sorted(set(perm)))
+                self.assertEqual(comb, sorted(set(comb)))
 
                 # Check interrelationships
-                self.assertEquals(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted
-                self.assertEquals(perm, [t for t in prod if len(set(t))==r])    # perm: prods with no dups
+                self.assertEqual(cwr, [t for t in prod if sorted(t)==list(t)]) # cwr: prods which are sorted
+                self.assertEqual(perm, [t for t in prod if len(set(t))==r])    # perm: prods with no dups
                 self.assertEqual(comb, [t for t in perm if sorted(t)==list(t)]) # comb: perms that are sorted
                 self.assertEqual(comb, [t for t in cwr if len(set(t))==r])      # comb: cwrs without dups
                 self.assertEqual(comb, list(filter(set(cwr).__contains__, perm)))     # comb: perm that is a cwr
@@ -788,6 +806,11 @@
         self.assertRaises(ValueError, islice, range(10), 1, 'a', 1)
         self.assertEqual(len(list(islice(count(), 1, 10, maxsize))), 1)
 
+        # Issue #10323:  Less islice in a predictable state
+        c = count()
+        self.assertEqual(list(islice(c, 1, 3, 50)), [1])
+        self.assertEqual(next(c), 3)
+
     def test_takewhile(self):
         data = [1, 3, 5, 20, 2, 4, 6, 8]
         underten = lambda x: x<10
@@ -927,6 +950,9 @@
 
 class TestExamples(unittest.TestCase):
 
+    def test_accumlate(self):
+        self.assertEqual(list(accumulate([1,2,3,4,5])), [1, 3, 6, 10, 15])
+
     def test_chain(self):
         self.assertEqual(''.join(chain('ABC', 'DEF')), 'ABCDEF')
 
@@ -1014,6 +1040,10 @@
         next(iterator)
         del container, iterator
 
+    def test_accumulate(self):
+        a = []
+        self.makecycle(accumulate([1,2,a,3]), a)
+
     def test_chain(self):
         a = []
         self.makecycle(chain(a), a)
@@ -1183,6 +1213,17 @@
 
 class TestVariousIteratorArgs(unittest.TestCase):
 
+    def test_accumulate(self):
+        s = [1,2,3,4,5]
+        r = [1,3,6,10,15]
+        n = len(s)
+        for g in (G, I, Ig, L, R):
+            self.assertEqual(list(accumulate(g(s))), r)
+        self.assertEqual(list(accumulate(S(s))), [])
+        self.assertRaises(TypeError, accumulate, X(s))
+        self.assertRaises(TypeError, accumulate, N(s))
+        self.assertRaises(ZeroDivisionError, list, accumulate(E(s)))
+
     def test_chain(self):
         for s in ("123", "", range(1000), ('do', 1.2), range(2000,2200,5)):
             for g in (G, I, Ig, S, L, R):

Modified: python/branches/pep-3151/Lib/test/test_json.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_json.py	(original)
+++ python/branches/pep-3151/Lib/test/test_json.py	Sat Feb 26 08:16:32 2011
@@ -5,12 +5,12 @@
 be run.
 """
 
-import json.tests
+from test import json_tests
 import test.support
 
 
 def test_main():
-    test.support.run_unittest(json.tests.test_suite())
+    test.support.run_unittest(json_tests.test_suite())
 
 
 if __name__ == "__main__":

Modified: python/branches/pep-3151/Lib/test/test_keywordonlyarg.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_keywordonlyarg.py	(original)
+++ python/branches/pep-3151/Lib/test/test_keywordonlyarg.py	Sat Feb 26 08:16:32 2011
@@ -101,51 +101,51 @@
             pass
 
     def testFunctionCall(self):
-        self.assertEquals(1, posonly_sum(1))
-        self.assertEquals(1+2, posonly_sum(1,**{"2":2}))
-        self.assertEquals(1+2+3, posonly_sum(1,*(2,3)))
-        self.assertEquals(1+2+3+4, posonly_sum(1,*(2,3),**{"4":4}))
-
-        self.assertEquals(1, keywordonly_sum(k2=1))
-        self.assertEquals(1+2, keywordonly_sum(k1=1, k2=2))
-
-        self.assertEquals(1+2, keywordonly_and_kwarg_sum(k1=1, k2=2))
-        self.assertEquals(1+2+3, keywordonly_and_kwarg_sum(k1=1, k2=2, k3=3))
-        self.assertEquals(1+2+3+4,
-                          keywordonly_and_kwarg_sum(k1=1, k2=2,
+        self.assertEqual(1, posonly_sum(1))
+        self.assertEqual(1+2, posonly_sum(1,**{"2":2}))
+        self.assertEqual(1+2+3, posonly_sum(1,*(2,3)))
+        self.assertEqual(1+2+3+4, posonly_sum(1,*(2,3),**{"4":4}))
+
+        self.assertEqual(1, keywordonly_sum(k2=1))
+        self.assertEqual(1+2, keywordonly_sum(k1=1, k2=2))
+
+        self.assertEqual(1+2, keywordonly_and_kwarg_sum(k1=1, k2=2))
+        self.assertEqual(1+2+3, keywordonly_and_kwarg_sum(k1=1, k2=2, k3=3))
+        self.assertEqual(1+2+3+4,
+                         keywordonly_and_kwarg_sum(k1=1, k2=2,
                                                     **{"a":3,"b":4}))
 
-        self.assertEquals(1+2, mixedargs_sum(1, k1=2))
-        self.assertEquals(1+2+3, mixedargs_sum(1, 2, k1=3))
-        self.assertEquals(1+2+3+4, mixedargs_sum(1, 2, k1=3, k2=4))
-        self.assertEquals(1+2+3+4+5, mixedargs_sum(1, 2, 3, k1=4, k2=5))
-
-        self.assertEquals(1+2, mixedargs_sum2(1, k1=2))
-        self.assertEquals(1+2+3, mixedargs_sum2(1, 2, k1=3))
-        self.assertEquals(1+2+3+4, mixedargs_sum2(1, 2, k1=3, k2=4))
-        self.assertEquals(1+2+3+4+5, mixedargs_sum2(1, 2, 3, k1=4, k2=5))
-        self.assertEquals(1+2+3+4+5+6,
-                          mixedargs_sum2(1, 2, 3, k1=4, k2=5, k3=6))
-        self.assertEquals(1+2+3+4+5+6,
-                          mixedargs_sum2(1, 2, 3, k1=4, **{'k2':5, 'k3':6}))
-
-        self.assertEquals(1, Foo(k1=1).sum())
-        self.assertEquals(1+2, Foo(k1=1,k2=2).sum())
-
-        self.assertEquals([1,2,3], sortnum(3,2,1))
-        self.assertEquals([3,2,1], sortnum(1,2,3, reverse=True))
-
-        self.assertEquals(['a','b','c'], sortwords('a','c','b'))
-        self.assertEquals(['c','b','a'], sortwords('a','c','b', reverse=True))
-        self.assertEquals(['c','b','a'],
-                          sortwords('a','c','b', reverse=True, ignore='ignore'))
+        self.assertEqual(1+2, mixedargs_sum(1, k1=2))
+        self.assertEqual(1+2+3, mixedargs_sum(1, 2, k1=3))
+        self.assertEqual(1+2+3+4, mixedargs_sum(1, 2, k1=3, k2=4))
+        self.assertEqual(1+2+3+4+5, mixedargs_sum(1, 2, 3, k1=4, k2=5))
+
+        self.assertEqual(1+2, mixedargs_sum2(1, k1=2))
+        self.assertEqual(1+2+3, mixedargs_sum2(1, 2, k1=3))
+        self.assertEqual(1+2+3+4, mixedargs_sum2(1, 2, k1=3, k2=4))
+        self.assertEqual(1+2+3+4+5, mixedargs_sum2(1, 2, 3, k1=4, k2=5))
+        self.assertEqual(1+2+3+4+5+6,
+                         mixedargs_sum2(1, 2, 3, k1=4, k2=5, k3=6))
+        self.assertEqual(1+2+3+4+5+6,
+                         mixedargs_sum2(1, 2, 3, k1=4, **{'k2':5, 'k3':6}))
+
+        self.assertEqual(1, Foo(k1=1).sum())
+        self.assertEqual(1+2, Foo(k1=1,k2=2).sum())
+
+        self.assertEqual([1,2,3], sortnum(3,2,1))
+        self.assertEqual([3,2,1], sortnum(1,2,3, reverse=True))
+
+        self.assertEqual(['a','b','c'], sortwords('a','c','b'))
+        self.assertEqual(['c','b','a'], sortwords('a','c','b', reverse=True))
+        self.assertEqual(['c','b','a'],
+                         sortwords('a','c','b', reverse=True, ignore='ignore'))
 
     def testKwDefaults(self):
         def foo(p1,p2=0, *, k1, k2=0):
             return p1 + p2 + k1 + k2
 
-        self.assertEquals(2, foo.__code__.co_kwonlyargcount)
-        self.assertEquals({"k2":0}, foo.__kwdefaults__)
+        self.assertEqual(2, foo.__code__.co_kwonlyargcount)
+        self.assertEqual({"k2":0}, foo.__kwdefaults__)
         foo.__kwdefaults__ = {"k1":0}
         try:
             foo(1,k1=10)

Modified: python/branches/pep-3151/Lib/test/test_kqueue.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_kqueue.py	(original)
+++ python/branches/pep-3151/Lib/test/test_kqueue.py	Sat Feb 26 08:16:32 2011
@@ -91,7 +91,7 @@
         try:
             client.connect(('127.0.0.1', serverSocket.getsockname()[1]))
         except socket.error as e:
-            self.assertEquals(e.args[0], errno.EINPROGRESS)
+            self.assertEqual(e.args[0], errno.EINPROGRESS)
         else:
             #raise AssertionError("Connect should have raised EINPROGRESS")
             pass # FreeBSD doesn't raise an exception here
@@ -125,7 +125,7 @@
         events = kq.control(None, 4, 1)
         events = [(e.ident, e.filter, e.flags) for e in events]
         events.sort()
-        self.assertEquals(events, [
+        self.assertEqual(events, [
             (client.fileno(), select.KQ_FILTER_WRITE, flags),
             (server.fileno(), select.KQ_FILTER_WRITE, flags)])
 
@@ -144,7 +144,7 @@
         events = [(e.ident, e.filter, e.flags) for e in events]
         events.sort()
 
-        self.assertEquals(events, [
+        self.assertEqual(events, [
             (client.fileno(), select.KQ_FILTER_WRITE, flags),
             (client.fileno(), select.KQ_FILTER_READ, flags),
             (server.fileno(), select.KQ_FILTER_WRITE, flags),
@@ -167,7 +167,7 @@
         events = kq.control([], 4, 0.99)
         events = [(e.ident, e.filter, e.flags) for e in events]
         events.sort()
-        self.assertEquals(events, [
+        self.assertEqual(events, [
             (server.fileno(), select.KQ_FILTER_WRITE, flags)])
 
         client.close()
@@ -184,7 +184,7 @@
         r = kq.control([event1, event2], 1, 1)
         self.assertTrue(r)
         self.assertFalse(r[0].flags & select.KQ_EV_ERROR)
-        self.assertEquals(b.recv(r[0].data), b'foo')
+        self.assertEqual(b.recv(r[0].data), b'foo')
 
         a.close()
         b.close()

Modified: python/branches/pep-3151/Lib/test/test_linecache.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_linecache.py	(original)
+++ python/branches/pep-3151/Lib/test/test_linecache.py	Sat Feb 26 08:16:32 2011
@@ -42,33 +42,33 @@
         getline = linecache.getline
 
         # Bad values for line number should return an empty string
-        self.assertEquals(getline(FILENAME, 2**15), EMPTY)
-        self.assertEquals(getline(FILENAME, -1), EMPTY)
+        self.assertEqual(getline(FILENAME, 2**15), EMPTY)
+        self.assertEqual(getline(FILENAME, -1), EMPTY)
 
         # Float values currently raise TypeError, should it?
         self.assertRaises(TypeError, getline, FILENAME, 1.1)
 
         # Bad filenames should return an empty string
-        self.assertEquals(getline(EMPTY, 1), EMPTY)
-        self.assertEquals(getline(INVALID_NAME, 1), EMPTY)
+        self.assertEqual(getline(EMPTY, 1), EMPTY)
+        self.assertEqual(getline(INVALID_NAME, 1), EMPTY)
 
         # Check whether lines correspond to those from file iteration
         for entry in TESTS:
             filename = os.path.join(TEST_PATH, entry) + '.py'
             with open(filename) as file:
                 for index, line in enumerate(file):
-                    self.assertEquals(line, getline(filename, index + 1))
+                    self.assertEqual(line, getline(filename, index + 1))
 
         # Check module loading
         for entry in MODULES:
             filename = os.path.join(MODULE_PATH, entry) + '.py'
             with open(filename) as file:
                 for index, line in enumerate(file):
-                    self.assertEquals(line, getline(filename, index + 1))
+                    self.assertEqual(line, getline(filename, index + 1))
 
         # Check that bogus data isn't returned (issue #1309567)
         empty = linecache.getlines('a/b/c/__init__.py')
-        self.assertEquals(empty, [])
+        self.assertEqual(empty, [])
 
     def test_no_ending_newline(self):
         self.addCleanup(support.unlink, support.TESTFN)
@@ -86,12 +86,12 @@
 
         # Are all files cached?
         cached_empty = [fn for fn in cached if fn not in linecache.cache]
-        self.assertEquals(cached_empty, [])
+        self.assertEqual(cached_empty, [])
 
         # Can we clear the cache?
         linecache.clearcache()
         cached_empty = [fn for fn in cached if fn in linecache.cache]
-        self.assertEquals(cached_empty, [])
+        self.assertEqual(cached_empty, [])
 
     def test_checkcache(self):
         getline = linecache.getline
@@ -106,7 +106,7 @@
         source_list = []
         with open(source_name) as source:
             for index, line in enumerate(source):
-                self.assertEquals(line, getline(source_name, index + 1))
+                self.assertEqual(line, getline(source_name, index + 1))
                 source_list.append(line)
 
         with open(source_name, 'w') as source:
@@ -117,13 +117,13 @@
 
         # Check that the cache matches the old contents
         for index, line in enumerate(source_list):
-            self.assertEquals(line, getline(source_name, index + 1))
+            self.assertEqual(line, getline(source_name, index + 1))
 
         # Update the cache and check whether it matches the new source file
         linecache.checkcache(source_name)
         with open(source_name) as source:
             for index, line in enumerate(source):
-                self.assertEquals(line, getline(source_name, index + 1))
+                self.assertEqual(line, getline(source_name, index + 1))
                 source_list.append(line)
 
 def test_main():

Modified: python/branches/pep-3151/Lib/test/test_listcomps.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_listcomps.py	(original)
+++ python/branches/pep-3151/Lib/test/test_listcomps.py	Sat Feb 26 08:16:32 2011
@@ -146,299 +146,3 @@
 
 if __name__ == "__main__":
     test_main(verbose=True)
-doctests = """
-########### Tests borrowed from or inspired by test_genexps.py ############
-
-Test simple loop with conditional
-
-    >>> sum([i*i for i in range(100) if i&1 == 1])
-    166650
-
-Test simple nesting
-
-    >>> [(i,j) for i in range(3) for j in range(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)]
-
-Test nesting with the inner expression dependent on the outer
-
-    >>> [(i,j) for i in range(4) for j in range(i)]
-    [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]
-
-Make sure the induction variable is not exposed
-
-    >>> i = 20
-    >>> sum([i*i for i in range(100)])
-    328350
-
-    >>> i
-    20
-
-Verify that syntax error's are raised for listcomps used as lvalues
-
-    >>> [y for y in (1,2)] = 10          # doctest: +IGNORE_EXCEPTION_DETAIL
-    Traceback (most recent call last):
-       ...
-    SyntaxError: ...
-
-    >>> [y for y in (1,2)] += 10         # doctest: +IGNORE_EXCEPTION_DETAIL
-    Traceback (most recent call last):
-       ...
-    SyntaxError: ...
-
-
-########### Tests borrowed from or inspired by test_generators.py ############
-
-Make a nested list comprehension that acts like range()
-
-    >>> def frange(n):
-    ...     return [i for i in range(n)]
-    >>> frange(10)
-    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-
-Same again, only as a lambda expression instead of a function definition
-
-    >>> lrange = lambda n:  [i for i in range(n)]
-    >>> lrange(10)
-    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-
-Generators can call other generators:
-
-    >>> def grange(n):
-    ...     for x in [i for i in range(n)]:
-    ...         yield x
-    >>> list(grange(5))
-    [0, 1, 2, 3, 4]
-
-
-Make sure that None is a valid return value
-
-    >>> [None for i in range(10)]
-    [None, None, None, None, None, None, None, None, None, None]
-
-########### Tests for various scoping corner cases ############
-
-Return lambdas that use the iteration variable as a default argument
-
-    >>> items = [(lambda i=i: i) for i in range(5)]
-    >>> [x() for x in items]
-    [0, 1, 2, 3, 4]
-
-Same again, only this time as a closure variable
-
-    >>> items = [(lambda: i) for i in range(5)]
-    >>> [x() for x in items]
-    [4, 4, 4, 4, 4]
-
-Another way to test that the iteration variable is local to the list comp
-
-    >>> items = [(lambda: i) for i in range(5)]
-    >>> i = 20
-    >>> [x() for x in items]
-    [4, 4, 4, 4, 4]
-
-And confirm that a closure can jump over the list comp scope
-
-    >>> items = [(lambda: y) for i in range(5)]
-    >>> y = 2
-    >>> [x() for x in items]
-    [2, 2, 2, 2, 2]
-
-We also repeat each of the above scoping tests inside a function
-
-    >>> def test_func():
-    ...     items = [(lambda i=i: i) for i in range(5)]
-    ...     return [x() for x in items]
-    >>> test_func()
-    [0, 1, 2, 3, 4]
-
-    >>> def test_func():
-    ...     items = [(lambda: i) for i in range(5)]
-    ...     return [x() for x in items]
-    >>> test_func()
-    [4, 4, 4, 4, 4]
-
-    >>> def test_func():
-    ...     items = [(lambda: i) for i in range(5)]
-    ...     i = 20
-    ...     return [x() for x in items]
-    >>> test_func()
-    [4, 4, 4, 4, 4]
-
-    >>> def test_func():
-    ...     items = [(lambda: y) for i in range(5)]
-    ...     y = 2
-    ...     return [x() for x in items]
-    >>> test_func()
-    [2, 2, 2, 2, 2]
-
-"""
-
-
-__test__ = {'doctests' : doctests}
-
-def test_main(verbose=None):
-    import sys
-    from test import support
-    from test import test_listcomps
-    support.run_doctest(test_listcomps, verbose)
-
-    # verify reference counting
-    if verbose and hasattr(sys, "gettotalrefcount"):
-        import gc
-        counts = [None] * 5
-        for i in range(len(counts)):
-            support.run_doctest(test_genexps, verbose)
-            gc.collect()
-            counts[i] = sys.gettotalrefcount()
-        print(counts)
-
-if __name__ == "__main__":
-    test_main(verbose=True)
-doctests = """
-########### Tests borrowed from or inspired by test_genexps.py ############
-
-Test simple loop with conditional
-
-    >>> sum([i*i for i in range(100) if i&1 == 1])
-    166650
-
-Test simple nesting
-
-    >>> [(i,j) for i in range(3) for j in range(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)]
-
-Test nesting with the inner expression dependent on the outer
-
-    >>> [(i,j) for i in range(4) for j in range(i)]
-    [(1, 0), (2, 0), (2, 1), (3, 0), (3, 1), (3, 2)]
-
-Make sure the induction variable is not exposed
-
-    >>> i = 20
-    >>> sum([i*i for i in range(100)])
-    328350
-
-    >>> i
-    20
-
-Verify that syntax error's are raised for listcomps used as lvalues
-
-    >>> [y for y in (1,2)] = 10          # doctest: +IGNORE_EXCEPTION_DETAIL
-    Traceback (most recent call last):
-       ...
-    SyntaxError: ...
-
-    >>> [y for y in (1,2)] += 10         # doctest: +IGNORE_EXCEPTION_DETAIL
-    Traceback (most recent call last):
-       ...
-    SyntaxError: ...
-
-
-########### Tests borrowed from or inspired by test_generators.py ############
-
-Make a nested list comprehension that acts like range()
-
-    >>> def frange(n):
-    ...     return [i for i in range(n)]
-    >>> frange(10)
-    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-
-Same again, only as a lambda expression instead of a function definition
-
-    >>> lrange = lambda n:  [i for i in range(n)]
-    >>> lrange(10)
-    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
-
-Generators can call other generators:
-
-    >>> def grange(n):
-    ...     for x in [i for i in range(n)]:
-    ...         yield x
-    >>> list(grange(5))
-    [0, 1, 2, 3, 4]
-
-
-Make sure that None is a valid return value
-
-    >>> [None for i in range(10)]
-    [None, None, None, None, None, None, None, None, None, None]
-
-########### Tests for various scoping corner cases ############
-
-Return lambdas that use the iteration variable as a default argument
-
-    >>> items = [(lambda i=i: i) for i in range(5)]
-    >>> [x() for x in items]
-    [0, 1, 2, 3, 4]
-
-Same again, only this time as a closure variable
-
-    >>> items = [(lambda: i) for i in range(5)]
-    >>> [x() for x in items]
-    [4, 4, 4, 4, 4]
-
-Another way to test that the iteration variable is local to the list comp
-
-    >>> items = [(lambda: i) for i in range(5)]
-    >>> i = 20
-    >>> [x() for x in items]
-    [4, 4, 4, 4, 4]
-
-And confirm that a closure can jump over the list comp scope
-
-    >>> items = [(lambda: y) for i in range(5)]
-    >>> y = 2
-    >>> [x() for x in items]
-    [2, 2, 2, 2, 2]
-
-We also repeat each of the above scoping tests inside a function
-
-    >>> def test_func():
-    ...     items = [(lambda i=i: i) for i in range(5)]
-    ...     return [x() for x in items]
-    >>> test_func()
-    [0, 1, 2, 3, 4]
-
-    >>> def test_func():
-    ...     items = [(lambda: i) for i in range(5)]
-    ...     return [x() for x in items]
-    >>> test_func()
-    [4, 4, 4, 4, 4]
-
-    >>> def test_func():
-    ...     items = [(lambda: i) for i in range(5)]
-    ...     i = 20
-    ...     return [x() for x in items]
-    >>> test_func()
-    [4, 4, 4, 4, 4]
-
-    >>> def test_func():
-    ...     items = [(lambda: y) for i in range(5)]
-    ...     y = 2
-    ...     return [x() for x in items]
-    >>> test_func()
-    [2, 2, 2, 2, 2]
-
-"""
-
-
-__test__ = {'doctests' : doctests}
-
-def test_main(verbose=None):
-    import sys
-    from test import support
-    from test import test_listcomps
-    support.run_doctest(test_listcomps, verbose)
-
-    # verify reference counting
-    if verbose and hasattr(sys, "gettotalrefcount"):
-        import gc
-        counts = [None] * 5
-        for i in range(len(counts)):
-            support.run_doctest(test_listcomps, verbose)
-            gc.collect()
-            counts[i] = sys.gettotalrefcount()
-        print(counts)
-
-if __name__ == "__main__":
-    test_main(verbose=True)

Modified: python/branches/pep-3151/Lib/test/test_logging.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_logging.py	(original)
+++ python/branches/pep-3151/Lib/test/test_logging.py	Sat Feb 26 08:16:32 2011
@@ -67,8 +67,12 @@
         try:
             self.saved_handlers = logging._handlers.copy()
             self.saved_handler_list = logging._handlerList[:]
-            self.saved_loggers = logger_dict.copy()
+            self.saved_loggers = saved_loggers = logger_dict.copy()
             self.saved_level_names = logging._levelNames.copy()
+            self.logger_states = logger_states = {}
+            for name in saved_loggers:
+                logger_states[name] = getattr(saved_loggers[name],
+                                              'disabled', None)
         finally:
             logging._releaseLock()
 
@@ -86,8 +90,12 @@
         self.root_hdlr = logging.StreamHandler(self.stream)
         self.root_formatter = logging.Formatter(self.log_format)
         self.root_hdlr.setFormatter(self.root_formatter)
-        self.assertFalse(self.logger1.hasHandlers())
-        self.assertFalse(self.logger2.hasHandlers())
+        if self.logger1.hasHandlers():
+            hlist = self.logger1.handlers + self.root_logger.handlers
+            raise AssertionError('Unexpected handlers: %s' % hlist)
+        if self.logger2.hasHandlers():
+            hlist = self.logger2.handlers + self.root_logger.handlers
+            raise AssertionError('Unexpected handlers: %s' % hlist)
         self.root_logger.addHandler(self.root_hdlr)
         self.assertTrue(self.logger1.hasHandlers())
         self.assertTrue(self.logger2.hasHandlers())
@@ -112,6 +120,10 @@
             loggerDict = logging.getLogger().manager.loggerDict
             loggerDict.clear()
             loggerDict.update(self.saved_loggers)
+            logger_states = self.logger_states
+            for name in self.logger_states:
+                if logger_states[name] is not None:
+                    self.saved_loggers[name].disabled = logger_states[name]
         finally:
             logging._releaseLock()
 
@@ -127,14 +139,14 @@
         except AttributeError:
             # StringIO.StringIO lacks a reset() method.
             actual_lines = stream.getvalue().splitlines()
-        self.assertEquals(len(actual_lines), len(expected_values),
+        self.assertEqual(len(actual_lines), len(expected_values),
                           '%s vs. %s' % (actual_lines, expected_values))
         for actual, expected in zip(actual_lines, expected_values):
             match = pat.search(actual)
             if not match:
                 self.fail("Log line does not match expected pattern:\n" +
                             actual)
-            self.assertEquals(tuple(match.groups()), expected)
+            self.assertEqual(tuple(match.groups()), expected)
         s = stream.read()
         if s:
             self.fail("Remaining output at end of log stream:\n" + s)
@@ -729,7 +741,7 @@
             except RuntimeError:
                 logging.exception("just testing")
             sys.stdout.seek(0)
-            self.assertEquals(output.getvalue(),
+            self.assertEqual(output.getvalue(),
                 "ERROR:root:just testing\nGot a [RuntimeError]\n")
             # Original logger output is empty
             self.assert_log_lines([])
@@ -848,7 +860,7 @@
         logger = logging.getLogger("tcp")
         logger.error("spam")
         logger.debug("eggs")
-        self.assertEquals(self.get_output(), "spam\neggs\n")
+        self.assertEqual(self.get_output(), "spam\neggs\n")
 
 
 class MemoryTest(BaseTest):
@@ -907,7 +919,8 @@
     def test_encoding_plain_file(self):
         # In Python 2.x, a plain file object is treated as having no encoding.
         log = logging.getLogger("test")
-        fn = tempfile.mktemp(".log", "test_logging-1-")
+        fd, fn = tempfile.mkstemp(".log", "test_logging-1-")
+        os.close(fd)
         # the non-ascii data we write to the log.
         data = "foo\x80"
         try:
@@ -1564,7 +1577,7 @@
             except RuntimeError:
                 logging.exception("just testing")
             sys.stdout.seek(0)
-            self.assertEquals(output.getvalue(),
+            self.assertEqual(output.getvalue(),
                 "ERROR:root:just testing\nGot a [RuntimeError]\n")
             # Original logger output is empty
             self.assert_log_lines([])
@@ -1579,7 +1592,7 @@
             except RuntimeError:
                 logging.exception("just testing")
             sys.stdout.seek(0)
-            self.assertEquals(output.getvalue(),
+            self.assertEqual(output.getvalue(),
                 "ERROR:root:just testing\nGot a [RuntimeError]\n")
             # Original logger output is empty
             self.assert_log_lines([])
@@ -1799,7 +1812,7 @@
 class DerivedLogRecord(logging.LogRecord):
     pass
 
-class LogRecordClassTest(BaseTest):
+class LogRecordFactoryTest(BaseTest):
 
     def setUp(self):
         class CheckingFilter(logging.Filter):
@@ -1817,17 +1830,17 @@
         BaseTest.setUp(self)
         self.filter = CheckingFilter(DerivedLogRecord)
         self.root_logger.addFilter(self.filter)
-        self.orig_cls = logging.getLogRecordClass()
+        self.orig_factory = logging.getLogRecordFactory()
 
     def tearDown(self):
         self.root_logger.removeFilter(self.filter)
         BaseTest.tearDown(self)
-        logging.setLogRecordClass(self.orig_cls)
+        logging.setLogRecordFactory(self.orig_factory)
 
     def test_logrecord_class(self):
         self.assertRaises(TypeError, self.root_logger.warning,
                           self.next_message())
-        logging.setLogRecordClass(DerivedLogRecord)
+        logging.setLogRecordFactory(DerivedLogRecord)
         self.root_logger.error(self.next_message())
         self.assert_log_lines([
            ('root', 'ERROR', '2'),
@@ -1885,7 +1898,7 @@
         return logging.makeLogRecord(result)
 
     def test_percent(self):
-        "Test %-formatting"
+        # Test %-formatting
         r = self.get_record()
         f = logging.Formatter('${%(message)s}')
         self.assertEqual(f.format(r), '${Message with 2 placeholders}')
@@ -1898,7 +1911,7 @@
         self.assertFalse(f.usesTime())
 
     def test_braces(self):
-        "Test {}-formatting"
+        # Test {}-formatting
         r = self.get_record()
         f = logging.Formatter('$%{message}%$', style='{')
         self.assertEqual(f.format(r), '$%Message with 2 placeholders%$')
@@ -1911,7 +1924,7 @@
         self.assertFalse(f.usesTime())
 
     def test_dollars(self):
-        "Test $-formatting"
+        # Test $-formatting
         r = self.get_record()
         f = logging.Formatter('$message', style='$')
         self.assertEqual(f.format(r), 'Message with 2 placeholders')
@@ -1927,17 +1940,54 @@
         f = logging.Formatter('asctime', style='$')
         self.assertFalse(f.usesTime())
 
+class LastResortTest(BaseTest):
+    def test_last_resort(self):
+        # Test the last resort handler
+        root = self.root_logger
+        root.removeHandler(self.root_hdlr)
+        old_stderr = sys.stderr
+        old_lastresort = logging.lastResort
+        old_raise_exceptions = logging.raiseExceptions
+        try:
+            sys.stderr = sio = io.StringIO()
+            root.warning('This is your final chance!')
+            self.assertEqual(sio.getvalue(), 'This is your final chance!\n')
+            #No handlers and no last resort, so 'No handlers' message
+            logging.lastResort = None
+            sys.stderr = sio = io.StringIO()
+            root.warning('This is your final chance!')
+            self.assertEqual(sio.getvalue(), 'No handlers could be found for logger "root"\n')
+            # 'No handlers' message only printed once
+            sys.stderr = sio = io.StringIO()
+            root.warning('This is your final chance!')
+            self.assertEqual(sio.getvalue(), '')
+            root.manager.emittedNoHandlerWarning = False
+            #If raiseExceptions is False, no message is printed
+            logging.raiseExceptions = False
+            sys.stderr = sio = io.StringIO()
+            root.warning('This is your final chance!')
+            self.assertEqual(sio.getvalue(), '')
+        finally:
+            sys.stderr = old_stderr
+            root.addHandler(self.root_hdlr)
+            logging.lastResort = old_lastresort
+            logging.raiseExceptions = old_raise_exceptions
+
+
 class BaseFileTest(BaseTest):
     "Base class for handler tests that write log files"
 
     def setUp(self):
         BaseTest.setUp(self)
-        self.fn = tempfile.mktemp(".log", "test_logging-2-")
+        fd, self.fn = tempfile.mkstemp(".log", "test_logging-2-")
+        os.close(fd)
         self.rmfiles = []
 
     def tearDown(self):
         for fn in self.rmfiles:
             os.unlink(fn)
+        if os.path.exists(self.fn):
+            os.unlink(self.fn)
         BaseTest.tearDown(self)
 
     def assertLogFile(self, filename):
@@ -1966,7 +2016,6 @@
     def test_file_created(self):
         # checks that the file is created and assumes it was created
         # by us
-        self.assertFalse(os.path.exists(self.fn))
         rh = logging.handlers.RotatingFileHandler(self.fn)
         rh.emit(self.next_rec())
         self.assertLogFile(self.fn)
@@ -1997,11 +2046,41 @@
                   ('D', 60 * 60 * 24),
                   ('MIDNIGHT', 60 * 60 * 23),
                   # current time (epoch start) is a Thursday, W0 means Monday
-                  ('W0', secs(days=4, hours=23)),):
+                  ('W0', secs(days=4, hours=23)),
+                 ):
     def test_compute_rollover(self, when=when, exp=exp):
         rh = logging.handlers.TimedRotatingFileHandler(
             self.fn, when=when, interval=1, backupCount=0)
-        self.assertEquals(exp, rh.computeRollover(0.0))
+        currentTime = 0.0
+        actual = rh.computeRollover(currentTime)
+        if exp != actual:
+            # Failures occur on some systems for MIDNIGHT and W0.
+            # Print detailed calculation for MIDNIGHT so we can try to see
+            # what's going on
+            import time
+            if when == 'MIDNIGHT':
+                try:
+                    if rh.utc:
+                        t = time.gmtime(currentTime)
+                    else:
+                        t = time.localtime(currentTime)
+                    currentHour = t[3]
+                    currentMinute = t[4]
+                    currentSecond = t[5]
+                    # r is the number of seconds left between now and midnight
+                    r = logging.handlers._MIDNIGHT - ((currentHour * 60 +
+                                                       currentMinute) * 60 +
+                            currentSecond)
+                    result = currentTime + r
+                    print('t: %s (%s)' % (t, rh.utc), file=sys.stderr)
+                    print('currentHour: %s' % currentHour, file=sys.stderr)
+                    print('currentMinute: %s' % currentMinute, file=sys.stderr)
+                    print('currentSecond: %s' % currentSecond, file=sys.stderr)
+                    print('r: %s' % r, file=sys.stderr)
+                    print('result: %s' % result, file=sys.stderr)
+                except Exception:
+                    print('exception in diagnostic code: %s' % sys.exc_info()[1], file=sys.stderr)
+        self.assertEqual(exp, actual)
         rh.close()
     setattr(TimedRotatingFileHandlerTest, "test_compute_rollover_%s" % when, test_compute_rollover)
 
@@ -2015,9 +2094,10 @@
                  ConfigFileTest, SocketHandlerTest, MemoryTest,
                  EncodingTest, WarningsTest, ConfigDictTest, ManagerTest,
                  FormatterTest,
-                 LogRecordClassTest, ChildLoggerTest, QueueHandlerTest,
+                 LogRecordFactoryTest, ChildLoggerTest, QueueHandlerTest,
                  RotatingFileHandlerTest,
-                 #TimedRotatingFileHandlerTest
+                 LastResortTest,
+                 TimedRotatingFileHandlerTest
                 )
 
 if __name__ == "__main__":

Modified: python/branches/pep-3151/Lib/test/test_long.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_long.py	(original)
+++ python/branches/pep-3151/Lib/test/test_long.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,6 @@
 import unittest
 from test import support
+
 import sys
 
 import random
@@ -15,11 +16,6 @@
     def __str__(self):
         return self.format % self.args
 
-# decorator for skipping tests on non-IEEE 754 platforms
-requires_IEEE_754 = unittest.skipUnless(
-    float.__getformat__("double").startswith("IEEE"),
-    "test requires IEEE 754 doubles")
-
 # SHIFT should match the value in longintrepr.h for best testing.
 SHIFT = sys.int_info.bits_per_digit
 BASE = 2 ** SHIFT
@@ -276,7 +272,7 @@
         digits = digits or [0]
         return '-'[:sign] + \
                {2: '0b', 8: '0o', 10: '', 16: '0x'}[base] + \
-               "".join(map(lambda i: "0123456789abcdef"[i], digits))
+               "".join("0123456789abcdef"[i] for i in digits)
 
     def check_format_1(self, x):
         for base, mapper in (8, oct), (10, repr), (16, hex):
@@ -371,8 +367,7 @@
                 return 1729
         self.assertEqual(int(LongTrunc()), 1729)
 
-    @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
-                         "test requires IEEE 754 doubles")
+    @support.requires_IEEE_754
     def test_float_conversion(self):
 
         exact_values = [0, 1, 2,
@@ -703,7 +698,7 @@
         self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: "
                          "expected {}, got {}".format(a, b, expected, got))
 
-    @requires_IEEE_754
+    @support.requires_IEEE_754
     def test_correctly_rounded_true_division(self):
         # more stringent tests than those above, checking that the
         # result of true division of ints is always correctly rounded.

Modified: python/branches/pep-3151/Lib/test/test_mailbox.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_mailbox.py	(original)
+++ python/branches/pep-3151/Lib/test/test_mailbox.py	Sat Feb 26 08:16:32 2011
@@ -7,8 +7,10 @@
 import email.message
 import re
 import io
+import tempfile
 from test import support
 import unittest
+import textwrap
 import mailbox
 import glob
 try:
@@ -48,6 +50,8 @@
 
 class TestMailbox(TestBase):
 
+    maxDiff = None
+
     _factory = None     # Overridden by subclasses to reuse tests
     _template = 'From: foo\n\n%s'
 
@@ -69,14 +73,124 @@
         self.assertEqual(len(self._box), 2)
         keys.append(self._box.add(email.message_from_string(_sample_message)))
         self.assertEqual(len(self._box), 3)
-        keys.append(self._box.add(io.StringIO(_sample_message)))
+        keys.append(self._box.add(io.BytesIO(_bytes_sample_message)))
         self.assertEqual(len(self._box), 4)
         keys.append(self._box.add(_sample_message))
         self.assertEqual(len(self._box), 5)
+        keys.append(self._box.add(_bytes_sample_message))
+        self.assertEqual(len(self._box), 6)
+        with self.assertWarns(DeprecationWarning):
+            keys.append(self._box.add(
+                io.TextIOWrapper(io.BytesIO(_bytes_sample_message))))
+        self.assertEqual(len(self._box), 7)
         self.assertEqual(self._box.get_string(keys[0]), self._template % 0)
-        for i in (1, 2, 3, 4):
+        for i in (1, 2, 3, 4, 5, 6):
             self._check_sample(self._box[keys[i]])
 
+    _nonascii_msg = textwrap.dedent("""\
+            From: foo
+            Subject: Falinaptár házhozszállítással. Már rendeltél?
+
+            0
+            """)
+
+    def test_add_invalid_8bit_bytes_header(self):
+        key = self._box.add(self._nonascii_msg.encode('latin-1'))
+        self.assertEqual(len(self._box), 1)
+        self.assertEqual(self._box.get_bytes(key),
+            self._nonascii_msg.encode('latin-1'))
+
+    def test_invalid_nonascii_header_as_string(self):
+        subj = self._nonascii_msg.splitlines()[1]
+        key = self._box.add(subj.encode('latin-1'))
+        self.assertEqual(self._box.get_string(key),
+            'Subject: =?unknown-8bit?b?RmFsaW5hcHThciBo4Xpob3pzeuFsbO104XNz'
+            'YWwuIE3hciByZW5kZWx06Ww/?=\n\n')
+
+    def test_add_nonascii_string_header_raises(self):
+        with self.assertRaisesRegex(ValueError, "ASCII-only"):
+            self._box.add(self._nonascii_msg)
+        self._box.flush()
+        self.assertEqual(len(self._box), 0)
+        self.assertMailboxEmpty()
+
+    def test_add_that_raises_leaves_mailbox_empty(self):
+        # XXX This test will start failing when Message learns to handle
+        # non-ASCII string headers, and a different internal failure will
+        # need to be found or manufactured.
+        with self.assertRaises(ValueError):
+            self._box.add(email.message_from_string("From: Alphöso"))
+        self.assertEqual(len(self._box), 0)
+        self._box.close()
+        self.assertMailboxEmpty()
+
+    _non_latin_bin_msg = textwrap.dedent("""\
+        From: foo at bar.com
+        To: báz
+        Subject: Maintenant je vous présente mon collègue, le pouf célèbre
+        \tJean de Baddie
+        Mime-Version: 1.0
+        Content-Type: text/plain; charset="utf-8"
+        Content-Transfer-Encoding: 8bit
+
+        Да, они летят.
+        """).encode('utf-8')
+
+    def test_add_8bit_body(self):
+        key = self._box.add(self._non_latin_bin_msg)
+        self.assertEqual(self._box.get_bytes(key),
+                         self._non_latin_bin_msg)
+        with self._box.get_file(key) as f:
+            self.assertEqual(f.read(),
+                             self._non_latin_bin_msg.replace(b'\n',
+                                os.linesep.encode()))
+        self.assertEqual(self._box[key].get_payload(),
+                        "Да, они летят.\n")
+
+    def test_add_binary_file(self):
+        with tempfile.TemporaryFile('wb+') as f:
+            f.write(_bytes_sample_message)
+            f.seek(0)
+            key = self._box.add(f)
+        # See issue 11062
+        if not isinstance(self._box, mailbox.Babyl):
+            self.assertEqual(self._box.get_bytes(key).split(b'\n'),
+                _bytes_sample_message.split(b'\n'))
+
+    def test_add_binary_nonascii_file(self):
+        with tempfile.TemporaryFile('wb+') as f:
+            f.write(self._non_latin_bin_msg)
+            f.seek(0)
+            key = self._box.add(f)
+        # See issue 11062
+        if not isinstance(self._box, mailbox.Babyl):
+            self.assertEqual(self._box.get_bytes(key).split(b'\n'),
+                self._non_latin_bin_msg.split(b'\n'))
+
+    def test_add_text_file_warns(self):
+        with tempfile.TemporaryFile('w+') as f:
+            f.write(_sample_message)
+            f.seek(0)
+            with self.assertWarns(DeprecationWarning):
+                key = self._box.add(f)
+        # See issue 11062
+        if not isinstance(self._box, mailbox.Babyl):
+            self.assertEqual(self._box.get_bytes(key).split(b'\n'),
+                _bytes_sample_message.split(b'\n'))
+
+    def test_add_StringIO_warns(self):
+        with self.assertWarns(DeprecationWarning):
+            key = self._box.add(io.StringIO(self._template % "0"))
+        self.assertEqual(self._box.get_string(key), self._template % "0")
+
+    def test_add_nonascii_StringIO_raises(self):
+        with self.assertWarns(DeprecationWarning):
+            with self.assertRaisesRegex(ValueError, "ASCII-only"):
+                self._box.add(io.StringIO(self._nonascii_msg))
+        self.assertEqual(len(self._box), 0)
+        self._box.close()
+        self.assertMailboxEmpty()
+
     def test_remove(self):
         # Remove messages using remove()
         self._test_remove_or_delitem(self._box.remove)
@@ -154,12 +268,21 @@
         self.assertEqual(msg0.get_payload(), '0')
         self._check_sample(self._box.get_message(key1))
 
+    def test_get_bytes(self):
+        # Get bytes representations of messages
+        key0 = self._box.add(self._template % 0)
+        key1 = self._box.add(_sample_message)
+        self.assertEqual(self._box.get_bytes(key0),
+            (self._template % 0).encode('ascii'))
+        self.assertEqual(self._box.get_bytes(key1), _bytes_sample_message)
+
     def test_get_string(self):
         # Get string representations of messages
         key0 = self._box.add(self._template % 0)
         key1 = self._box.add(_sample_message)
         self.assertEqual(self._box.get_string(key0), self._template % 0)
-        self.assertEqual(self._box.get_string(key1), _sample_message)
+        self.assertEqual(self._box.get_string(key1).split('\n'),
+                         _sample_message.split('\n'))
 
     def test_get_file(self):
         # Get file representations of messages
@@ -169,9 +292,9 @@
             data0 = file.read()
         with self._box.get_file(key1) as file:
             data1 = file.read()
-        self.assertEqual(data0.replace(os.linesep, '\n'),
+        self.assertEqual(data0.decode('ascii').replace(os.linesep, '\n'),
                          self._template % 0)
-        self.assertEqual(data1.replace(os.linesep, '\n'),
+        self.assertEqual(data1.decode('ascii').replace(os.linesep, '\n'),
                          _sample_message)
 
     def test_iterkeys(self):
@@ -405,11 +528,12 @@
     def test_dump_message(self):
         # Write message representations to disk
         for input in (email.message_from_string(_sample_message),
-                      _sample_message, io.StringIO(_sample_message)):
-            output = io.StringIO()
+                      _sample_message, io.BytesIO(_bytes_sample_message)):
+            output = io.BytesIO()
             self._box._dump_message(input, output)
-            self.assertEqual(output.getvalue(), _sample_message)
-        output = io.StringIO()
+            self.assertEqual(output.getvalue(),
+                _bytes_sample_message.replace(b'\n', os.linesep.encode()))
+        output = io.BytesIO()
         self.assertRaises(TypeError,
                           lambda: self._box._dump_message(None, output))
 
@@ -439,6 +563,7 @@
         self.assertRaises(NotImplementedError, lambda: box.__getitem__(''))
         self.assertRaises(NotImplementedError, lambda: box.get_message(''))
         self.assertRaises(NotImplementedError, lambda: box.get_string(''))
+        self.assertRaises(NotImplementedError, lambda: box.get_bytes(''))
         self.assertRaises(NotImplementedError, lambda: box.get_file(''))
         self.assertRaises(NotImplementedError, lambda: '' in box)
         self.assertRaises(NotImplementedError, lambda: box.__contains__(''))
@@ -462,6 +587,9 @@
         if os.name in ('nt', 'os2') or sys.platform == 'cygwin':
             self._box.colon = '!'
 
+    def assertMailboxEmpty(self):
+        self.assertEqual(os.listdir(os.path.join(self._path, 'tmp')), [])
+
     def test_add_MM(self):
         # Add a MaildirMessage instance
         msg = mailbox.MaildirMessage(self._template % 0)
@@ -640,9 +768,9 @@
                              "Host name mismatch: '%s' should be '%s'" %
                              (groups[4], hostname))
             previous_groups = groups
-            tmp_file.write(_sample_message)
+            tmp_file.write(_bytes_sample_message)
             tmp_file.seek(0)
-            self.assertEqual(tmp_file.read(), _sample_message)
+            self.assertEqual(tmp_file.read(), _bytes_sample_message)
             tmp_file.close()
         file_count = len(os.listdir(os.path.join(self._path, "tmp")))
         self.assertEqual(file_count, repetitions,
@@ -781,12 +909,22 @@
         for lock_remnant in glob.glob(self._path + '.*'):
             support.unlink(lock_remnant)
 
+    def assertMailboxEmpty(self):
+        with open(self._path) as f:
+            self.assertEqual(f.readlines(), [])
+
     def test_add_from_string(self):
         # Add a string starting with 'From ' to the mailbox
         key = self._box.add('From foo at bar blah\nFrom: foo\n\n0')
         self.assertEqual(self._box[key].get_from(), 'foo at bar blah')
         self.assertEqual(self._box[key].get_payload(), '0')
 
+    def test_add_from_bytes(self):
+        # Add a byte string starting with 'From ' to the mailbox
+        key = self._box.add(b'From foo at bar blah\nFrom: foo\n\n0')
+        self.assertEqual(self._box[key].get_from(), 'foo at bar blah')
+        self.assertEqual(self._box[key].get_payload(), '0')
+
     def test_add_mbox_or_mmdf_message(self):
         # Add an mboxMessage or MMDFMessage
         for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
@@ -817,7 +955,7 @@
         self._box._file.seek(0)
         contents = self._box._file.read()
         self._box.close()
-        with open(self._path, 'r', newline='') as f:
+        with open(self._path, 'rb') as f:
             self.assertEqual(contents, f.read())
         self._box = self._factory(self._path)
 
@@ -897,6 +1035,9 @@
 
     _factory = lambda self, path, factory=None: mailbox.MH(path, factory)
 
+    def assertMailboxEmpty(self):
+        self.assertEqual(os.listdir(self._path), ['.mh_sequences'])
+
     def test_list_folders(self):
         # List folders
         self._box.add_folder('one')
@@ -1029,6 +1170,10 @@
 
     _factory = lambda self, path, factory=None: mailbox.Babyl(path, factory)
 
+    def assertMailboxEmpty(self):
+        with open(self._path) as f:
+            self.assertEqual(f.readlines(), [])
+
     def tearDown(self):
         super().tearDown()
         self._box.close()
@@ -1087,6 +1232,15 @@
             self._post_initialize_hook(msg)
             self._check_sample(msg)
 
+    def test_initialize_with_binary_file(self):
+        # Initialize based on contents of binary file
+        with open(self._path, 'wb+') as f:
+            f.write(_bytes_sample_message)
+            f.seek(0)
+            msg = self._factory(f)
+            self._post_initialize_hook(msg)
+            self._check_sample(msg)
+
     def test_initialize_with_nothing(self):
         # Initialize without arguments
         msg = self._factory()
@@ -1363,6 +1517,14 @@
             msg_plain = mailbox.Message(msg)
             self._check_sample(msg_plain)
 
+    def test_x_from_bytes(self):
+        # Convert all formats to Message
+        for class_ in (mailbox.Message, mailbox.MaildirMessage,
+                       mailbox.mboxMessage, mailbox.MHMessage,
+                       mailbox.BabylMessage, mailbox.MMDFMessage):
+            msg = class_(_bytes_sample_message)
+            self._check_sample(msg)
+
     def test_x_to_invalid(self):
         # Convert all formats to an invalid format
         for class_ in (mailbox.Message, mailbox.MaildirMessage,
@@ -1908,6 +2070,8 @@
 --NMuMz9nt05w80d4+--
 """
 
+_bytes_sample_message = _sample_message.encode('ascii')
+
 _sample_headers = {
     "Return-Path":"<gkj at gregorykjohnson.com>",
     "X-Original-To":"gkj+person at localhost",

Modified: python/branches/pep-3151/Lib/test/test_marshal.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_marshal.py	(original)
+++ python/branches/pep-3151/Lib/test/test_marshal.py	Sat Feb 26 08:16:32 2011
@@ -149,8 +149,8 @@
 
     def test_version_argument(self):
         # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
-        self.assertEquals(marshal.loads(marshal.dumps(5, 0)), 5)
-        self.assertEquals(marshal.loads(marshal.dumps(5, 1)), 5)
+        self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
+        self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
 
     def test_fuzz(self):
         # simple test that it's at least not *totally* trivial to

Modified: python/branches/pep-3151/Lib/test/test_math.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_math.py	(original)
+++ python/branches/pep-3151/Lib/test/test_math.py	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,7 @@
 # Python test set -- math module
 # XXXX Should not do tests around zero only
 
-from test.support import run_unittest, verbose
+from test.support import run_unittest, verbose, requires_IEEE_754
 import unittest
 import math
 import os
@@ -15,11 +15,6 @@
 INF = float('inf')
 NINF = float('-inf')
 
-# decorator for skipping tests on non-IEEE 754 platforms
-requires_IEEE_754 = unittest.skipUnless(
-    float.__getformat__("double").startswith("IEEE"),
-    "test requires IEEE 754 doubles")
-
 # detect evidence of double-rounding: fsum is not always correctly
 # rounded on machines that suffer from double rounding.
 x, y = 1e16, 2.9999 # use temporary values to defeat peephole optimizer
@@ -209,7 +204,7 @@
         self.ftest('acosh(2)', math.acosh(2), 1.3169578969248168)
         self.assertRaises(ValueError, math.acosh, 0)
         self.assertRaises(ValueError, math.acosh, -1)
-        self.assertEquals(math.acosh(INF), INF)
+        self.assertEqual(math.acosh(INF), INF)
         self.assertRaises(ValueError, math.acosh, NINF)
         self.assertTrue(math.isnan(math.acosh(NAN)))
 
@@ -227,8 +222,8 @@
         self.ftest('asinh(0)', math.asinh(0), 0)
         self.ftest('asinh(1)', math.asinh(1), 0.88137358701954305)
         self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
-        self.assertEquals(math.asinh(INF), INF)
-        self.assertEquals(math.asinh(NINF), NINF)
+        self.assertEqual(math.asinh(INF), INF)
+        self.assertEqual(math.asinh(NINF), NINF)
         self.assertTrue(math.isnan(math.asinh(NAN)))
 
     def testAtan(self):
@@ -314,15 +309,15 @@
 
     def testCeil(self):
         self.assertRaises(TypeError, math.ceil)
-        self.assertEquals(int, type(math.ceil(0.5)))
+        self.assertEqual(int, type(math.ceil(0.5)))
         self.ftest('ceil(0.5)', math.ceil(0.5), 1)
         self.ftest('ceil(1.0)', math.ceil(1.0), 1)
         self.ftest('ceil(1.5)', math.ceil(1.5), 2)
         self.ftest('ceil(-0.5)', math.ceil(-0.5), 0)
         self.ftest('ceil(-1.0)', math.ceil(-1.0), -1)
         self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
-        #self.assertEquals(math.ceil(INF), INF)
-        #self.assertEquals(math.ceil(NINF), NINF)
+        #self.assertEqual(math.ceil(INF), INF)
+        #self.assertEqual(math.ceil(NINF), NINF)
         #self.assertTrue(math.isnan(math.ceil(NAN)))
 
         class TestCeil:
@@ -348,19 +343,19 @@
 
         self.assertRaises(TypeError, math.copysign)
         # copysign should let us distinguish signs of zeros
-        self.assertEquals(math.copysign(1., 0.), 1.)
-        self.assertEquals(math.copysign(1., -0.), -1.)
-        self.assertEquals(math.copysign(INF, 0.), INF)
-        self.assertEquals(math.copysign(INF, -0.), NINF)
-        self.assertEquals(math.copysign(NINF, 0.), INF)
-        self.assertEquals(math.copysign(NINF, -0.), NINF)
+        self.assertEqual(math.copysign(1., 0.), 1.)
+        self.assertEqual(math.copysign(1., -0.), -1.)
+        self.assertEqual(math.copysign(INF, 0.), INF)
+        self.assertEqual(math.copysign(INF, -0.), NINF)
+        self.assertEqual(math.copysign(NINF, 0.), INF)
+        self.assertEqual(math.copysign(NINF, -0.), NINF)
         # and of infinities
-        self.assertEquals(math.copysign(1., INF), 1.)
-        self.assertEquals(math.copysign(1., NINF), -1.)
-        self.assertEquals(math.copysign(INF, INF), INF)
-        self.assertEquals(math.copysign(INF, NINF), NINF)
-        self.assertEquals(math.copysign(NINF, INF), INF)
-        self.assertEquals(math.copysign(NINF, NINF), NINF)
+        self.assertEqual(math.copysign(1., INF), 1.)
+        self.assertEqual(math.copysign(1., NINF), -1.)
+        self.assertEqual(math.copysign(INF, INF), INF)
+        self.assertEqual(math.copysign(INF, NINF), NINF)
+        self.assertEqual(math.copysign(NINF, INF), INF)
+        self.assertEqual(math.copysign(NINF, NINF), NINF)
         self.assertTrue(math.isnan(math.copysign(NAN, 1.)))
         self.assertTrue(math.isnan(math.copysign(NAN, INF)))
         self.assertTrue(math.isnan(math.copysign(NAN, NINF)))
@@ -370,7 +365,7 @@
         # given platform.
         self.assertTrue(math.isinf(math.copysign(INF, NAN)))
         # similarly, copysign(2., NAN) could be 2. or -2.
-        self.assertEquals(abs(math.copysign(2., NAN)), 2.)
+        self.assertEqual(abs(math.copysign(2., NAN)), 2.)
 
     def testCos(self):
         self.assertRaises(TypeError, math.cos)
@@ -390,8 +385,8 @@
         self.assertRaises(TypeError, math.cosh)
         self.ftest('cosh(0)', math.cosh(0), 1)
         self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert
-        self.assertEquals(math.cosh(INF), INF)
-        self.assertEquals(math.cosh(NINF), INF)
+        self.assertEqual(math.cosh(INF), INF)
+        self.assertEqual(math.cosh(NINF), INF)
         self.assertTrue(math.isnan(math.cosh(NAN)))
 
     def testDegrees(self):
@@ -405,8 +400,8 @@
         self.ftest('exp(-1)', math.exp(-1), 1/math.e)
         self.ftest('exp(0)', math.exp(0), 1)
         self.ftest('exp(1)', math.exp(1), math.e)
-        self.assertEquals(math.exp(INF), INF)
-        self.assertEquals(math.exp(NINF), 0.)
+        self.assertEqual(math.exp(INF), INF)
+        self.assertEqual(math.exp(NINF), 0.)
         self.assertTrue(math.isnan(math.exp(NAN)))
 
     def testFabs(self):
@@ -432,7 +427,7 @@
 
     def testFloor(self):
         self.assertRaises(TypeError, math.floor)
-        self.assertEquals(int, type(math.floor(0.5)))
+        self.assertEqual(int, type(math.floor(0.5)))
         self.ftest('floor(0.5)', math.floor(0.5), 0)
         self.ftest('floor(1.0)', math.floor(1.0), 1)
         self.ftest('floor(1.5)', math.floor(1.5), 1)
@@ -443,8 +438,8 @@
         # This fails on some platforms - so check it here
         self.ftest('floor(1.23e167)', math.floor(1.23e167), 1.23e167)
         self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
-        #self.assertEquals(math.ceil(INF), INF)
-        #self.assertEquals(math.ceil(NINF), NINF)
+        #self.assertEqual(math.ceil(INF), INF)
+        #self.assertEqual(math.ceil(NINF), NINF)
         #self.assertTrue(math.isnan(math.floor(NAN)))
 
         class TestFloor:
@@ -475,12 +470,12 @@
         self.assertRaises(ValueError, math.fmod, INF, 1.)
         self.assertRaises(ValueError, math.fmod, NINF, 1.)
         self.assertRaises(ValueError, math.fmod, INF, 0.)
-        self.assertEquals(math.fmod(3.0, INF), 3.0)
-        self.assertEquals(math.fmod(-3.0, INF), -3.0)
-        self.assertEquals(math.fmod(3.0, NINF), 3.0)
-        self.assertEquals(math.fmod(-3.0, NINF), -3.0)
-        self.assertEquals(math.fmod(0.0, 3.0), 0.0)
-        self.assertEquals(math.fmod(0.0, NINF), 0.0)
+        self.assertEqual(math.fmod(3.0, INF), 3.0)
+        self.assertEqual(math.fmod(-3.0, INF), -3.0)
+        self.assertEqual(math.fmod(3.0, NINF), 3.0)
+        self.assertEqual(math.fmod(-3.0, NINF), -3.0)
+        self.assertEqual(math.fmod(0.0, 3.0), 0.0)
+        self.assertEqual(math.fmod(0.0, NINF), 0.0)
 
     def testFrexp(self):
         self.assertRaises(TypeError, math.frexp)
@@ -496,8 +491,8 @@
         testfrexp('frexp(1)', math.frexp(1), (0.5, 1))
         testfrexp('frexp(2)', math.frexp(2), (0.5, 2))
 
-        self.assertEquals(math.frexp(INF)[0], INF)
-        self.assertEquals(math.frexp(NINF)[0], NINF)
+        self.assertEqual(math.frexp(INF)[0], INF)
+        self.assertEqual(math.frexp(NINF)[0], NINF)
         self.assertTrue(math.isnan(math.frexp(NAN)[0]))
 
     @requires_IEEE_754
@@ -610,28 +605,28 @@
         self.ftest('ldexp(-1,1)', math.ldexp(-1,1), -2)
         self.assertRaises(OverflowError, math.ldexp, 1., 1000000)
         self.assertRaises(OverflowError, math.ldexp, -1., 1000000)
-        self.assertEquals(math.ldexp(1., -1000000), 0.)
-        self.assertEquals(math.ldexp(-1., -1000000), -0.)
-        self.assertEquals(math.ldexp(INF, 30), INF)
-        self.assertEquals(math.ldexp(NINF, -213), NINF)
+        self.assertEqual(math.ldexp(1., -1000000), 0.)
+        self.assertEqual(math.ldexp(-1., -1000000), -0.)
+        self.assertEqual(math.ldexp(INF, 30), INF)
+        self.assertEqual(math.ldexp(NINF, -213), NINF)
         self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
 
         # large second argument
         for n in [10**5, 10**10, 10**20, 10**40]:
-            self.assertEquals(math.ldexp(INF, -n), INF)
-            self.assertEquals(math.ldexp(NINF, -n), NINF)
-            self.assertEquals(math.ldexp(1., -n), 0.)
-            self.assertEquals(math.ldexp(-1., -n), -0.)
-            self.assertEquals(math.ldexp(0., -n), 0.)
-            self.assertEquals(math.ldexp(-0., -n), -0.)
+            self.assertEqual(math.ldexp(INF, -n), INF)
+            self.assertEqual(math.ldexp(NINF, -n), NINF)
+            self.assertEqual(math.ldexp(1., -n), 0.)
+            self.assertEqual(math.ldexp(-1., -n), -0.)
+            self.assertEqual(math.ldexp(0., -n), 0.)
+            self.assertEqual(math.ldexp(-0., -n), -0.)
             self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
 
             self.assertRaises(OverflowError, math.ldexp, 1., n)
             self.assertRaises(OverflowError, math.ldexp, -1., n)
-            self.assertEquals(math.ldexp(0., n), 0.)
-            self.assertEquals(math.ldexp(-0., n), -0.)
-            self.assertEquals(math.ldexp(INF, n), INF)
-            self.assertEquals(math.ldexp(NINF, n), NINF)
+            self.assertEqual(math.ldexp(0., n), 0.)
+            self.assertEqual(math.ldexp(-0., n), -0.)
+            self.assertEqual(math.ldexp(INF, n), INF)
+            self.assertEqual(math.ldexp(NINF, n), NINF)
             self.assertTrue(math.isnan(math.ldexp(NAN, n)))
 
     def testLog(self):
@@ -647,13 +642,13 @@
         self.assertRaises(ValueError, math.log, -1.5)
         self.assertRaises(ValueError, math.log, -10**1000)
         self.assertRaises(ValueError, math.log, NINF)
-        self.assertEquals(math.log(INF), INF)
+        self.assertEqual(math.log(INF), INF)
         self.assertTrue(math.isnan(math.log(NAN)))
 
     def testLog1p(self):
         self.assertRaises(TypeError, math.log1p)
         n= 2**90
-        self.assertAlmostEquals(math.log1p(n), math.log1p(float(n)))
+        self.assertAlmostEqual(math.log1p(n), math.log1p(float(n)))
 
     def testLog10(self):
         self.assertRaises(TypeError, math.log10)
@@ -664,7 +659,7 @@
         self.assertRaises(ValueError, math.log10, -1.5)
         self.assertRaises(ValueError, math.log10, -10**1000)
         self.assertRaises(ValueError, math.log10, NINF)
-        self.assertEquals(math.log(INF), INF)
+        self.assertEqual(math.log(INF), INF)
         self.assertTrue(math.isnan(math.log10(NAN)))
 
     def testModf(self):
@@ -679,8 +674,8 @@
         testmodf('modf(1.5)', math.modf(1.5), (0.5, 1.0))
         testmodf('modf(-1.5)', math.modf(-1.5), (-0.5, -1.0))
 
-        self.assertEquals(math.modf(INF), (0.0, INF))
-        self.assertEquals(math.modf(NINF), (-0.0, NINF))
+        self.assertEqual(math.modf(INF), (0.0, INF))
+        self.assertEqual(math.modf(NINF), (-0.0, NINF))
 
         modf_nan = math.modf(NAN)
         self.assertTrue(math.isnan(modf_nan[0]))
@@ -859,8 +854,8 @@
         self.ftest('sinh(0)', math.sinh(0), 0)
         self.ftest('sinh(1)**2-cosh(1)**2', math.sinh(1)**2-math.cosh(1)**2, -1)
         self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
-        self.assertEquals(math.sinh(INF), INF)
-        self.assertEquals(math.sinh(NINF), NINF)
+        self.assertEqual(math.sinh(INF), INF)
+        self.assertEqual(math.sinh(NINF), NINF)
         self.assertTrue(math.isnan(math.sinh(NAN)))
 
     def testSqrt(self):
@@ -868,7 +863,7 @@
         self.ftest('sqrt(0)', math.sqrt(0), 0)
         self.ftest('sqrt(1)', math.sqrt(1), 1)
         self.ftest('sqrt(4)', math.sqrt(4), 2)
-        self.assertEquals(math.sqrt(INF), INF)
+        self.assertEqual(math.sqrt(INF), INF)
         self.assertRaises(ValueError, math.sqrt, NINF)
         self.assertTrue(math.isnan(math.sqrt(NAN)))
 

Modified: python/branches/pep-3151/Lib/test/test_memoryio.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_memoryio.py	(original)
+++ python/branches/pep-3151/Lib/test/test_memoryio.py	Sat Feb 26 08:16:32 2011
@@ -20,17 +20,17 @@
         buf = self.buftype("1234567890")
         bytesIo = self.ioclass(buf)
 
-        self.assertEquals(buf[:1], bytesIo.read(1))
-        self.assertEquals(buf[1:5], bytesIo.read(4))
-        self.assertEquals(buf[5:], bytesIo.read(900))
-        self.assertEquals(self.EOF, bytesIo.read())
+        self.assertEqual(buf[:1], bytesIo.read(1))
+        self.assertEqual(buf[1:5], bytesIo.read(4))
+        self.assertEqual(buf[5:], bytesIo.read(900))
+        self.assertEqual(self.EOF, bytesIo.read())
 
     def testReadNoArgs(self):
         buf = self.buftype("1234567890")
         bytesIo = self.ioclass(buf)
 
-        self.assertEquals(buf, bytesIo.read())
-        self.assertEquals(self.EOF, bytesIo.read())
+        self.assertEqual(buf, bytesIo.read())
+        self.assertEqual(self.EOF, bytesIo.read())
 
     def testSeek(self):
         buf = self.buftype("1234567890")
@@ -38,21 +38,21 @@
 
         bytesIo.read(5)
         bytesIo.seek(0)
-        self.assertEquals(buf, bytesIo.read())
+        self.assertEqual(buf, bytesIo.read())
 
         bytesIo.seek(3)
-        self.assertEquals(buf[3:], bytesIo.read())
+        self.assertEqual(buf[3:], bytesIo.read())
         self.assertRaises(TypeError, bytesIo.seek, 0.0)
 
     def testTell(self):
         buf = self.buftype("1234567890")
         bytesIo = self.ioclass(buf)
 
-        self.assertEquals(0, bytesIo.tell())
+        self.assertEqual(0, bytesIo.tell())
         bytesIo.seek(5)
-        self.assertEquals(5, bytesIo.tell())
+        self.assertEqual(5, bytesIo.tell())
         bytesIo.seek(10000)
-        self.assertEquals(10000, bytesIo.tell())
+        self.assertEqual(10000, bytesIo.tell())
 
 
 class MemoryTestMixin:
@@ -452,6 +452,11 @@
         self.assertEqual(a.tobytes(), b"1234567890d")
         memio.close()
         self.assertRaises(ValueError, memio.readinto, b)
+        memio = self.ioclass(b"123")
+        b = bytearray()
+        memio.seek(42)
+        memio.readinto(b)
+        self.assertEqual(b, b"")
 
     def test_relative_seek(self):
         buf = self.buftype("1234567890")
@@ -629,7 +634,7 @@
         self.assertEqual(len(state), 3)
         bytearray(state[0]) # Check if state[0] supports the buffer interface.
         self.assertIsInstance(state[1], int)
-        self.assert_(isinstance(state[2], dict) or state[2] is None)
+        self.assertTrue(isinstance(state[2], dict) or state[2] is None)
         memio.close()
         self.assertRaises(ValueError, memio.__getstate__)
 
@@ -675,7 +680,7 @@
         self.assertIsInstance(state[0], str)
         self.assertIsInstance(state[1], str)
         self.assertIsInstance(state[2], int)
-        self.assert_(isinstance(state[3], dict) or state[3] is None)
+        self.assertTrue(isinstance(state[3], dict) or state[3] is None)
         memio.close()
         self.assertRaises(ValueError, memio.__getstate__)
 

Modified: python/branches/pep-3151/Lib/test/test_memoryview.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_memoryview.py	(original)
+++ python/branches/pep-3151/Lib/test/test_memoryview.py	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,7 @@
 import gc
 import weakref
 import array
+import io
 
 
 class AbstractMemoryTests:
@@ -27,11 +28,11 @@
         b = tp(self._source)
         oldrefcount = sys.getrefcount(b)
         m = self._view(b)
-        self.assertEquals(m[0], item(b"a"))
+        self.assertEqual(m[0], item(b"a"))
         self.assertIsInstance(m[0], bytes)
-        self.assertEquals(m[5], item(b"f"))
-        self.assertEquals(m[-1], item(b"f"))
-        self.assertEquals(m[-6], item(b"a"))
+        self.assertEqual(m[5], item(b"f"))
+        self.assertEqual(m[-1], item(b"f"))
+        self.assertEqual(m[-6], item(b"a"))
         # Bounds checking
         self.assertRaises(IndexError, lambda: m[6])
         self.assertRaises(IndexError, lambda: m[-7])
@@ -42,7 +43,7 @@
         self.assertRaises(TypeError, lambda: m[0.0])
         self.assertRaises(TypeError, lambda: m["a"])
         m = None
-        self.assertEquals(sys.getrefcount(b), oldrefcount)
+        self.assertEqual(sys.getrefcount(b), oldrefcount)
 
     def test_getitem(self):
         for tp in self._types:
@@ -66,7 +67,7 @@
         self.assertRaises(TypeError, setitem, 65)
         self.assertRaises(TypeError, setitem, memoryview(b"a"))
         m = None
-        self.assertEquals(sys.getrefcount(b), oldrefcount)
+        self.assertEqual(sys.getrefcount(b), oldrefcount)
 
     def test_setitem_writable(self):
         if not self.rw_type:
@@ -109,7 +110,7 @@
         self.assertRaises(ValueError, setitem, slice(0,2), b"a")
 
         m = None
-        self.assertEquals(sys.getrefcount(b), oldrefcount)
+        self.assertEqual(sys.getrefcount(b), oldrefcount)
 
     def test_delitem(self):
         for tp in self._types:
@@ -127,14 +128,14 @@
             # This calls self.getitem_type() on each separate byte of b"abcdef"
             expected = b"".join(
                 self.getitem_type(bytes([c])) for c in b"abcdef")
-            self.assertEquals(b, expected)
+            self.assertEqual(b, expected)
             self.assertIsInstance(b, bytes)
 
     def test_tolist(self):
         for tp in self._types:
             m = self._view(tp(self._source))
             l = m.tolist()
-            self.assertEquals(l, list(b"abcdef"))
+            self.assertEqual(l, list(b"abcdef"))
 
     def test_compare(self):
         # memoryviews can compare for equality with other objects
@@ -168,26 +169,26 @@
 
     def check_attributes_with_type(self, tp):
         m = self._view(tp(self._source))
-        self.assertEquals(m.format, self.format)
-        self.assertEquals(m.itemsize, self.itemsize)
-        self.assertEquals(m.ndim, 1)
-        self.assertEquals(m.shape, (6,))
-        self.assertEquals(len(m), 6)
-        self.assertEquals(m.strides, (self.itemsize,))
-        self.assertEquals(m.suboffsets, None)
+        self.assertEqual(m.format, self.format)
+        self.assertEqual(m.itemsize, self.itemsize)
+        self.assertEqual(m.ndim, 1)
+        self.assertEqual(m.shape, (6,))
+        self.assertEqual(len(m), 6)
+        self.assertEqual(m.strides, (self.itemsize,))
+        self.assertEqual(m.suboffsets, None)
         return m
 
     def test_attributes_readonly(self):
         if not self.ro_type:
             return
         m = self.check_attributes_with_type(self.ro_type)
-        self.assertEquals(m.readonly, True)
+        self.assertEqual(m.readonly, True)
 
     def test_attributes_writable(self):
         if not self.rw_type:
             return
         m = self.check_attributes_with_type(self.rw_type)
-        self.assertEquals(m.readonly, False)
+        self.assertEqual(m.readonly, False)
 
     def test_getbuffer(self):
         # Test PyObject_GetBuffer() on a memoryview object.
@@ -198,9 +199,9 @@
             oldviewrefcount = sys.getrefcount(m)
             s = str(m, "utf-8")
             self._check_contents(tp, b, s.encode("utf-8"))
-            self.assertEquals(sys.getrefcount(m), oldviewrefcount)
+            self.assertEqual(sys.getrefcount(m), oldviewrefcount)
             m = None
-            self.assertEquals(sys.getrefcount(b), oldrefcount)
+            self.assertEqual(sys.getrefcount(b), oldrefcount)
 
     def test_gc(self):
         for tp in self._types:
@@ -226,7 +227,7 @@
             self.assertTrue(wr() is None, wr())
 
     def _check_released(self, m, tp):
-        check = self.assertRaisesRegexp(ValueError, "released")
+        check = self.assertRaisesRegex(ValueError, "released")
         with check: bytes(m)
         with check: m.tobytes()
         with check: m.tolist()
@@ -271,6 +272,17 @@
             m.release()
             self._check_released(m, tp)
 
+    def test_writable_readonly(self):
+        # Issue #10451: memoryview incorrectly exposes a readonly
+        # buffer as writable causing a segfault if using mmap
+        tp = self.ro_type
+        if tp is None:
+            return
+        b = tp(self._source)
+        m = self._view(b)
+        i = io.BytesIO(b'ZZZZ')
+        self.assertRaises(TypeError, i.readinto, m)
+
 # Variations on source objects for the buffer: bytes-like objects, then arrays
 # with itemsize > 1.
 # NOTE: support for multi-dimensional objects is unimplemented.
@@ -307,7 +319,7 @@
         return memoryview(obj)
 
     def _check_contents(self, tp, obj, contents):
-        self.assertEquals(obj, tp(contents))
+        self.assertEqual(obj, tp(contents))
 
 class BaseMemorySliceTests:
     source_bytes = b"XabcdefY"
@@ -317,14 +329,14 @@
         return m[1:7]
 
     def _check_contents(self, tp, obj, contents):
-        self.assertEquals(obj[1:7], tp(contents))
+        self.assertEqual(obj[1:7], tp(contents))
 
     def test_refs(self):
         for tp in self._types:
             m = memoryview(tp(self._source))
             oldrefcount = sys.getrefcount(m)
             m[1:2]
-            self.assertEquals(sys.getrefcount(m), oldrefcount)
+            self.assertEqual(sys.getrefcount(m), oldrefcount)
 
 class BaseMemorySliceSliceTests:
     source_bytes = b"XabcdefY"
@@ -334,7 +346,7 @@
         return m[:7][1:]
 
     def _check_contents(self, tp, obj, contents):
-        self.assertEquals(obj[1:7], tp(contents))
+        self.assertEqual(obj[1:7], tp(contents))
 
 
 # Concrete test classes
@@ -361,7 +373,7 @@
         m = memoryview(a)
         new_a = array.array('i', range(9, -1, -1))
         m[:] = new_a
-        self.assertEquals(a, new_a)
+        self.assertEqual(a, new_a)
 
 
 class BytesMemorySliceTest(unittest.TestCase,

Modified: python/branches/pep-3151/Lib/test/test_metaclass.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_metaclass.py	(original)
+++ python/branches/pep-3151/Lib/test/test_metaclass.py	Sat Feb 26 08:16:32 2011
@@ -246,7 +246,13 @@
 
 """
 
-__test__ = {'doctests' : doctests}
+import sys
+
+# Trace function introduces __locals__ which causes various tests to fail.
+if hasattr(sys, 'gettrace') and sys.gettrace():
+    __test__ = {}
+else:
+    __test__ = {'doctests' : doctests}
 
 def test_main(verbose=False):
     from test import support

Modified: python/branches/pep-3151/Lib/test/test_minidom.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_minidom.py	(original)
+++ python/branches/pep-3151/Lib/test/test_minidom.py	Sat Feb 26 08:16:32 2011
@@ -755,7 +755,7 @@
     def check_clone_pi(self, deep, testName):
         doc = parseString("<?target data?><doc/>")
         pi = doc.firstChild
-        self.assertEquals(pi.nodeType, Node.PROCESSING_INSTRUCTION_NODE)
+        self.assertEqual(pi.nodeType, Node.PROCESSING_INSTRUCTION_NODE)
         clone = pi.cloneNode(deep)
         self.confirm(clone.target == pi.target
                 and clone.data == pi.data)
@@ -955,7 +955,7 @@
     def testBug0777884(self):
         doc = parseString("<o>text</o>")
         text = doc.documentElement.childNodes[0]
-        self.assertEquals(text.nodeType, Node.TEXT_NODE)
+        self.assertEqual(text.nodeType, Node.TEXT_NODE)
         # Should run quietly, doing nothing.
         text.normalize()
         doc.unlink()
@@ -1233,7 +1233,7 @@
         doc = parseString("<doc>a</doc>")
         elem = doc.documentElement
         text = elem.childNodes[0]
-        self.assertEquals(text.nodeType, Node.TEXT_NODE)
+        self.assertEqual(text.nodeType, Node.TEXT_NODE)
 
         self.checkWholeText(text, "a")
         elem.appendChild(doc.createTextNode("b"))

Modified: python/branches/pep-3151/Lib/test/test_mmap.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_mmap.py	(original)
+++ python/branches/pep-3151/Lib/test/test_mmap.py	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,4 @@
-from test.support import TESTFN, run_unittest, import_module
+from test.support import TESTFN, run_unittest, import_module, unlink, requires
 import unittest
 import os
 import re
@@ -320,6 +320,33 @@
             mf.close()
             f.close()
 
+    def test_length_0_offset(self):
+        # Issue #10916: test mapping of remainder of file by passing 0 for
+        # map length with an offset doesn't cause a segfault.
+        if not hasattr(os, "stat"):
+            self.skipTest("needs os.stat")
+        # NOTE: allocation granularity is currently 65536 under Win64,
+        # and therefore the minimum offset alignment.
+        with open(TESTFN, "wb") as f:
+            f.write((65536 * 2) * b'm') # Arbitrary character
+
+        with open(TESTFN, "rb") as f:
+            with mmap.mmap(f.fileno(), 0, offset=65536, access=mmap.ACCESS_READ) as mf:
+                self.assertRaises(IndexError, mf.__getitem__, 80000)
+
+    def test_length_0_large_offset(self):
+        # Issue #10959: test mapping of a file by passing 0 for
+        # map length with a large offset doesn't cause a segfault.
+        if not hasattr(os, "stat"):
+            self.skipTest("needs os.stat")
+
+        with open(TESTFN, "wb") as f:
+            f.write(115699 * b'm') # Arbitrary character
+
+        with open(TESTFN, "w+b") as f:
+            self.assertRaises(ValueError, mmap.mmap, f.fileno(), 0,
+                              offset=2147418112)
+
     def test_move(self):
         # make move works everywhere (64-bit format problem earlier)
         f = open(TESTFN, 'wb+')
@@ -413,7 +440,7 @@
                     data = bytes(reversed(data))
                     L[start:stop:step] = data
                     m[start:stop:step] = data
-                    self.assertEquals(m[:], bytes(L))
+                    self.assertEqual(m[:], bytes(L))
 
     def make_mmap_file (self, f, halfsize):
         # Write 2 pages worth of data to the file
@@ -509,27 +536,27 @@
         f.close()
         # Test write_byte()
         for i in range(len(data)):
-            self.assertEquals(m.tell(), i)
+            self.assertEqual(m.tell(), i)
             m.write_byte(data[i])
-            self.assertEquals(m.tell(), i+1)
+            self.assertEqual(m.tell(), i+1)
         self.assertRaises(ValueError, m.write_byte, b"x"[0])
-        self.assertEquals(m[:], data)
+        self.assertEqual(m[:], data)
         # Test read_byte()
         m.seek(0)
         for i in range(len(data)):
-            self.assertEquals(m.tell(), i)
-            self.assertEquals(m.read_byte(), data[i])
-            self.assertEquals(m.tell(), i+1)
+            self.assertEqual(m.tell(), i)
+            self.assertEqual(m.read_byte(), data[i])
+            self.assertEqual(m.tell(), i+1)
         self.assertRaises(ValueError, m.read_byte)
         # Test read()
         m.seek(3)
-        self.assertEquals(m.read(3), b"345")
-        self.assertEquals(m.tell(), 6)
+        self.assertEqual(m.read(3), b"345")
+        self.assertEqual(m.tell(), 6)
         # Test write()
         m.seek(3)
         m.write(b"bar")
-        self.assertEquals(m.tell(), 6)
-        self.assertEquals(m[:], b"012bar6789")
+        self.assertEqual(m.tell(), 6)
+        self.assertEqual(m[:], b"012bar6789")
         m.seek(8)
         self.assertRaises(ValueError, m.write, b"bar")
 
@@ -537,9 +564,9 @@
         for b in (129, 200, 255): # > 128
             m = mmap.mmap(-1, 1)
             m.write_byte(b)
-            self.assertEquals(m[0], b)
+            self.assertEqual(m[0], b)
             m.seek(0)
-            self.assertEquals(m.read_byte(), b)
+            self.assertEqual(m.read_byte(), b)
             m.close()
 
     if os.name == 'nt':
@@ -553,8 +580,8 @@
             m1[:] = data1
             m2 = mmap.mmap(-1, len(data2), tagname="foo")
             m2[:] = data2
-            self.assertEquals(m1[:], data2)
-            self.assertEquals(m2[:], data2)
+            self.assertEqual(m1[:], data2)
+            self.assertEqual(m2[:], data2)
             m2.close()
             m1.close()
 
@@ -563,8 +590,8 @@
             m1[:] = data1
             m2 = mmap.mmap(-1, len(data2), tagname="boo")
             m2[:] = data2
-            self.assertEquals(m1[:], data1)
-            self.assertEquals(m2[:], data2)
+            self.assertEqual(m1[:], data1)
+            self.assertEqual(m2[:], data2)
             m2.close()
             m1.close()
 
@@ -618,9 +645,56 @@
                               "wrong exception raised in context manager")
         self.assertTrue(m.closed, "context manager failed")
 
+class LargeMmapTests(unittest.TestCase):
+
+    def setUp(self):
+        unlink(TESTFN)
+
+    def tearDown(self):
+        unlink(TESTFN)
+
+    def _working_largefile(self):
+        # Only run if the current filesystem supports large files.
+        f = open(TESTFN, 'wb', buffering=0)
+        try:
+            f.seek(0x80000001)
+            f.write(b'x')
+            f.flush()
+        except (IOError, OverflowError):
+            raise unittest.SkipTest("filesystem does not have largefile support")
+        finally:
+            f.close()
+            unlink(TESTFN)
+
+    def test_large_offset(self):
+        if sys.platform[:3] == 'win' or sys.platform == 'darwin':
+            requires('largefile',
+                'test requires %s bytes and a long time to run' % str(0x180000000))
+        self._working_largefile()
+        with open(TESTFN, 'wb') as f:
+            f.seek(0x14FFFFFFF)
+            f.write(b" ")
+
+        with open(TESTFN, 'rb') as f:
+            with mmap.mmap(f.fileno(), 0, offset=0x140000000, access=mmap.ACCESS_READ) as m:
+                self.assertEqual(m[0xFFFFFFF], 32)
+
+    def test_large_filesize(self):
+        if sys.platform[:3] == 'win' or sys.platform == 'darwin':
+            requires('largefile',
+                'test requires %s bytes and a long time to run' % str(0x180000000))
+        self._working_largefile()
+        with open(TESTFN, 'wb') as f:
+            f.seek(0x17FFFFFFF)
+            f.write(b" ")
+
+        with open(TESTFN, 'rb') as f:
+            with mmap.mmap(f.fileno(), 0x10000, access=mmap.ACCESS_READ) as m:
+                self.assertEqual(m.size(), 0x180000000)
+
 
 def test_main():
-    run_unittest(MmapTests)
+    run_unittest(MmapTests, LargeMmapTests)
 
 if __name__ == '__main__':
     test_main()

Modified: python/branches/pep-3151/Lib/test/test_multiprocessing.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_multiprocessing.py	(original)
+++ python/branches/pep-3151/Lib/test/test_multiprocessing.py	Sat Feb 26 08:16:32 2011
@@ -163,6 +163,18 @@
         self.assertEqual(current.ident, os.getpid())
         self.assertEqual(current.exitcode, None)
 
+    def test_daemon_argument(self):
+        if self.TYPE == "threads":
+            return
+
+        # By default uses the current process's daemon flag.
+        proc0 = self.Process(target=self._test)
+        self.assertEquals(proc0.daemon, self.current_process().daemon)
+        proc1 = self.Process(target=self._test, daemon=True)
+        self.assertTrue(proc1.daemon)
+        proc2 = self.Process(target=self._test, daemon=False)
+        self.assertFalse(proc2.daemon)
+
     @classmethod
     def _test(cls, q, *args, **kwds):
         current = cls.current_process()
@@ -186,30 +198,30 @@
         current = self.current_process()
 
         if self.TYPE != 'threads':
-            self.assertEquals(p.authkey, current.authkey)
-        self.assertEquals(p.is_alive(), False)
-        self.assertEquals(p.daemon, True)
+            self.assertEqual(p.authkey, current.authkey)
+        self.assertEqual(p.is_alive(), False)
+        self.assertEqual(p.daemon, True)
         self.assertNotIn(p, self.active_children())
         self.assertTrue(type(self.active_children()) is list)
         self.assertEqual(p.exitcode, None)
 
         p.start()
 
-        self.assertEquals(p.exitcode, None)
-        self.assertEquals(p.is_alive(), True)
+        self.assertEqual(p.exitcode, None)
+        self.assertEqual(p.is_alive(), True)
         self.assertIn(p, self.active_children())
 
-        self.assertEquals(q.get(), args[1:])
-        self.assertEquals(q.get(), kwargs)
-        self.assertEquals(q.get(), p.name)
+        self.assertEqual(q.get(), args[1:])
+        self.assertEqual(q.get(), kwargs)
+        self.assertEqual(q.get(), p.name)
         if self.TYPE != 'threads':
-            self.assertEquals(q.get(), current.authkey)
-            self.assertEquals(q.get(), p.pid)
+            self.assertEqual(q.get(), current.authkey)
+            self.assertEqual(q.get(), p.pid)
 
         p.join()
 
-        self.assertEquals(p.exitcode, 0)
-        self.assertEquals(p.is_alive(), False)
+        self.assertEqual(p.exitcode, 0)
+        self.assertEqual(p.is_alive(), False)
         self.assertNotIn(p, self.active_children())
 
     @classmethod
@@ -815,8 +827,6 @@
 #
 #
 
- at unittest.skipUnless(HAS_SHAREDCTYPES,
-                     "requires multiprocessing.sharedctypes")
 class _TestValue(BaseTestCase):
 
     ALLOWED_TYPES = ('processes',)
@@ -828,6 +838,10 @@
         ('c', latin('x'), latin('y'))
         ]
 
+    def setUp(self):
+        if not HAS_SHAREDCTYPES:
+            self.skipTest("requires multiprocessing.sharedctypes")
+
     @classmethod
     def _test(cls, values):
         for sv, cv in zip(values, cls.codes_values):
@@ -1662,12 +1676,14 @@
         ('y', c_double)
         ]
 
- at unittest.skipUnless(HAS_SHAREDCTYPES,
-                     "requires multiprocessing.sharedctypes")
 class _TestSharedCTypes(BaseTestCase):
 
     ALLOWED_TYPES = ('processes',)
 
+    def setUp(self):
+        if not HAS_SHAREDCTYPES:
+            self.skipTest("requires multiprocessing.sharedctypes")
+
     @classmethod
     def _double(cls, x, y, foo, arr, string):
         x.value *= 2

Modified: python/branches/pep-3151/Lib/test/test_netrc.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_netrc.py	(original)
+++ python/branches/pep-3151/Lib/test/test_netrc.py	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,13 @@
 from test import support
 
 TEST_NETRC = """
+
+ #this is a comment
+#this is a comment
+# this is a comment
+
 machine foo login log1 password pass1 account acct1
+machine bar login log1 password pass# account acct1
 
 macdef macro1
 line1
@@ -28,17 +34,21 @@
         fp = open(temp_filename, mode)
         fp.write(TEST_NETRC)
         fp.close()
+        self.nrc = netrc.netrc(temp_filename)
 
     def tearDown(self):
         os.unlink(temp_filename)
 
     def test_case_1(self):
-        nrc = netrc.netrc(temp_filename)
-        self.assertTrue(nrc.macros == {'macro1':['line1\n', 'line2\n'],
-                                           'macro2':['line3\n', 'line4\n']}
-                                           )
-        self.assertTrue(nrc.hosts['foo'] == ('log1', 'acct1', 'pass1'))
-        self.assertTrue(nrc.hosts['default'] == ('log2', None, 'pass2'))
+        self.assertEqual(self.nrc.hosts['foo'], ('log1', 'acct1', 'pass1'))
+        self.assertEqual(self.nrc.hosts['default'], ('log2', None, 'pass2'))
+
+    def test_macros(self):
+        self.assertEqual(self.nrc.macros, {'macro1':['line1\n', 'line2\n'],
+                                           'macro2':['line3\n', 'line4\n']})
+
+    def test_parses_passwords_with_hash_character(self):
+        self.assertEqual(self.nrc.hosts['bar'], ('log1', 'acct1', 'pass#'))
 
 def test_main():
     support.run_unittest(NetrcTestCase)

Modified: python/branches/pep-3151/Lib/test/test_nntplib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_nntplib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_nntplib.py	Sat Feb 26 08:16:32 2011
@@ -2,7 +2,9 @@
 import datetime
 import textwrap
 import unittest
+import functools
 import contextlib
+import collections.abc
 from test import support
 from nntplib import NNTP, GroupInfo, _have_ssl
 import nntplib
@@ -112,9 +114,13 @@
 
     def test_xover(self):
         resp, count, first, last, name = self.server.group(self.GROUP_NAME)
-        resp, lines = self.server.xover(last, last)
+        resp, lines = self.server.xover(last - 5, last)
+        if len(lines) == 0:
+            self.skipTest("no articles retrieved")
+        # The 'last' article is not necessarily part of the output (cancelled?)
         art_num, art_dict = lines[0]
-        self.assertEqual(art_num, last)
+        self.assertGreaterEqual(art_num, last - 5)
+        self.assertLessEqual(art_num, last)
         self._check_art_dict(art_dict)
 
     def test_over(self):
@@ -127,7 +133,9 @@
         # The "start-end" article range form
         resp, lines = self.server.over((start, last))
         art_num, art_dict = lines[-1]
-        self.assertEqual(art_num, last)
+        # The 'last' article is not necessarily part of the output (cancelled?)
+        self.assertGreaterEqual(art_num, start)
+        self.assertLessEqual(art_num, last)
         self._check_art_dict(art_dict)
         # XXX The "message_id" form is unsupported by gmane
         # 503 Overview by message-ID unsupported
@@ -149,32 +157,28 @@
 
     def test_article_head_body(self):
         resp, count, first, last, name = self.server.group(self.GROUP_NAME)
-        resp, head = self.server.head(last)
+        # Try to find an available article
+        for art_num in (last, first, last - 1):
+            try:
+                resp, head = self.server.head(art_num)
+            except nntplib.NNTPTemporaryError as e:
+                if not e.response.startswith("423 "):
+                    raise
+                # "423 No such article" => choose another one
+                continue
+            break
+        else:
+            self.skipTest("could not find a suitable article number")
         self.assertTrue(resp.startswith("221 "), resp)
-        self.check_article_resp(resp, head, last)
-        resp, body = self.server.body(last)
+        self.check_article_resp(resp, head, art_num)
+        resp, body = self.server.body(art_num)
         self.assertTrue(resp.startswith("222 "), resp)
-        self.check_article_resp(resp, body, last)
-        resp, article = self.server.article(last)
+        self.check_article_resp(resp, body, art_num)
+        resp, article = self.server.article(art_num)
         self.assertTrue(resp.startswith("220 "), resp)
-        self.check_article_resp(resp, article, last)
+        self.check_article_resp(resp, article, art_num)
         self.assertEqual(article.lines, head.lines + [b''] + body.lines)
 
-    def test_quit(self):
-        self.server.quit()
-        self.server = None
-
-    def test_login(self):
-        baduser = "notarealuser"
-        badpw = "notarealpassword"
-        # Check that bogus credentials cause failure
-        self.assertRaises(nntplib.NNTPError, self.server.login,
-                     user=baduser, password=badpw, usenetrc=False)
-        # FIXME: We should check that correct credentials succeed, but that
-        # would require valid details for some server somewhere to be in the
-        # test suite, I think. Gmane is anonymous, at least as used for the
-        # other tests.
-
     def test_capabilities(self):
         # The server under test implements NNTP version 2 and has a
         # couple of well-known capabilities. Just sanity check that we
@@ -207,6 +211,49 @@
                 # Check that trying starttls when it's already active fails.
                 self.assertRaises(ValueError, self.server.starttls)
 
+    def test_zlogin(self):
+        # This test must be the penultimate because further commands will be
+        # refused.
+        baduser = "notarealuser"
+        badpw = "notarealpassword"
+        # Check that bogus credentials cause failure
+        self.assertRaises(nntplib.NNTPError, self.server.login,
+                          user=baduser, password=badpw, usenetrc=False)
+        # FIXME: We should check that correct credentials succeed, but that
+        # would require valid details for some server somewhere to be in the
+        # test suite, I think. Gmane is anonymous, at least as used for the
+        # other tests.
+
+    def test_zzquit(self):
+        # This test must be called last, hence the name
+        cls = type(self)
+        try:
+            self.server.quit()
+        finally:
+            cls.server = None
+
+    @classmethod
+    def wrap_methods(cls):
+        # Wrap all methods in a transient_internet() exception catcher
+        # XXX put a generic version in test.support?
+        def wrap_meth(meth):
+            @functools.wraps(meth)
+            def wrapped(self):
+                with support.transient_internet(self.NNTP_HOST):
+                    meth(self)
+            return wrapped
+        for name in dir(cls):
+            if not name.startswith('test_'):
+                continue
+            meth = getattr(cls, name)
+            if not isinstance(meth, collections.abc.Callable):
+                continue
+            # Need to use a closure so that meth remains bound to its current
+            # value
+            setattr(cls, name, wrap_meth(meth))
+
+NetworkedNNTPTestsMixin.wrap_methods()
+
 
 class NetworkedNNTPTests(NetworkedNNTPTestsMixin, unittest.TestCase):
     # This server supports STARTTLS (gmane doesn't)
@@ -214,33 +261,34 @@
     GROUP_NAME = 'fr.comp.lang.python'
     GROUP_PAT = 'fr.comp.lang.*'
 
-    def setUp(self):
+    NNTP_CLASS = NNTP
+
+    @classmethod
+    def setUpClass(cls):
         support.requires("network")
-        with support.transient_internet(self.NNTP_HOST):
-            self.server = NNTP(self.NNTP_HOST, timeout=TIMEOUT, usenetrc=False)
+        with support.transient_internet(cls.NNTP_HOST):
+            cls.server = cls.NNTP_CLASS(cls.NNTP_HOST, timeout=TIMEOUT, usenetrc=False)
 
-    def tearDown(self):
-        if self.server is not None:
-            self.server.quit()
+    @classmethod
+    def tearDownClass(cls):
+        if cls.server is not None:
+            cls.server.quit()
 
 
 if _have_ssl:
-    class NetworkedNNTP_SSLTests(NetworkedNNTPTestsMixin, unittest.TestCase):
-        NNTP_HOST = 'snews.gmane.org'
-        GROUP_NAME = 'gmane.comp.python.devel'
-        GROUP_PAT = 'gmane.comp.python.d*'
-
-        def setUp(self):
-            support.requires("network")
-            with support.transient_internet(self.NNTP_HOST):
-                self.server = nntplib.NNTP_SSL(self.NNTP_HOST, timeout=TIMEOUT,
-                                               usenetrc=False)
-
-        def tearDown(self):
-            if self.server is not None:
-                self.server.quit()
+    class NetworkedNNTP_SSLTests(NetworkedNNTPTests):
+
+        # Technical limits for this public NNTP server (see http://www.aioe.org):
+        # "Only two concurrent connections per IP address are allowed and
+        # 400 connections per day are accepted from each IP address."
+
+        NNTP_HOST = 'nntp.aioe.org'
+        GROUP_NAME = 'comp.lang.python'
+        GROUP_PAT = 'comp.lang.*'
+
+        NNTP_CLASS = nntplib.NNTP_SSL
 
-        # Disabled with gmane as it produces too much data
+        # Disabled as it produces too much data
         test_list = None
 
         # Disabled as the connection will already be encrypted.
@@ -765,7 +813,7 @@
 
     def _check_article_body(self, lines):
         self.assertEqual(len(lines), 4)
-        self.assertEqual(lines[-1].decode('utf8'), "-- Signed by André.")
+        self.assertEqual(lines[-1].decode('utf-8'), "-- Signed by André.")
         self.assertEqual(lines[-2], b"")
         self.assertEqual(lines[-3], b".Here is a dot-starting line.")
         self.assertEqual(lines[-4], b"This is just a test article.")

Modified: python/branches/pep-3151/Lib/test/test_normalization.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_normalization.py	(original)
+++ python/branches/pep-3151/Lib/test/test_normalization.py	Sat Feb 26 08:16:32 2011
@@ -45,6 +45,7 @@
                                         check=check_version)
         except (IOError, HTTPException):
             self.skipTest("Could not retrieve " + TESTDATAURL)
+        self.addCleanup(testdata.close)
         for line in testdata:
             if '#' in line:
                 line = line.split('#')[0]
@@ -54,9 +55,6 @@
             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:

Modified: python/branches/pep-3151/Lib/test/test_ntpath.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_ntpath.py	(original)
+++ python/branches/pep-3151/Lib/test/test_ntpath.py	Sat Feb 26 08:16:32 2011
@@ -248,7 +248,7 @@
             self.assertFalse(ntpath.sameopenfile(tf1.fileno(), tf2.fileno()))
             # Make sure invalid values don't cause issues on win32
             if sys.platform == "win32":
-                with self.assertRaises(ValueError):
+                with self.assertRaises(OSError):
                     # Invalid file descriptors shouldn't display assert
                     # dialogs (#4804)
                     ntpath.sameopenfile(-1, -1)

Modified: python/branches/pep-3151/Lib/test/test_opcodes.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_opcodes.py	(original)
+++ python/branches/pep-3151/Lib/test/test_opcodes.py	Sat Feb 26 08:16:32 2011
@@ -68,35 +68,35 @@
 
         f = eval('lambda: None')
         g = eval('lambda: None')
-        self.assertNotEquals(f, g)
+        self.assertNotEqual(f, g)
 
         f = eval('lambda a: a')
         g = eval('lambda a: a')
-        self.assertNotEquals(f, g)
+        self.assertNotEqual(f, g)
 
         f = eval('lambda a=1: a')
         g = eval('lambda a=1: a')
-        self.assertNotEquals(f, g)
+        self.assertNotEqual(f, g)
 
         f = eval('lambda: 0')
         g = eval('lambda: 1')
-        self.assertNotEquals(f, g)
+        self.assertNotEqual(f, g)
 
         f = eval('lambda: None')
         g = eval('lambda a: None')
-        self.assertNotEquals(f, g)
+        self.assertNotEqual(f, g)
 
         f = eval('lambda a: None')
         g = eval('lambda b: None')
-        self.assertNotEquals(f, g)
+        self.assertNotEqual(f, g)
 
         f = eval('lambda a: None')
         g = eval('lambda a=None: None')
-        self.assertNotEquals(f, g)
+        self.assertNotEqual(f, g)
 
         f = eval('lambda a=0: None')
         g = eval('lambda a=1: None')
-        self.assertNotEquals(f, g)
+        self.assertNotEqual(f, g)
 
     def test_modulo_of_string_subclasses(self):
         class MyString(str):

Modified: python/branches/pep-3151/Lib/test/test_operator.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_operator.py	(original)
+++ python/branches/pep-3151/Lib/test/test_operator.py	Sat Feb 26 08:16:32 2011
@@ -360,12 +360,12 @@
         f = operator.methodcaller('foo')
         self.assertRaises(IndexError, f, a)
         f = operator.methodcaller('foo', 1, 2)
-        self.assertEquals(f(a), 3)
+        self.assertEqual(f(a), 3)
         f = operator.methodcaller('bar')
-        self.assertEquals(f(a), 42)
+        self.assertEqual(f(a), 42)
         self.assertRaises(TypeError, f, a, a)
         f = operator.methodcaller('bar', f=5)
-        self.assertEquals(f(a), 5)
+        self.assertEqual(f(a), 5)
 
     def test_inplace(self):
         class C(object):

Modified: python/branches/pep-3151/Lib/test/test_optparse.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_optparse.py	(original)
+++ python/branches/pep-3151/Lib/test/test_optparse.py	Sat Feb 26 08:16:32 2011
@@ -423,13 +423,13 @@
 
     def test_str_aliases_string(self):
         self.parser.add_option("-s", type="str")
-        self.assertEquals(self.parser.get_option("-s").type, "string")
+        self.assertEqual(self.parser.get_option("-s").type, "string")
 
     def test_type_object(self):
         self.parser.add_option("-s", type=str)
-        self.assertEquals(self.parser.get_option("-s").type, "string")
+        self.assertEqual(self.parser.get_option("-s").type, "string")
         self.parser.add_option("-x", type=int)
-        self.assertEquals(self.parser.get_option("-x").type, "int")
+        self.assertEqual(self.parser.get_option("-x").type, "int")
 
 
 # Custom type for testing processing of default values.

Modified: python/branches/pep-3151/Lib/test/test_os.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_os.py	(original)
+++ python/branches/pep-3151/Lib/test/test_os.py	Sat Feb 26 08:16:32 2011
@@ -15,6 +15,13 @@
 import contextlib
 import mmap
 import uuid
+import asyncore
+import asynchat
+import socket
+try:
+    import threading
+except ImportError:
+    threading = None
 
 # Detect whether we're on a Linux system that uses the (now outdated
 # and unmaintained) linuxthreads threading library.  There's an issue
@@ -229,8 +236,8 @@
         result = os.stat(fname)
 
         # Make sure direct access works
-        self.assertEquals(result[stat.ST_SIZE], 3)
-        self.assertEquals(result.st_size, 3)
+        self.assertEqual(result[stat.ST_SIZE], 3)
+        self.assertEqual(result.st_size, 3)
 
         # Make sure all the attributes are there
         members = dir(result)
@@ -241,7 +248,7 @@
                     def trunc(x): return int(x)
                 else:
                     def trunc(x): return x
-                self.assertEquals(trunc(getattr(result, attr)),
+                self.assertEqual(trunc(getattr(result, attr)),
                                   result[getattr(stat, name)])
                 self.assertIn(attr, members)
 
@@ -305,13 +312,13 @@
                 return
 
         # Make sure direct access works
-        self.assertEquals(result.f_bfree, result[3])
+        self.assertEqual(result.f_bfree, result[3])
 
         # Make sure all the attributes are there.
         members = ('bsize', 'frsize', 'blocks', 'bfree', 'bavail', 'files',
                     'ffree', 'favail', 'flag', 'namemax')
         for value, member in enumerate(members):
-            self.assertEquals(getattr(result, 'f_' + member), result[value])
+            self.assertEqual(getattr(result, 'f_' + member), result[value])
 
         # Make sure that assignment really fails
         try:
@@ -346,7 +353,7 @@
         # time stamps in stat, but not in utime.
         os.utime(support.TESTFN, (st.st_atime, int(st.st_mtime-delta)))
         st2 = os.stat(support.TESTFN)
-        self.assertEquals(st2.st_mtime, int(st.st_mtime-delta))
+        self.assertEqual(st2.st_mtime, int(st.st_mtime-delta))
 
     # Restrict test to Win32, since there is no guarantee other
     # systems support centiseconds
@@ -363,7 +370,12 @@
             def test_1565150(self):
                 t1 = 1159195039.25
                 os.utime(self.fname, (t1, t1))
-                self.assertEquals(os.stat(self.fname).st_mtime, t1)
+                self.assertEqual(os.stat(self.fname).st_mtime, t1)
+
+            def test_large_time(self):
+                t1 = 5000000000 # some day in 2128
+                os.utime(self.fname, (t1, t1))
+                self.assertEqual(os.stat(self.fname).st_mtime, t1)
 
         def test_1686475(self):
             # Verify that an open file can be stat'ed
@@ -408,24 +420,24 @@
             os.environ.update(HELLO="World")
             with os.popen("/bin/sh -c 'echo $HELLO'") as popen:
                 value = popen.read().strip()
-                self.assertEquals(value, "World")
+                self.assertEqual(value, "World")
 
     def test_os_popen_iter(self):
         if os.path.exists("/bin/sh"):
             with os.popen(
                 "/bin/sh -c 'echo \"line1\nline2\nline3\"'") as popen:
                 it = iter(popen)
-                self.assertEquals(next(it), "line1\n")
-                self.assertEquals(next(it), "line2\n")
-                self.assertEquals(next(it), "line3\n")
+                self.assertEqual(next(it), "line1\n")
+                self.assertEqual(next(it), "line2\n")
+                self.assertEqual(next(it), "line3\n")
                 self.assertRaises(StopIteration, next, it)
 
     # Verify environ keys and values from the OS are of the
     # correct str type.
     def test_keyvalue_types(self):
         for key, val in os.environ.items():
-            self.assertEquals(type(key), str)
-            self.assertEquals(type(val), str)
+            self.assertEqual(type(key), str)
+            self.assertEqual(type(val), str)
 
     def test_items(self):
         for key, value in self._reference().items():
@@ -493,15 +505,15 @@
                 sys.getfilesystemencoding(),)
             self.skipTest(msg)
         os.environ['unicode'] = value
-        self.assertEquals(os.environ['unicode'], value)
-        self.assertEquals(os.environb[b'unicode'], value_bytes)
+        self.assertEqual(os.environ['unicode'], value)
+        self.assertEqual(os.environb[b'unicode'], value_bytes)
 
         # os.environb -> os.environ
         value = b'\xff'
         os.environb[b'bytes'] = value
-        self.assertEquals(os.environb[b'bytes'], value)
+        self.assertEqual(os.environb[b'bytes'], value)
         value_str = value.decode(sys.getfilesystemencoding(), 'surrogateescape')
-        self.assertEquals(os.environ['bytes'], value_str)
+        self.assertEqual(os.environ['bytes'], value_str)
 
 class WalkTests(unittest.TestCase):
     """Tests for os.walk()."""
@@ -630,6 +642,28 @@
                             'dir5', 'dir6')
         os.makedirs(path)
 
+    def test_exist_ok_existing_directory(self):
+        path = os.path.join(support.TESTFN, 'dir1')
+        mode = 0o777
+        old_mask = os.umask(0o022)
+        os.makedirs(path, mode)
+        self.assertRaises(OSError, os.makedirs, path, mode)
+        self.assertRaises(OSError, os.makedirs, path, mode, exist_ok=False)
+        self.assertRaises(OSError, os.makedirs, path, 0o776, exist_ok=True)
+        os.makedirs(path, mode=mode, exist_ok=True)
+        os.umask(old_mask)
+
+    def test_exist_ok_existing_regular_file(self):
+        base = support.TESTFN
+        path = os.path.join(support.TESTFN, 'dir1')
+        f = open(path, 'w')
+        f.write('abc')
+        f.close()
+        self.assertRaises(OSError, os.makedirs, path)
+        self.assertRaises(OSError, os.makedirs, path, exist_ok=False)
+        self.assertRaises(OSError, os.makedirs, path, exist_ok=True)
+        os.remove(path)
+
     def tearDown(self):
         path = os.path.join(support.TESTFN, 'dir1', 'dir2', 'dir3',
                             'dir4', 'dir5', 'dir6')
@@ -860,6 +894,42 @@
         if hasattr(os, "write"):
             self.check(os.write, b" ")
 
+
+class LinkTests(unittest.TestCase):
+    def setUp(self):
+        self.file1 = support.TESTFN
+        self.file2 = os.path.join(support.TESTFN + "2")
+
+    def tearDown(self):
+        for file in (self.file1, self.file2):
+            if os.path.exists(file):
+                os.unlink(file)
+
+    def _test_link(self, file1, file2):
+        with open(file1, "w") as f1:
+            f1.write("test")
+
+        os.link(file1, file2)
+        with open(file1, "r") as f1, open(file2, "r") as f2:
+            self.assertTrue(os.path.sameopenfile(f1.fileno(), f2.fileno()))
+
+    def test_link(self):
+        self._test_link(self.file1, self.file2)
+
+    def test_link_bytes(self):
+        self._test_link(bytes(self.file1, sys.getfilesystemencoding()),
+                        bytes(self.file2, sys.getfilesystemencoding()))
+
+    def test_unicode_name(self):
+        try:
+            os.fsencode("\xf1")
+        except UnicodeError:
+            raise unittest.SkipTest("Unable to encode for this platform.")
+
+        self.file1 += "\xf1"
+        self.file2 = self.file1 + "2"
+        self._test_link(self.file1, self.file2)
+
 if sys.platform != 'win32':
     class Win32ErrorTests(unittest.TestCase):
         pass
@@ -958,7 +1028,7 @@
         def test_listdir(self):
             expected = self.unicodefn
             found = set(os.listdir(self.dir))
-            self.assertEquals(found, expected)
+            self.assertEqual(found, expected)
 
         def test_open(self):
             for fn in self.unicodefn:
@@ -1048,13 +1118,15 @@
                                 "win_console_handler.py"), tagname],
                    creationflags=subprocess.CREATE_NEW_PROCESS_GROUP)
         # Let the interpreter startup before we send signals. See #3137.
-        count, max = 0, 20
+        count, max = 0, 100
         while count < max and proc.poll() is None:
             if m[0] == 1:
                 break
-            time.sleep(0.5)
+            time.sleep(0.1)
             count += 1
         else:
+            # Forcefully kill the process if we weren't able to signal it.
+            os.kill(proc.pid, signal.SIGINT)
             self.fail("Subprocess didn't finish initialization")
         os.kill(proc.pid, event)
         # proc.send_signal(event) could also be done here.
@@ -1088,12 +1160,6 @@
         self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT")
 
 
-def skipUnlessWindows6(test):
-    if (hasattr(sys, 'getwindowsversion')
-        and sys.getwindowsversion().major >= 6):
-        return test
-    return unittest.skip("Requires Windows Vista or later")(test)
-
 @unittest.skipUnless(sys.platform == "win32", "Win32 specific tests")
 @support.skip_unless_symlink
 class Win32SymlinkTests(unittest.TestCase):
@@ -1168,8 +1234,8 @@
 
 class FSEncodingTests(unittest.TestCase):
     def test_nop(self):
-        self.assertEquals(os.fsencode(b'abc\xff'), b'abc\xff')
-        self.assertEquals(os.fsdecode('abc\u0141'), 'abc\u0141')
+        self.assertEqual(os.fsencode(b'abc\xff'), b'abc\xff')
+        self.assertEqual(os.fsdecode('abc\u0141'), 'abc\u0141')
 
     def test_identity(self):
         # assert fsdecode(fsencode(x)) == x
@@ -1178,7 +1244,7 @@
                 bytesfn = os.fsencode(fn)
             except UnicodeEncodeError:
                 continue
-            self.assertEquals(os.fsdecode(bytesfn), fn)
+            self.assertEqual(os.fsdecode(bytesfn), fn)
 
 
 class PidTests(unittest.TestCase):
@@ -1202,6 +1268,271 @@
         self.assertNotEqual(len(user_name), 0)
 
 
+ at unittest.skipUnless(hasattr(os, 'getpriority') and hasattr(os, 'setpriority'),
+                     "needs os.getpriority and os.setpriority")
+class ProgramPriorityTests(unittest.TestCase):
+    """Tests for os.getpriority() and os.setpriority()."""
+
+    def test_set_get_priority(self):
+        base = os.getpriority(os.PRIO_PROCESS, os.getpid())
+        os.setpriority(os.PRIO_PROCESS, os.getpid(), base + 1)
+        try:
+            self.assertEqual(os.getpriority(os.PRIO_PROCESS, os.getpid()), base + 1)
+        finally:
+            try:
+                os.setpriority(os.PRIO_PROCESS, os.getpid(), base)
+            except OSError as err:
+                if err.errno != errno.EACCES:
+                    raise
+
+
+class SendfileTestServer(asyncore.dispatcher, threading.Thread):
+
+    class Handler(asynchat.async_chat):
+
+        def __init__(self, conn):
+            asynchat.async_chat.__init__(self, conn)
+            self.in_buffer = []
+            self.closed = False
+            self.push(b"220 ready\r\n")
+
+        def handle_read(self):
+            data = self.recv(4096)
+            self.in_buffer.append(data)
+
+        def get_data(self):
+            return b''.join(self.in_buffer)
+
+        def handle_close(self):
+            self.close()
+            self.closed = True
+
+        def handle_error(self):
+            raise
+
+    def __init__(self, address):
+        threading.Thread.__init__(self)
+        asyncore.dispatcher.__init__(self)
+        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
+        self.bind(address)
+        self.listen(5)
+        self.host, self.port = self.socket.getsockname()[:2]
+        self.handler_instance = None
+        self._active = False
+        self._active_lock = threading.Lock()
+
+    # --- public API
+
+    @property
+    def running(self):
+        return self._active
+
+    def start(self):
+        assert not self.running
+        self.__flag = threading.Event()
+        threading.Thread.start(self)
+        self.__flag.wait()
+
+    def stop(self):
+        assert self.running
+        self._active = False
+        self.join()
+
+    def wait(self):
+        # wait for handler connection to be closed, then stop the server
+        while not getattr(self.handler_instance, "closed", True):
+            time.sleep(0.001)
+        self.stop()
+
+    # --- internals
+
+    def run(self):
+        self._active = True
+        self.__flag.set()
+        while self._active and asyncore.socket_map:
+            self._active_lock.acquire()
+            asyncore.loop(timeout=0.001, count=1)
+            self._active_lock.release()
+        asyncore.close_all()
+
+    def handle_accept(self):
+        conn, addr = self.accept()
+        self.handler_instance = self.Handler(conn)
+
+    def handle_connect(self):
+        self.close()
+    handle_read = handle_connect
+
+    def writable(self):
+        return 0
+
+    def handle_error(self):
+        raise
+
+
+ at unittest.skipUnless(threading is not None, "test needs threading module")
+ at unittest.skipUnless(hasattr(os, 'sendfile'), "test needs os.sendfile()")
+class TestSendfile(unittest.TestCase):
+
+    DATA = b"12345abcde" * 1024 * 1024  # 10 Mb
+    SUPPORT_HEADERS_TRAILERS = not sys.platform.startswith("linux") and \
+                               not sys.platform.startswith("solaris") and \
+                               not sys.platform.startswith("sunos")
+
+    @classmethod
+    def setUpClass(cls):
+        with open(support.TESTFN, "wb") as f:
+            f.write(cls.DATA)
+
+    @classmethod
+    def tearDownClass(cls):
+        support.unlink(support.TESTFN)
+
+    def setUp(self):
+        self.server = SendfileTestServer((support.HOST, 0))
+        self.server.start()
+        self.client = socket.socket()
+        self.client.connect((self.server.host, self.server.port))
+        self.client.settimeout(1)
+        # synchronize by waiting for "220 ready" response
+        self.client.recv(1024)
+        self.sockno = self.client.fileno()
+        self.file = open(support.TESTFN, 'rb')
+        self.fileno = self.file.fileno()
+
+    def tearDown(self):
+        self.file.close()
+        self.client.close()
+        if self.server.running:
+            self.server.stop()
+
+    def sendfile_wrapper(self, sock, file, offset, nbytes, headers=[], trailers=[]):
+        """A higher level wrapper representing how an application is
+        supposed to use sendfile().
+        """
+        while 1:
+            try:
+                if self.SUPPORT_HEADERS_TRAILERS:
+                    return os.sendfile(sock, file, offset, nbytes, headers,
+                                       trailers)
+                else:
+                    return os.sendfile(sock, file, offset, nbytes)
+            except OSError as err:
+                if err.errno == errno.ECONNRESET:
+                    # disconnected
+                    raise
+                elif err.errno in (errno.EAGAIN, errno.EBUSY):
+                    # we have to retry send data
+                    continue
+                else:
+                    raise
+
+    def test_send_whole_file(self):
+        # normal send
+        total_sent = 0
+        offset = 0
+        nbytes = 4096
+        while 1:
+            sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
+            if sent == 0:
+                break
+            offset += sent
+            total_sent += sent
+            self.assertTrue(sent <= nbytes)
+            self.assertEqual(offset, total_sent)
+
+        self.assertEqual(total_sent, len(self.DATA))
+        self.client.close()
+        self.server.wait()
+        data = self.server.handler_instance.get_data()
+        self.assertEqual(hash(data), hash(self.DATA))
+
+    def test_send_at_certain_offset(self):
+        # start sending a file at a certain offset
+        total_sent = 0
+        offset = len(self.DATA) / 2
+        nbytes = 4096
+        while 1:
+            sent = self.sendfile_wrapper(self.sockno, self.fileno, offset, nbytes)
+            if sent == 0:
+                break
+            offset += sent
+            total_sent += sent
+            self.assertTrue(sent <= nbytes)
+
+        self.client.close()
+        self.server.wait()
+        data = self.server.handler_instance.get_data()
+        expected = self.DATA[int(len(self.DATA) / 2):]
+        self.assertEqual(total_sent, len(expected))
+        self.assertEqual(hash(data), hash(expected))
+
+    def test_offset_overflow(self):
+        # specify an offset > file size
+        offset = len(self.DATA) + 4096
+        sent = os.sendfile(self.sockno, self.fileno, offset, 4096)
+        self.assertEqual(sent, 0)
+        self.client.close()
+        self.server.wait()
+        data = self.server.handler_instance.get_data()
+        self.assertEqual(data, b'')
+
+    def test_invalid_offset(self):
+        with self.assertRaises(OSError) as cm:
+            os.sendfile(self.sockno, self.fileno, -1, 4096)
+        self.assertEqual(cm.exception.errno, errno.EINVAL)
+
+    # --- headers / trailers tests
+
+    if SUPPORT_HEADERS_TRAILERS:
+
+        def test_headers(self):
+            total_sent = 0
+            sent = os.sendfile(self.sockno, self.fileno, 0, 4096,
+                               headers=[b"x" * 512])
+            total_sent += sent
+            offset = 4096
+            nbytes = 4096
+            while 1:
+                sent = self.sendfile_wrapper(self.sockno, self.fileno,
+                                                     offset, nbytes)
+                if sent == 0:
+                    break
+                total_sent += sent
+                offset += sent
+
+            expected_data = b"x" * 512 + self.DATA
+            self.assertEqual(total_sent, len(expected_data))
+            self.client.close()
+            self.server.wait()
+            data = self.server.handler_instance.get_data()
+            self.assertEqual(hash(data), hash(expected_data))
+
+        def test_trailers(self):
+            TESTFN2 = support.TESTFN + "2"
+            f = open(TESTFN2, 'wb')
+            f.write(b"abcde")
+            f.close()
+            f = open(TESTFN2, 'rb')
+            try:
+                os.sendfile(self.sockno, f.fileno(), 0, 4096, trailers=[b"12345"])
+                self.client.close()
+                self.server.wait()
+                data = self.server.handler_instance.get_data()
+                self.assertEqual(data, b"abcde12345")
+            finally:
+                os.remove(TESTFN2)
+
+        if hasattr(os, "SF_NODISKIO"):
+            def test_flags(self):
+                try:
+                    os.sendfile(self.sockno, self.fileno, 0, 4096,
+                                flags=os.SF_NODISKIO)
+                except OSError as err:
+                    if err.errno not in (errno.EBUSY, errno.EAGAIN):
+                        raise
+
+
 def test_main():
     support.run_unittest(
         FileTests,
@@ -1221,6 +1552,9 @@
         FSEncodingTests,
         PidTests,
         LoginTests,
+        LinkTests,
+        TestSendfile,
+        ProgramPriorityTests,
     )
 
 if __name__ == "__main__":

Modified: python/branches/pep-3151/Lib/test/test_parser.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_parser.py	(original)
+++ python/branches/pep-3151/Lib/test/test_parser.py	Sat Feb 26 08:16:32 2011
@@ -20,8 +20,8 @@
         except parser.ParserError as why:
             self.fail("could not roundtrip %r: %s" % (s, why))
 
-        self.assertEquals(t, st2.totuple(),
-                          "could not re-generate syntax tree")
+        self.assertEqual(t, st2.totuple(),
+                         "could not re-generate syntax tree")
 
     def check_expr(self, s):
         self.roundtrip(parser.expr, s)
@@ -498,14 +498,14 @@
     def test_compile_expr(self):
         st = parser.expr('2 + 3')
         code = parser.compilest(st)
-        self.assertEquals(eval(code), 5)
+        self.assertEqual(eval(code), 5)
 
     def test_compile_suite(self):
         st = parser.suite('x = 2; y = x + 3')
         code = parser.compilest(st)
         globs = {}
         exec(code, globs)
-        self.assertEquals(globs['y'], 5)
+        self.assertEqual(globs['y'], 5)
 
     def test_compile_error(self):
         st = parser.suite('1 = 3 + 4')
@@ -560,36 +560,36 @@
         st3_copy = parser.expr('list(x**3 for x in range(20))')
 
         # exercise fast path for object identity
-        self.assertEquals(st1 == st1, True)
-        self.assertEquals(st2 == st2, True)
-        self.assertEquals(st3 == st3, True)
+        self.assertEqual(st1 == st1, True)
+        self.assertEqual(st2 == st2, True)
+        self.assertEqual(st3 == st3, True)
         # slow path equality
         self.assertEqual(st1, st1_copy)
         self.assertEqual(st2, st2_copy)
         self.assertEqual(st3, st3_copy)
-        self.assertEquals(st1 == st2, False)
-        self.assertEquals(st1 == st3, False)
-        self.assertEquals(st2 == st3, False)
-        self.assertEquals(st1 != st1, False)
-        self.assertEquals(st2 != st2, False)
-        self.assertEquals(st3 != st3, False)
-        self.assertEquals(st1 != st1_copy, False)
-        self.assertEquals(st2 != st2_copy, False)
-        self.assertEquals(st3 != st3_copy, False)
-        self.assertEquals(st2 != st1, True)
-        self.assertEquals(st1 != st3, True)
-        self.assertEquals(st3 != st2, True)
+        self.assertEqual(st1 == st2, False)
+        self.assertEqual(st1 == st3, False)
+        self.assertEqual(st2 == st3, False)
+        self.assertEqual(st1 != st1, False)
+        self.assertEqual(st2 != st2, False)
+        self.assertEqual(st3 != st3, False)
+        self.assertEqual(st1 != st1_copy, False)
+        self.assertEqual(st2 != st2_copy, False)
+        self.assertEqual(st3 != st3_copy, False)
+        self.assertEqual(st2 != st1, True)
+        self.assertEqual(st1 != st3, True)
+        self.assertEqual(st3 != st2, True)
         # we don't particularly care what the ordering is;  just that
         # it's usable and self-consistent
-        self.assertEquals(st1 < st2, not (st2 <= st1))
-        self.assertEquals(st1 < st3, not (st3 <= st1))
-        self.assertEquals(st2 < st3, not (st3 <= st2))
-        self.assertEquals(st1 < st2, st2 > st1)
-        self.assertEquals(st1 < st3, st3 > st1)
-        self.assertEquals(st2 < st3, st3 > st2)
-        self.assertEquals(st1 <= st2, st2 >= st1)
-        self.assertEquals(st3 <= st1, st1 >= st3)
-        self.assertEquals(st2 <= st3, st3 >= st2)
+        self.assertEqual(st1 < st2, not (st2 <= st1))
+        self.assertEqual(st1 < st3, not (st3 <= st1))
+        self.assertEqual(st2 < st3, not (st3 <= st2))
+        self.assertEqual(st1 < st2, st2 > st1)
+        self.assertEqual(st1 < st3, st3 > st1)
+        self.assertEqual(st2 < st3, st3 > st2)
+        self.assertEqual(st1 <= st2, st2 >= st1)
+        self.assertEqual(st3 <= st1, st1 >= st3)
+        self.assertEqual(st2 <= st3, st3 >= st2)
         # transitivity
         bottom = min(st1, st2, st3)
         top = max(st1, st2, st3)
@@ -604,8 +604,8 @@
         self.assertTrue(mid <= mid)
         self.assertTrue(top <= top)
         # interaction with other types
-        self.assertEquals(st1 == 1588.602459, False)
-        self.assertEquals('spanish armada' != st2, True)
+        self.assertEqual(st1 == 1588.602459, False)
+        self.assertEqual('spanish armada' != st2, True)
         self.assertRaises(TypeError, operator.ge, st3, None)
         self.assertRaises(TypeError, operator.le, False, st1)
         self.assertRaises(TypeError, operator.lt, st1, 1815)

Modified: python/branches/pep-3151/Lib/test/test_pdb.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pdb.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pdb.py	Sat Feb 26 08:16:32 2011
@@ -20,16 +20,19 @@
     def __enter__(self):
         self.real_stdin = sys.stdin
         sys.stdin = _FakeInput(self.input)
+        self.orig_trace = sys.gettrace() if hasattr(sys, 'gettrace') else None
 
     def __exit__(self, *exc):
         sys.stdin = self.real_stdin
+        if self.orig_trace:
+            sys.settrace(self.orig_trace)
 
 
 def test_pdb_displayhook():
     """This tests the custom displayhook for pdb.
 
     >>> def test_function(foo, bar):
-    ...     import pdb; pdb.Pdb().set_trace()
+    ...     import pdb; pdb.Pdb(nosigint=True).set_trace()
     ...     pass
 
     >>> with PdbTestInput([
@@ -69,7 +72,7 @@
     ...     return foo.upper()
 
     >>> def test_function():
-    ...     import pdb; pdb.Pdb().set_trace()
+    ...     import pdb; pdb.Pdb(nosigint=True).set_trace()
     ...     ret = test_function_2('baz')
     ...     print(ret)
 
@@ -168,7 +171,7 @@
     """Test basic commands related to breakpoints.
 
     >>> def test_function():
-    ...     import pdb; pdb.Pdb().set_trace()
+    ...     import pdb; pdb.Pdb(nosigint=True).set_trace()
     ...     print(1)
     ...     print(2)
     ...     print(3)
@@ -192,6 +195,9 @@
     ...     'ignore 1 10',
     ...     'condition 1 1 < 2',
     ...     'break 4',
+    ...     'break 4',
+    ...     'break',
+    ...     'clear 3',
     ...     'break',
     ...     'condition 1',
     ...     'enable 1',
@@ -220,6 +226,17 @@
     New condition set for breakpoint 1.
     (Pdb) break 4
     Breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
+    (Pdb) break 4
+    Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
+    (Pdb) break
+    Num Type         Disp Enb   Where
+    1   breakpoint   keep no    at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
+            stop only if 1 < 2
+            ignore next 10 hits
+    2   breakpoint   keep yes   at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
+    3   breakpoint   keep yes   at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
+    (Pdb) clear 3
+    Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
     (Pdb) break
     Num Type         Disp Enb   Where
     1   breakpoint   keep no    at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:3
@@ -244,10 +261,10 @@
     Clear all breaks? y
     Deleted breakpoint 2 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:4
     (Pdb) tbreak 5
-    Breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
+    Breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
     (Pdb) continue
     2
-    Deleted breakpoint 3 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
+    Deleted breakpoint 4 at <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>:5
     > <doctest test.test_pdb.test_pdb_breakpoint_commands[0]>(5)test_function()
     -> print(3)
     (Pdb) break
@@ -283,7 +300,7 @@
     ...     return foo
 
     >>> def test_function():
-    ...     import pdb; pdb.Pdb().set_trace()
+    ...     import pdb; pdb.Pdb(nosigint=True).set_trace()
     ...     ret = test_function_2('baz')
 
     >>> with PdbTestInput([  # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
@@ -306,7 +323,7 @@
     -> ret = test_function_2('baz')
     (Pdb) list
       1         def test_function():
-      2             import pdb; pdb.Pdb().set_trace()
+      2             import pdb; pdb.Pdb(nosigint=True).set_trace()
       3  ->         ret = test_function_2('baz')
     [EOF]
     (Pdb) step
@@ -369,7 +386,7 @@
     ...         print('Exception!')
 
     >>> def test_function():
-    ...     import pdb; pdb.Pdb().set_trace()
+    ...     import pdb; pdb.Pdb(nosigint=True).set_trace()
     ...     test_function_2()
     ...     print('Not reached.')
 
@@ -402,7 +419,7 @@
     -> 1/0
     (Pdb) list
       1         def test_function():
-      2             import pdb; pdb.Pdb().set_trace()
+      2             import pdb; pdb.Pdb(nosigint=True).set_trace()
       3  ->         test_function_2()
       4             print('Not reached.')
     [EOF]
@@ -426,7 +443,7 @@
 
     >>> def skip_module():
     ...     import string
-    ...     import pdb; pdb.Pdb(skip=['stri*']).set_trace()
+    ...     import pdb; pdb.Pdb(skip=['stri*'], nosigint=True).set_trace()
     ...     string.capwords('FOO')
 
     >>> with PdbTestInput([
@@ -455,7 +472,7 @@
     >>> def skip_module():
     ...     def callback():
     ...         return None
-    ...     import pdb; pdb.Pdb(skip=['module_to_skip*']).set_trace()
+    ...     import pdb; pdb.Pdb(skip=['module_to_skip*'], nosigint=True).set_trace()
     ...     mod.foo_pony(callback)
 
     >>> with PdbTestInput([
@@ -496,7 +513,7 @@
     """Test that "continue" and "next" work properly in bottom frame (issue #5294).
 
     >>> def test_function():
-    ...     import pdb, sys; inst = pdb.Pdb()
+    ...     import pdb, sys; inst = pdb.Pdb(nosigint=True)
     ...     inst.set_trace()
     ...     inst.botframe = sys._getframe()  # hackery to get the right botframe
     ...     print(1)
@@ -536,7 +553,8 @@
 
 def pdb_invoke(method, arg):
     """Run pdb.method(arg)."""
-    import pdb; getattr(pdb, method)(arg)
+    import pdb
+    getattr(pdb.Pdb(nosigint=True), method)(arg)
 
 
 def test_pdb_run_with_incorrect_argument():

Modified: python/branches/pep-3151/Lib/test/test_pep247.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pep247.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pep247.py	Sat Feb 26 08:16:32 2011
@@ -30,23 +30,23 @@
             obj3 = cls()
             obj3.update(b'string')
             h2 = obj3.digest()
-        self.assertEquals(h1, h2)
+        self.assertEqual(h1, h2)
         self.assertTrue(hasattr(obj1, 'digest_size'))
 
         if digest_size is not None:
-            self.assertEquals(obj1.digest_size, digest_size)
+            self.assertEqual(obj1.digest_size, digest_size)
 
-        self.assertEquals(obj1.digest_size, len(h1))
+        self.assertEqual(obj1.digest_size, len(h1))
         obj1.update(b'string')
         obj_copy = obj1.copy()
-        self.assertEquals(obj1.digest(), obj_copy.digest())
-        self.assertEquals(obj1.hexdigest(), obj_copy.hexdigest())
+        self.assertEqual(obj1.digest(), obj_copy.digest())
+        self.assertEqual(obj1.hexdigest(), obj_copy.hexdigest())
 
         digest, hexdigest = obj1.digest(), obj1.hexdigest()
         hd2 = ""
         for byte in digest:
             hd2 += '%02x' % byte
-        self.assertEquals(hd2, hexdigest)
+        self.assertEqual(hd2, hexdigest)
 
     def test_md5(self):
         self.check_object(md5, None, None)

Modified: python/branches/pep-3151/Lib/test/test_pep263.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pep263.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pep263.py	Sat Feb 26 08:16:32 2011
@@ -26,7 +26,7 @@
         try:
             compile(b"# coding: cp932\nprint '\x94\x4e'", "dummy", "exec")
         except SyntaxError as v:
-            self.assertEquals(v.text, "print '\u5e74'\n")
+            self.assertEqual(v.text, "print '\u5e74'\n")
         else:
             self.fail()
 
@@ -34,7 +34,7 @@
         c = compile("# coding=latin-1\n\u00c6 = '\u00c6'", "dummy", "exec")
         d = {}
         exec(c, d)
-        self.assertEquals(d['\xc6'], '\xc6')
+        self.assertEqual(d['\xc6'], '\xc6')
 
     def test_issue3297(self):
         c = compile("a, b = '\U0001010F', '\\U0001010F'", "dummy", "exec")

Modified: python/branches/pep-3151/Lib/test/test_pep3120.py
==============================================================================
Binary files. No diff available.

Modified: python/branches/pep-3151/Lib/test/test_pep3131.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pep3131.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pep3131.py	Sat Feb 26 08:16:32 2011
@@ -8,15 +8,15 @@
             ä = 1
             µ = 2 # this is a compatibility character
             蟒 = 3
-        self.assertEquals(getattr(T, "\xe4"), 1)
-        self.assertEquals(getattr(T, "\u03bc"), 2)
-        self.assertEquals(getattr(T, '\u87d2'), 3)
+        self.assertEqual(getattr(T, "\xe4"), 1)
+        self.assertEqual(getattr(T, "\u03bc"), 2)
+        self.assertEqual(getattr(T, '\u87d2'), 3)
 
     def test_invalid(self):
         try:
             from test import badsyntax_3131
         except SyntaxError as s:
-            self.assertEquals(str(s),
+            self.assertEqual(str(s),
               "invalid character in identifier (badsyntax_3131.py, line 2)")
         else:
             self.fail("expected exception didn't occur")

Modified: python/branches/pep-3151/Lib/test/test_pickle.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pickle.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pickle.py	Sat Feb 26 08:16:32 2011
@@ -31,9 +31,9 @@
         f.seek(0)
         return bytes(f.read())
 
-    def loads(self, buf):
+    def loads(self, buf, **kwds):
         f = io.BytesIO(buf)
-        u = self.unpickler(f)
+        u = self.unpickler(f, **kwds)
         return u.load()
 
 
@@ -45,8 +45,8 @@
     def dumps(self, arg, proto=None):
         return pickle.dumps(arg, proto)
 
-    def loads(self, buf):
-        return pickle.loads(buf)
+    def loads(self, buf, **kwds):
+        return pickle.loads(buf, **kwds)
 
 
 class PyPersPicklerTests(AbstractPersistentPicklerTests):
@@ -64,12 +64,12 @@
         f.seek(0)
         return f.read()
 
-    def loads(self, buf):
+    def loads(self, buf, **kwds):
         class PersUnpickler(self.unpickler):
             def persistent_load(subself, obj):
                 return self.persistent_load(obj)
         f = io.BytesIO(buf)
-        u = PersUnpickler(f)
+        u = PersUnpickler(f, **kwds)
         return u.load()
 
 

Modified: python/branches/pep-3151/Lib/test/test_pickletools.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pickletools.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pickletools.py	Sat Feb 26 08:16:32 2011
@@ -9,8 +9,8 @@
     def dumps(self, arg, proto=None):
         return pickletools.optimize(pickle.dumps(arg, proto))
 
-    def loads(self, buf):
-        return pickle.loads(buf)
+    def loads(self, buf, **kwds):
+        return pickle.loads(buf, **kwds)
 
     # Test relies on precise output of dumps()
     test_pickle_to_2x = None

Modified: python/branches/pep-3151/Lib/test/test_platform.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_platform.py	(original)
+++ python/branches/pep-3151/Lib/test/test_platform.py	Sat Feb 26 08:16:32 2011
@@ -182,17 +182,17 @@
             # On Snow Leopard, sw_vers reports 10.6.0 as 10.6
             if len_diff > 0:
                 expect_list.extend(['0'] * len_diff)
-            self.assertEquals(result_list, expect_list)
+            self.assertEqual(result_list, expect_list)
 
             # res[1] claims to contain
             # (version, dev_stage, non_release_version)
             # That information is no longer available
-            self.assertEquals(res[1], ('', '', ''))
+            self.assertEqual(res[1], ('', '', ''))
 
             if sys.byteorder == 'little':
-                self.assertEquals(res[2], 'i386')
+                self.assertEqual(res[2], 'i386')
             else:
-                self.assertEquals(res[2], 'PowerPC')
+                self.assertEqual(res[2], 'PowerPC')
 
 
     @unittest.skipUnless(sys.platform == 'darwin', "OSX only test")
@@ -210,8 +210,8 @@
         else:
             # parent
             cpid, sts = os.waitpid(pid, 0)
-            self.assertEquals(cpid, pid)
-            self.assertEquals(sts, 0)
+            self.assertEqual(cpid, pid)
+            self.assertEqual(sts, 0)
 
     def test_dist(self):
         res = platform.dist()

Modified: python/branches/pep-3151/Lib/test/test_poplib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_poplib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_poplib.py	Sat Feb 26 08:16:32 2011
@@ -108,6 +108,10 @@
     def cmd_apop(self, arg):
         self.push('+OK done nothing.')
 
+    def cmd_quit(self, arg):
+        self.push('+OK closing.')
+        self.close_when_done()
+
 
 class DummyPOP3Server(asyncore.dispatcher, threading.Thread):
 
@@ -165,10 +169,10 @@
     def setUp(self):
         self.server = DummyPOP3Server((HOST, PORT))
         self.server.start()
-        self.client = poplib.POP3(self.server.host, self.server.port)
+        self.client = poplib.POP3(self.server.host, self.server.port, timeout=3)
 
     def tearDown(self):
-        self.client.quit()
+        self.client.close()
         self.server.stop()
 
     def test_getwelcome(self):
@@ -228,6 +232,12 @@
         self.client.uidl()
         self.client.uidl('foo')
 
+    def test_quit(self):
+        resp = self.client.quit()
+        self.assertTrue(resp)
+        self.assertIsNone(self.client.sock)
+        self.assertIsNone(self.client.file)
+
 
 SUPPORTS_SSL = False
 if hasattr(poplib, 'POP3_SSL'):
@@ -274,6 +284,7 @@
             else:
                 DummyPOP3Handler.handle_read(self)
 
+
     class TestPOP3_SSLClass(TestPOP3Class):
         # repeat previous tests by using poplib.POP3_SSL
 

Modified: python/branches/pep-3151/Lib/test/test_posix.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_posix.py	(original)
+++ python/branches/pep-3151/Lib/test/test_posix.py	Sat Feb 26 08:16:32 2011
@@ -105,7 +105,7 @@
             try:
                 posix.initgroups(name, 13)
             except OSError as e:
-                self.assertEquals(e.errno, errno.EPERM)
+                self.assertEqual(e.errno, errno.EPERM)
             else:
                 self.fail("Expected OSError to be raised by initgroups")
 
@@ -285,6 +285,18 @@
         if hasattr(posix, 'listdir'):
             self.assertTrue(support.TESTFN in posix.listdir())
 
+    @unittest.skipUnless(hasattr(posix, 'fdlistdir'), "test needs posix.fdlistdir()")
+    def test_fdlistdir(self):
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        self.assertEqual(
+            sorted(posix.listdir('.')),
+            sorted(posix.fdlistdir(f))
+            )
+        # Check the fd was closed by fdlistdir
+        with self.assertRaises(OSError) as ctx:
+            posix.close(f)
+        self.assertEqual(ctx.exception.errno, errno.EBADF)
+
     def test_access(self):
         if hasattr(posix, 'access'):
             self.assertTrue(posix.access(support.TESTFN, os.R_OK))
@@ -373,6 +385,7 @@
                 os.chdir(curdir)
                 support.rmtree(base_path)
 
+    @unittest.skipUnless(hasattr(os, 'getegid'), "test needs os.getegid()")
     def test_getgroups(self):
         with os.popen('id -G') as idg:
             groups = idg.read().strip()
@@ -382,9 +395,203 @@
 
         # 'id -G' and 'os.getgroups()' should return the same
         # groups, ignoring order and duplicates.
+        # #10822 - it is implementation defined whether posix.getgroups()
+        # includes the effective gid so we include it anyway, since id -G does
         self.assertEqual(
                 set([int(x) for x in groups.split()]),
-                set(posix.getgroups()))
+                set(posix.getgroups() + [posix.getegid()]))
+
+    # tests for the posix *at functions follow
+
+    @unittest.skipUnless(hasattr(posix, 'faccessat'), "test needs posix.faccessat()")
+    def test_faccessat(self):
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            self.assertTrue(posix.faccessat(f, support.TESTFN, os.R_OK))
+        finally:
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'fchmodat'), "test needs posix.fchmodat()")
+    def test_fchmodat(self):
+        os.chmod(support.TESTFN, stat.S_IRUSR)
+
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            posix.fchmodat(f, support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
+
+            s = posix.stat(support.TESTFN)
+            self.assertEqual(s[0] & stat.S_IRWXU, stat.S_IRUSR | stat.S_IWUSR)
+        finally:
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'fchownat'), "test needs posix.fchownat()")
+    def test_fchownat(self):
+        support.unlink(support.TESTFN)
+        open(support.TESTFN, 'w').close()
+
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            posix.fchownat(f, support.TESTFN, os.getuid(), os.getgid())
+        finally:
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'fstatat'), "test needs posix.fstatat()")
+    def test_fstatat(self):
+        support.unlink(support.TESTFN)
+        with open(support.TESTFN, 'w') as outfile:
+            outfile.write("testline\n")
+
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            s1 = posix.stat(support.TESTFN)
+            s2 = posix.fstatat(f, support.TESTFN)
+            self.assertEqual(s1, s2)
+        finally:
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'futimesat'), "test needs posix.futimesat()")
+    def test_futimesat(self):
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            now = time.time()
+            posix.futimesat(f, support.TESTFN, None)
+            self.assertRaises(TypeError, posix.futimesat, f, support.TESTFN, (None, None))
+            self.assertRaises(TypeError, posix.futimesat, f, support.TESTFN, (now, None))
+            self.assertRaises(TypeError, posix.futimesat, f, support.TESTFN, (None, now))
+            posix.futimesat(f, support.TESTFN, (int(now), int(now)))
+            posix.futimesat(f, support.TESTFN, (now, now))
+        finally:
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'linkat'), "test needs posix.linkat()")
+    def test_linkat(self):
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            posix.linkat(f, support.TESTFN, f, support.TESTFN + 'link')
+            # should have same inodes
+            self.assertEqual(posix.stat(support.TESTFN)[1],
+                posix.stat(support.TESTFN + 'link')[1])
+        finally:
+            posix.close(f)
+            support.unlink(support.TESTFN + 'link')
+
+    @unittest.skipUnless(hasattr(posix, 'mkdirat'), "test needs posix.mkdirat()")
+    def test_mkdirat(self):
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            posix.mkdirat(f, support.TESTFN + 'dir')
+            posix.stat(support.TESTFN + 'dir') # should not raise exception
+        finally:
+            posix.close(f)
+            support.rmtree(support.TESTFN + 'dir')
+
+    @unittest.skipUnless(hasattr(posix, 'mknodat') and hasattr(stat, 'S_IFIFO'),
+                         "don't have mknodat()/S_IFIFO")
+    def test_mknodat(self):
+        # Test using mknodat() to create a FIFO (the only use specified
+        # by POSIX).
+        support.unlink(support.TESTFN)
+        mode = stat.S_IFIFO | stat.S_IRUSR | stat.S_IWUSR
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            posix.mknodat(f, support.TESTFN, mode, 0)
+        except OSError as e:
+            # Some old systems don't allow unprivileged users to use
+            # mknod(), or only support creating device nodes.
+            self.assertIn(e.errno, (errno.EPERM, errno.EINVAL))
+        else:
+            self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
+        finally:
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'openat'), "test needs posix.openat()")
+    def test_openat(self):
+        support.unlink(support.TESTFN)
+        with open(support.TESTFN, 'w') as outfile:
+            outfile.write("testline\n")
+        a = posix.open(posix.getcwd(), posix.O_RDONLY)
+        b = posix.openat(a, support.TESTFN, posix.O_RDONLY)
+        try:
+            res = posix.read(b, 9).decode(encoding="utf-8")
+            self.assertEqual("testline\n", res)
+        finally:
+            posix.close(a)
+            posix.close(b)
+
+    @unittest.skipUnless(hasattr(posix, 'readlinkat'), "test needs posix.readlinkat()")
+    def test_readlinkat(self):
+        os.symlink(support.TESTFN, support.TESTFN + 'link')
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            self.assertEqual(posix.readlink(support.TESTFN + 'link'),
+                posix.readlinkat(f, support.TESTFN + 'link'))
+        finally:
+            support.unlink(support.TESTFN + 'link')
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'renameat'), "test needs posix.renameat()")
+    def test_renameat(self):
+        support.unlink(support.TESTFN)
+        open(support.TESTFN + 'ren', 'w').close()
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            posix.renameat(f, support.TESTFN + 'ren', f, support.TESTFN)
+        except:
+            posix.rename(support.TESTFN + 'ren', support.TESTFN)
+            raise
+        else:
+            posix.stat(support.TESTFN) # should not throw exception
+        finally:
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'symlinkat'), "test needs posix.symlinkat()")
+    def test_symlinkat(self):
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            posix.symlinkat(support.TESTFN, f, support.TESTFN + 'link')
+            self.assertEqual(posix.readlink(support.TESTFN + 'link'), support.TESTFN)
+        finally:
+            posix.close(f)
+            support.unlink(support.TESTFN + 'link')
+
+    @unittest.skipUnless(hasattr(posix, 'unlinkat'), "test needs posix.unlinkat()")
+    def test_unlinkat(self):
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        open(support.TESTFN + 'del', 'w').close()
+        posix.stat(support.TESTFN + 'del') # should not throw exception
+        try:
+            posix.unlinkat(f, support.TESTFN + 'del')
+        except:
+            support.unlink(support.TESTFN + 'del')
+            raise
+        else:
+            self.assertRaises(OSError, posix.stat, support.TESTFN + 'link')
+        finally:
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'utimensat'), "test needs posix.utimensat()")
+    def test_utimensat(self):
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            now = time.time()
+            posix.utimensat(f, support.TESTFN, None, None)
+            self.assertRaises(TypeError, posix.utimensat, f, support.TESTFN, (None, None), (None, None))
+            self.assertRaises(TypeError, posix.utimensat, f, support.TESTFN, (now, 0), None)
+            self.assertRaises(TypeError, posix.utimensat, f, support.TESTFN, None, (now, 0))
+            posix.utimensat(f, support.TESTFN, (int(now), int((now - int(now)) * 1e9)),
+                    (int(now), int((now - int(now)) * 1e9)))
+        finally:
+            posix.close(f)
+
+    @unittest.skipUnless(hasattr(posix, 'mkfifoat'), "don't have mkfifoat()")
+    def test_mkfifoat(self):
+        support.unlink(support.TESTFN)
+        f = posix.open(posix.getcwd(), posix.O_RDONLY)
+        try:
+            posix.mkfifoat(f, support.TESTFN, stat.S_IRUSR | stat.S_IWUSR)
+            self.assertTrue(stat.S_ISFIFO(posix.stat(support.TESTFN).st_mode))
+        finally:
+            posix.close(f)
 
 class PosixGroupsTester(unittest.TestCase):
 

Modified: python/branches/pep-3151/Lib/test/test_posixpath.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_posixpath.py	(original)
+++ python/branches/pep-3151/Lib/test/test_posixpath.py	Sat Feb 26 08:16:32 2011
@@ -180,7 +180,8 @@
     @unittest.skipIf(
         sys.platform.startswith('win'),
         "posixpath.samefile does not work on links in Windows")
-    @support.skip_unless_symlink
+    @unittest.skipUnless(hasattr(os, "symlink"),
+                         "Missing symlink implementation")
     def test_samefile_on_links(self):
         test_fn1 = support.TESTFN + "1"
         test_fn2 = support.TESTFN + "2"
@@ -204,7 +205,8 @@
     @unittest.skipIf(
         sys.platform.startswith('win'),
         "posixpath.samestat does not work on links in Windows")
-    @support.skip_unless_symlink
+    @unittest.skipUnless(hasattr(os, "symlink"),
+                         "Missing symlink implementation")
     def test_samestat_on_links(self):
         test_fn1 = support.TESTFN + "1"
         test_fn2 = support.TESTFN + "2"
@@ -273,7 +275,8 @@
         self.assertEqual(posixpath.normpath(b"///..//./foo/.//bar"),
                          b"/foo/bar")
 
-    @support.skip_unless_symlink
+    @unittest.skipUnless(hasattr(os, "symlink"),
+                         "Missing symlink implementation")
     @skip_if_ABSTFN_contains_backslash
     def test_realpath_basic(self):
         # Basic operation.
@@ -283,7 +286,8 @@
         finally:
             support.unlink(ABSTFN)
 
-    @support.skip_unless_symlink
+    @unittest.skipUnless(hasattr(os, "symlink"),
+                         "Missing symlink implementation")
     @skip_if_ABSTFN_contains_backslash
     def test_realpath_symlink_loops(self):
         # Bug #930024, return the path unchanged if we get into an infinite
@@ -307,7 +311,8 @@
             support.unlink(ABSTFN+"1")
             support.unlink(ABSTFN+"2")
 
-    @support.skip_unless_symlink
+    @unittest.skipUnless(hasattr(os, "symlink"),
+                         "Missing symlink implementation")
     @skip_if_ABSTFN_contains_backslash
     def test_realpath_resolve_parents(self):
         # We also need to resolve any symlinks in the parents of a relative
@@ -328,7 +333,8 @@
             safe_rmdir(ABSTFN + "/y")
             safe_rmdir(ABSTFN)
 
-    @support.skip_unless_symlink
+    @unittest.skipUnless(hasattr(os, "symlink"),
+                         "Missing symlink implementation")
     @skip_if_ABSTFN_contains_backslash
     def test_realpath_resolve_before_normalizing(self):
         # Bug #990669: Symbolic links should be resolved before we
@@ -358,7 +364,8 @@
             safe_rmdir(ABSTFN + "/k")
             safe_rmdir(ABSTFN)
 
-    @support.skip_unless_symlink
+    @unittest.skipUnless(hasattr(os, "symlink"),
+                         "Missing symlink implementation")
     @skip_if_ABSTFN_contains_backslash
     def test_realpath_resolve_first(self):
         # Bug #1213894: The first component of the path, if not absolute,

Modified: python/branches/pep-3151/Lib/test/test_pow.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pow.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pow.py	Sat Feb 26 08:16:32 2011
@@ -5,17 +5,17 @@
     def powtest(self, type):
         if type != float:
             for i in range(-1000, 1000):
-                self.assertEquals(pow(type(i), 0), 1)
-                self.assertEquals(pow(type(i), 1), type(i))
-                self.assertEquals(pow(type(0), 1), type(0))
-                self.assertEquals(pow(type(1), 1), type(1))
+                self.assertEqual(pow(type(i), 0), 1)
+                self.assertEqual(pow(type(i), 1), type(i))
+                self.assertEqual(pow(type(0), 1), type(0))
+                self.assertEqual(pow(type(1), 1), type(1))
 
             for i in range(-100, 100):
-                self.assertEquals(pow(type(i), 3), i*i*i)
+                self.assertEqual(pow(type(i), 3), i*i*i)
 
             pow2 = 1
             for i in range(0, 31):
-                self.assertEquals(pow(2, i), pow2)
+                self.assertEqual(pow(2, i), pow2)
                 if i != 30 : pow2 = pow2*2
 
             for othertype in (int,):
@@ -67,30 +67,30 @@
 
     def test_other(self):
         # Other tests-- not very systematic
-        self.assertEquals(pow(3,3) % 8, pow(3,3,8))
-        self.assertEquals(pow(3,3) % -8, pow(3,3,-8))
-        self.assertEquals(pow(3,2) % -2, pow(3,2,-2))
-        self.assertEquals(pow(-3,3) % 8, pow(-3,3,8))
-        self.assertEquals(pow(-3,3) % -8, pow(-3,3,-8))
-        self.assertEquals(pow(5,2) % -8, pow(5,2,-8))
-
-        self.assertEquals(pow(3,3) % 8, pow(3,3,8))
-        self.assertEquals(pow(3,3) % -8, pow(3,3,-8))
-        self.assertEquals(pow(3,2) % -2, pow(3,2,-2))
-        self.assertEquals(pow(-3,3) % 8, pow(-3,3,8))
-        self.assertEquals(pow(-3,3) % -8, pow(-3,3,-8))
-        self.assertEquals(pow(5,2) % -8, pow(5,2,-8))
+        self.assertEqual(pow(3,3) % 8, pow(3,3,8))
+        self.assertEqual(pow(3,3) % -8, pow(3,3,-8))
+        self.assertEqual(pow(3,2) % -2, pow(3,2,-2))
+        self.assertEqual(pow(-3,3) % 8, pow(-3,3,8))
+        self.assertEqual(pow(-3,3) % -8, pow(-3,3,-8))
+        self.assertEqual(pow(5,2) % -8, pow(5,2,-8))
+
+        self.assertEqual(pow(3,3) % 8, pow(3,3,8))
+        self.assertEqual(pow(3,3) % -8, pow(3,3,-8))
+        self.assertEqual(pow(3,2) % -2, pow(3,2,-2))
+        self.assertEqual(pow(-3,3) % 8, pow(-3,3,8))
+        self.assertEqual(pow(-3,3) % -8, pow(-3,3,-8))
+        self.assertEqual(pow(5,2) % -8, pow(5,2,-8))
 
         for i in range(-10, 11):
             for j in range(0, 6):
                 for k in range(-7, 11):
                     if j >= 0 and k != 0:
-                        self.assertEquals(
+                        self.assertEqual(
                             pow(i,j) % k,
                             pow(i,j,k)
                         )
                     if j >= 0 and k != 0:
-                        self.assertEquals(
+                        self.assertEqual(
                             pow(int(i),j) % k,
                             pow(int(i),j,k)
                         )
@@ -104,7 +104,7 @@
     def test_bug705231(self):
         # -1.0 raised to an integer should never blow up.  It did if the
         # platform pow() was buggy, and Python didn't worm around it.
-        eq = self.assertEquals
+        eq = self.assertEqual
         a = -1.0
         # The next two tests can still fail if the platform floor()
         # function doesn't treat all large inputs as integers

Modified: python/branches/pep-3151/Lib/test/test_pty.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pty.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pty.py	Sat Feb 26 08:16:32 2011
@@ -86,7 +86,7 @@
         fcntl.fcntl(master_fd, fcntl.F_SETFL, orig_flags | os.O_NONBLOCK)
         try:
             s1 = os.read(master_fd, 1024)
-            self.assertEquals(b'', s1)
+            self.assertEqual(b'', s1)
         except OSError as e:
             if e.errno != errno.EAGAIN:
                 raise
@@ -96,14 +96,14 @@
         debug("Writing to slave_fd")
         os.write(slave_fd, TEST_STRING_1)
         s1 = os.read(master_fd, 1024)
-        self.assertEquals(b'I wish to buy a fish license.\n',
-                          normalize_output(s1))
+        self.assertEqual(b'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(b'For my pet fish, Eric.\n', normalize_output(s2))
+        self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2))
 
         os.close(slave_fd)
         os.close(master_fd)

Modified: python/branches/pep-3151/Lib/test/test_pyclbr.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pyclbr.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pyclbr.py	Sat Feb 26 08:16:32 2011
@@ -45,7 +45,7 @@
     def assertEqualsOrIgnored(self, a, b, ignore):
         ''' succeed iff a == b or a in ignore or b in ignore '''
         if a not in ignore and b not in ignore:
-            self.assertEquals(a, b)
+            self.assertEqual(a, b)
 
     def checkModule(self, moduleName, module=None, ignore=()):
         ''' succeed iff pyclbr.readmodule_ex(modulename) corresponds
@@ -87,7 +87,7 @@
                 self.assertIsInstance(py_item, (FunctionType, BuiltinFunctionType))
                 if py_item.__module__ != moduleName:
                     continue   # skip functions that came from somewhere else
-                self.assertEquals(py_item.__module__, value.module)
+                self.assertEqual(py_item.__module__, value.module)
             else:
                 self.assertIsInstance(py_item, type)
                 if py_item.__module__ != moduleName:
@@ -116,7 +116,7 @@
 
                 try:
                     self.assertListEq(foundMethods, actualMethods, ignore)
-                    self.assertEquals(py_item.__module__, value.module)
+                    self.assertEqual(py_item.__module__, value.module)
 
                     self.assertEqualsOrIgnored(py_item.__name__, value.name,
                                                ignore)

Modified: python/branches/pep-3151/Lib/test/test_pydoc.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pydoc.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pydoc.py	Sat Feb 26 08:16:32 2011
@@ -1,17 +1,20 @@
-import sys
 import os
-import os.path
+import sys
 import difflib
-import subprocess
-import re
-import pydoc
 import inspect
-import unittest
+import pydoc
+import re
+import string
+import subprocess
 import test.support
+import time
+import unittest
 import xml.etree
+import textwrap
+from io import StringIO
 from contextlib import contextmanager
-from test.support import (
-    TESTFN, forget, rmtree, EnvironmentVarGuard, reap_children)
+from test.support import TESTFN, forget, rmtree, EnvironmentVarGuard, \
+     reap_children, captured_output
 
 from test import pydoc_mod
 
@@ -22,9 +25,6 @@
 expected_text_pattern = """
 NAME
     test.pydoc_mod - This is a test module for test_pydoc
-
-FILE
-    %s
 %s
 CLASSES
     builtins.object
@@ -72,9 +72,7 @@
     nodoc_func()
 
 DATA
-    __author__ = 'Benjamin Peterson'
-    __credits__ = 'Nobody'
-    __version__ = '1.2.3.4'
+    __xyz__ = 'X, Y and Z'
 
 VERSION
     1.2.3.4
@@ -84,6 +82,9 @@
 
 CREDITS
     Nobody
+
+FILE
+    %s
 """.strip()
 
 expected_html_pattern = """
@@ -167,9 +168,7 @@
 <font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
 \x20\x20\x20\x20
 <tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
-<td width="100%%"><strong>__author__</strong> = 'Benjamin Peterson'<br>
-<strong>__credits__</strong> = 'Nobody'<br>
-<strong>__version__</strong> = '1.2.3.4'</td></tr></table><p>
+<td width="100%%"><strong>__xyz__</strong> = 'X, Y and Z'</td></tr></table><p>
 <table width="100%%" cellspacing=0 cellpadding=2 border=0 summary="section">
 <tr bgcolor="#7799ee">
 <td colspan=3 valign=bottom>&nbsp;<br>
@@ -223,24 +222,34 @@
 
     output = doc.docmodule(module)
 
-    # cleanup the extra text formatting that pydoc preforms
+    # clean up the extra text formatting that pydoc performs
     patt = re.compile('\b.')
     output = patt.sub('', output)
     return output.strip(), loc
 
 def print_diffs(text1, text2):
     "Prints unified diffs for two texts"
+    # XXX now obsolete, use unittest built-in support
     lines1 = text1.splitlines(True)
     lines2 = text2.splitlines(True)
     diffs = difflib.unified_diff(lines1, lines2, n=0, fromfile='expected',
                                  tofile='got')
     print('\n' + ''.join(diffs))
 
+def get_html_title(text):
+    # Bit of hack, but good enough for test purposes
+    header, _, _ = text.partition("</head>")
+    _, _, title = header.partition("<title>")
+    title, _, _ = title.partition("</title>")
+    return title
 
-class PyDocDocTest(unittest.TestCase):
+
+class PydocDocTest(unittest.TestCase):
 
     @unittest.skipIf(sys.flags.optimize >= 2,
                      "Docstrings are omitted with -O2 and above")
+    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
+                     'trace function introduces __locals__ unexpectedly')
     def test_html_doc(self):
         result, doc_loc = get_pydoc_html(pydoc_mod)
         mod_file = inspect.getabsfile(pydoc_mod)
@@ -256,10 +265,12 @@
 
     @unittest.skipIf(sys.flags.optimize >= 2,
                      "Docstrings are omitted with -O2 and above")
+    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
+                     'trace function introduces __locals__ unexpectedly')
     def test_text_doc(self):
         result, doc_loc = get_pydoc_text(pydoc_mod)
         expected_text = expected_text_pattern % \
-                        (inspect.getabsfile(pydoc_mod), doc_loc)
+                        (doc_loc, inspect.getabsfile(pydoc_mod))
         if result != expected_text:
             print_diffs(expected_text, result)
             self.fail("outputs are not equal, see diff above")
@@ -331,6 +342,43 @@
         self.assertEqual(stripid("<type 'exceptions.Exception'>"),
                          "<type 'exceptions.Exception'>")
 
+    @unittest.skipIf(sys.flags.optimize >= 2,
+                     'Docstrings are omitted with -O2 and above')
+    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
+                     'trace function introduces __locals__ unexpectedly')
+    def test_help_output_redirect(self):
+        # issue 940286, if output is set in Helper, then all output from
+        # Helper.help should be redirected
+        old_pattern = expected_text_pattern
+        getpager_old = pydoc.getpager
+        getpager_new = lambda: (lambda x: x)
+        self.maxDiff = None
+
+        buf = StringIO()
+        helper = pydoc.Helper(output=buf)
+        unused, doc_loc = get_pydoc_text(pydoc_mod)
+        module = "test.pydoc_mod"
+        help_header = """
+        Help on module test.pydoc_mod in test:
+
+        """.lstrip()
+        help_header = textwrap.dedent(help_header)
+        expected_help_pattern = help_header + expected_text_pattern
+
+        pydoc.getpager = getpager_new
+        try:
+            with captured_output('stdout') as output, \
+                 captured_output('stderr') as err:
+                helper.help(module)
+                result = buf.getvalue().strip()
+                expected_text = expected_help_pattern % \
+                                (doc_loc, inspect.getabsfile(pydoc_mod))
+                self.assertEqual('', output.getvalue())
+                self.assertEqual('', err.getvalue())
+                self.assertEqual(expected_text, result)
+        finally:
+            pydoc.getpager = getpager_old
+
 
 class TestDescriptions(unittest.TestCase):
 
@@ -340,16 +388,8 @@
         doc = pydoc.render_doc(pydocfodder)
         self.assertIn("pydocfodder", doc)
 
-    def test_classic_class(self):
-        class C: "Classic class"
-        c = C()
-        self.assertEqual(pydoc.describe(C), 'class C')
-        self.assertEqual(pydoc.describe(c), 'C')
-        expected = 'C in module %s' % __name__
-        self.assertIn(expected, pydoc.render_doc(c))
-
     def test_class(self):
-        class C(object): "New-style class"
+        class C: "New-style class"
         c = C()
 
         self.assertEqual(pydoc.describe(C), 'class C')
@@ -358,8 +398,75 @@
         self.assertIn(expected, pydoc.render_doc(c))
 
 
+class PydocServerTest(unittest.TestCase):
+    """Tests for pydoc._start_server"""
+
+    def test_server(self):
+
+        # Minimal test that starts the server, then stops it.
+        def my_url_handler(url, content_type):
+            text = 'the URL sent was: (%s, %s)' % (url, content_type)
+            return text
+
+        serverthread = pydoc._start_server(my_url_handler, port=0)
+        starttime = time.time()
+        timeout = 1  #seconds
+
+        while serverthread.serving:
+            time.sleep(.01)
+            if serverthread.serving and time.time() - starttime > timeout:
+                serverthread.stop()
+                break
+
+        self.assertEqual(serverthread.error, None)
+
+
+class PydocUrlHandlerTest(unittest.TestCase):
+    """Tests for pydoc._url_handler"""
+
+    def test_content_type_err(self):
+        f = pydoc._url_handler
+        self.assertRaises(TypeError, f, 'A', '')
+        self.assertRaises(TypeError, f, 'B', 'foobar')
+
+    def test_url_requests(self):
+        # Test for the correct title in the html pages returned.
+        # This tests the different parts of the URL handler without
+        # getting too picky about the exact html.
+        requests = [
+            ("", "Pydoc: Index of Modules"),
+            ("get?key=", "Pydoc: Index of Modules"),
+            ("index", "Pydoc: Index of Modules"),
+            ("topics", "Pydoc: Topics"),
+            ("keywords", "Pydoc: Keywords"),
+            ("pydoc", "Pydoc: module pydoc"),
+            ("get?key=pydoc", "Pydoc: module pydoc"),
+            ("search?key=pydoc", "Pydoc: Search Results"),
+            ("topic?key=def", "Pydoc: KEYWORD def"),
+            ("topic?key=STRINGS", "Pydoc: TOPIC STRINGS"),
+            ("foobar", "Pydoc: Error - foobar"),
+            ("getfile?key=foobar", "Pydoc: Error - getfile?key=foobar"),
+            ]
+
+        for url, title in requests:
+            text = pydoc._url_handler(url, "text/html")
+            result = get_html_title(text)
+            self.assertEqual(result, title)
+
+        path = string.__file__
+        title = "Pydoc: getfile " + path
+        url = "getfile?key=" + path
+        text = pydoc._url_handler(url, "text/html")
+        result = get_html_title(text)
+        self.assertEqual(result, title)
+
+
 def test_main():
-    test.support.run_unittest(PyDocDocTest, TestDescriptions)
+    test.support.run_unittest(PydocDocTest,
+                              TestDescriptions,
+                              PydocServerTest,
+                              PydocUrlHandlerTest,
+                              )
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/pep-3151/Lib/test/test_pyexpat.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_pyexpat.py	(original)
+++ python/branches/pep-3151/Lib/test/test_pyexpat.py	Sat Feb 26 08:16:32 2011
@@ -23,12 +23,12 @@
     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)
+            self.assertEqual(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)
+            self.assertEqual(self.parser.specified_attributes, y)
 
 
 data = b'''\
@@ -155,6 +155,14 @@
         'ElementDeclHandler', 'AttlistDeclHandler', 'SkippedEntityHandler',
         ]
 
+    def _hookup_callbacks(self, parser, handler):
+        """
+        Set each of the callbacks defined on handler and named in
+        self.handler_names on the given parser.
+        """
+        for name in self.handler_names:
+            setattr(parser, name, getattr(handler, name))
+
     def _verify_parse_output(self, operations):
         expected_operations = [
             ('XML declaration', ('1.0', 'iso-8859-1', 0)),
@@ -190,26 +198,26 @@
             "End element: 'root'",
         ]
         for operation, expected_operation in zip(operations, expected_operations):
-            self.assertEquals(operation, expected_operation)
+            self.assertEqual(operation, expected_operation)
 
     def test_unicode(self):
         # Try the parse again, this time producing Unicode output
         out = self.Outputter()
         parser = expat.ParserCreate(namespace_separator='!')
-        for name in self.handler_names:
-            setattr(parser, name, getattr(out, name))
+        self._hookup_callbacks(parser, out)
 
         parser.Parse(data, 1)
 
         operations = out.out
         self._verify_parse_output(operations)
+        # Issue #6697.
+        self.assertRaises(AttributeError, getattr, parser, '\uD800')
 
     def test_parse_file(self):
         # Try parsing a file
         out = self.Outputter()
         parser = expat.ParserCreate(namespace_separator='!')
-        for name in self.handler_names:
-            setattr(parser, name, getattr(out, name))
+        self._hookup_callbacks(parser, out)
         file = BytesIO(data)
 
         parser.ParseFile(file)
@@ -230,14 +238,14 @@
             expat.ParserCreate(namespace_separator=42)
             self.fail()
         except TypeError as e:
-            self.assertEquals(str(e),
+            self.assertEqual(str(e),
                 'ParserCreate() argument 2 must be str or None, not int')
 
         try:
             expat.ParserCreate(namespace_separator='too long')
             self.fail()
         except ValueError as e:
-            self.assertEquals(str(e),
+            self.assertEqual(str(e),
                 'namespace_separator must be at most one character, omitted, or None')
 
     def test_zero_length(self):
@@ -263,7 +271,7 @@
         p.EndElementHandler = collector
         p.Parse("<e> <e/> <e></e> </e>", 1)
         tag = L[0]
-        self.assertEquals(len(L), 6)
+        self.assertEqual(len(L), 6)
         for entry in L:
             # L should have the same string repeated over and over.
             self.assertTrue(tag is entry)
@@ -285,7 +293,7 @@
         out = ExternalOutputter(parser)
         parser.ExternalEntityRefHandler = out.ExternalEntityRefHandler
         parser.Parse(data, 1)
-        self.assertEquals(out.parser_result, 1)
+        self.assertEqual(out.parser_result, 1)
 
 
 class BufferTextTest(unittest.TestCase):
@@ -296,7 +304,7 @@
         self.parser.CharacterDataHandler = self.CharacterDataHandler
 
     def check(self, expected, label):
-        self.assertEquals(self.stuff, expected,
+        self.assertEqual(self.stuff, expected,
                 "%s\nstuff    = %r\nexpected = %r"
                 % (label, self.stuff, map(str, expected)))
 
@@ -329,47 +337,47 @@
         # 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")
+        self.assertEqual(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")
+        self.assertEqual(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")
+        self.assertEqual(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")
+        self.assertEqual(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>"])
+        self.assertEqual(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,
+        self.assertEqual(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,
+        self.assertEqual(self.stuff,
             ["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "345", "</a>"],
             "buffered text not properly split")
 
@@ -377,10 +385,10 @@
         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")
+        self.assertEqual(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:
@@ -395,9 +403,9 @@
             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])
+            self.assertEqual(e.args[0], 'a',
+                             "Expected RuntimeError for element 'a', but" + \
+                             " found %r" % e.args[0])
 
 
 # Test Current* members:
@@ -416,7 +424,7 @@
         self.assertTrue(self.upto < len(self.expected_list),
                         'too many parser events')
         expected = self.expected_list[self.upto]
-        self.assertEquals(pos, expected,
+        self.assertEqual(pos, expected,
                 'Expected position %s, got position %s' %(pos, expected))
         self.upto += 1
 
@@ -457,10 +465,10 @@
     """
 
     def test_1025_bytes(self):
-        self.assertEquals(self.small_buffer_test(1025), 2)
+        self.assertEqual(self.small_buffer_test(1025), 2)
 
     def test_1000_bytes(self):
-        self.assertEquals(self.small_buffer_test(1000), 1)
+        self.assertEqual(self.small_buffer_test(1000), 1)
 
     def test_wrong_size(self):
         parser = expat.ParserCreate()
@@ -483,15 +491,15 @@
         # once.
         self.n = 0
         parser.Parse(xml1)
-        self.assertEquals(self.n, 1)
+        self.assertEqual(self.n, 1)
 
         # Reassign to buffer_size, but assign the same size.
         parser.buffer_size = parser.buffer_size
-        self.assertEquals(self.n, 1)
+        self.assertEqual(self.n, 1)
 
         # Try parsing rest of the document
         parser.Parse(xml2)
-        self.assertEquals(self.n, 2)
+        self.assertEqual(self.n, 2)
 
 
     def test_disabling_buffer(self):
@@ -502,27 +510,27 @@
         parser.CharacterDataHandler = self.counting_handler
         parser.buffer_text = 1
         parser.buffer_size = 1024
-        self.assertEquals(parser.buffer_size, 1024)
+        self.assertEqual(parser.buffer_size, 1024)
 
         # Parse one chunk of XML
         self.n = 0
         parser.Parse(xml1, 0)
-        self.assertEquals(parser.buffer_size, 1024)
-        self.assertEquals(self.n, 1)
+        self.assertEqual(parser.buffer_size, 1024)
+        self.assertEqual(self.n, 1)
 
         # Turn off buffering and parse the next chunk.
         parser.buffer_text = 0
         self.assertFalse(parser.buffer_text)
-        self.assertEquals(parser.buffer_size, 1024)
+        self.assertEqual(parser.buffer_size, 1024)
         for i in range(10):
             parser.Parse(xml2, 0)
-        self.assertEquals(self.n, 11)
+        self.assertEqual(self.n, 11)
 
         parser.buffer_text = 1
         self.assertTrue(parser.buffer_text)
-        self.assertEquals(parser.buffer_size, 1024)
+        self.assertEqual(parser.buffer_size, 1024)
         parser.Parse(xml3, 1)
-        self.assertEquals(self.n, 12)
+        self.assertEqual(self.n, 12)
 
 
 
@@ -550,14 +558,14 @@
         parser.CharacterDataHandler = self.counting_handler
         parser.buffer_text = 1
         parser.buffer_size = 1024
-        self.assertEquals(parser.buffer_size, 1024)
+        self.assertEqual(parser.buffer_size, 1024)
 
         self.n = 0
         parser.Parse(xml1, 0)
         parser.buffer_size *= 2
-        self.assertEquals(parser.buffer_size, 2048)
+        self.assertEqual(parser.buffer_size, 2048)
         parser.Parse(xml2, 1)
-        self.assertEquals(self.n, 2)
+        self.assertEqual(self.n, 2)
 
     def test_change_size_2(self):
         xml1 = "<?xml version='1.0' encoding='iso8859'?><a>a<s>%s" % ('a' * 1023)
@@ -566,14 +574,14 @@
         parser.CharacterDataHandler = self.counting_handler
         parser.buffer_text = 1
         parser.buffer_size = 2048
-        self.assertEquals(parser.buffer_size, 2048)
+        self.assertEqual(parser.buffer_size, 2048)
 
         self.n=0
         parser.Parse(xml1, 0)
         parser.buffer_size = parser.buffer_size // 2
-        self.assertEquals(parser.buffer_size, 1024)
+        self.assertEqual(parser.buffer_size, 1024)
         parser.Parse(xml2, 1)
-        self.assertEquals(self.n, 4)
+        self.assertEqual(self.n, 4)
 
 class MalformedInputTest(unittest.TestCase):
     def test1(self):
@@ -583,7 +591,7 @@
             parser.Parse(xml, True)
             self.fail()
         except expat.ExpatError as e:
-            self.assertEquals(str(e), 'unclosed token: line 2, column 0')
+            self.assertEqual(str(e), 'unclosed token: line 2, column 0')
 
     def test2(self):
         xml = "<?xml version\xc2\x85='1.0'?>\r\n"
@@ -592,7 +600,7 @@
             parser.Parse(xml, True)
             self.fail()
         except expat.ExpatError as e:
-            self.assertEquals(str(e), 'XML declaration not well-formed: line 1, column 14')
+            self.assertEqual(str(e), 'XML declaration not well-formed: line 1, column 14')
 
 class ErrorMessageTest(unittest.TestCase):
     def test_codes(self):
@@ -607,8 +615,50 @@
             parser.Parse(xml, True)
             self.fail()
         except expat.ExpatError as e:
-            self.assertEquals(e.code,
-                              errors.codes[errors.XML_ERROR_UNCLOSED_TOKEN])
+            self.assertEqual(e.code,
+                             errors.codes[errors.XML_ERROR_UNCLOSED_TOKEN])
+
+
+class ForeignDTDTests(unittest.TestCase):
+    """
+    Tests for the UseForeignDTD method of expat parser objects.
+    """
+    def test_use_foreign_dtd(self):
+        """
+        If UseForeignDTD is passed True and a document without an external
+        entity reference is parsed, ExternalEntityRefHandler is first called
+        with None for the public and system ids.
+        """
+        handler_call_args = []
+        def resolve_entity(context, base, system_id, public_id):
+            handler_call_args.append((public_id, system_id))
+            return 1
+
+        parser = expat.ParserCreate()
+        parser.UseForeignDTD(True)
+        parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
+        parser.ExternalEntityRefHandler = resolve_entity
+        parser.Parse("<?xml version='1.0'?><element/>")
+        self.assertEqual(handler_call_args, [(None, None)])
+
+    def test_ignore_use_foreign_dtd(self):
+        """
+        If UseForeignDTD is passed True and a document with an external
+        entity reference is parsed, ExternalEntityRefHandler is called with
+        the public and system ids from the document.
+        """
+        handler_call_args = []
+        def resolve_entity(context, base, system_id, public_id):
+            handler_call_args.append((public_id, system_id))
+            return 1
+
+        parser = expat.ParserCreate()
+        parser.UseForeignDTD(True)
+        parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS)
+        parser.ExternalEntityRefHandler = resolve_entity
+        parser.Parse(
+            "<?xml version='1.0'?><!DOCTYPE foo PUBLIC 'bar' 'baz'><element/>")
+        self.assertEqual(handler_call_args, [("bar", "baz")])
 
 
 def test_main():
@@ -622,7 +672,8 @@
                  sf1296433Test,
                  ChardataBufferTest,
                  MalformedInputTest,
-                 ErrorMessageTest)
+                 ErrorMessageTest,
+                 ForeignDTDTests)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/pep-3151/Lib/test/test_queue.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_queue.py	(original)
+++ python/branches/pep-3151/Lib/test/test_queue.py	Sat Feb 26 08:16:32 2011
@@ -100,8 +100,8 @@
                             LifoQueue = [222, 333, 111],
                             PriorityQueue = [111, 222, 333])
         actual_order = [q.get(), q.get(), q.get()]
-        self.assertEquals(actual_order, target_order[q.__class__.__name__],
-                          "Didn't seem to queue the correct data!")
+        self.assertEqual(actual_order, target_order[q.__class__.__name__],
+                         "Didn't seem to queue the correct data!")
         for i in range(QUEUE_SIZE-1):
             q.put(i)
             self.assertTrue(q.qsize(), "Queue should not be empty")
@@ -161,8 +161,8 @@
         for i in range(100):
             q.put(i)
         q.join()
-        self.assertEquals(self.cum, sum(range(100)),
-                          "q.join() did not block until all tasks were done")
+        self.assertEqual(self.cum, sum(range(100)),
+                         "q.join() did not block until all tasks were done")
         for i in (0,1):
             q.put(-1)         # instruct the threads to close
         q.join()                # verify that you can join twice

Modified: python/branches/pep-3151/Lib/test/test_random.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_random.py	(original)
+++ python/branches/pep-3151/Lib/test/test_random.py	Sat Feb 26 08:16:32 2011
@@ -246,8 +246,8 @@
              '0x1.1ebb4352e4c4dp-1', '0x1.1a7422abf9c11p-1'])
         self.gen.seed("the quick brown fox", version=2)
         self.assertEqual([self.gen.random().hex() for i in range(4)],
-            ['0x1.1294009b9eda4p-2', '0x1.2ff96171b0010p-1',
-             '0x1.459e0989bd8e0p-5', '0x1.8b5f55892ddcbp-1'])
+            ['0x1.1239ddfb11b7cp-3', '0x1.b3cbb5c51b120p-4',
+             '0x1.8c4f55116b60fp-1', '0x1.63eb525174a27p-1'])
 
     def test_setstate_first_arg(self):
         self.assertRaises(ValueError, self.gen.setstate, (1, None, None))

Modified: python/branches/pep-3151/Lib/test/test_range.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_range.py	(original)
+++ python/branches/pep-3151/Lib/test/test_range.py	Sat Feb 26 08:16:32 2011
@@ -90,6 +90,250 @@
         r = range(-sys.maxsize, sys.maxsize, 2)
         self.assertEqual(len(r), sys.maxsize)
 
+    def test_large_operands(self):
+        x = range(10**20, 10**20+10, 3)
+        self.assertEqual(len(x), 4)
+        self.assertEqual(len(list(x)), 4)
+
+        x = range(10**20+10, 10**20, 3)
+        self.assertEqual(len(x), 0)
+        self.assertEqual(len(list(x)), 0)
+
+        x = range(10**20, 10**20+10, -3)
+        self.assertEqual(len(x), 0)
+        self.assertEqual(len(list(x)), 0)
+
+        x = range(10**20+10, 10**20, -3)
+        self.assertEqual(len(x), 4)
+        self.assertEqual(len(list(x)), 4)
+
+        # Now test range() with longs
+        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.maxsize)
+        b = int(100 * sys.maxsize)
+        c = int(50 * sys.maxsize)
+
+        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(range(a, b, c))
+        self.assertIn(a, seq)
+        self.assertNotIn(b, seq)
+        self.assertEqual(len(seq), 2)
+        self.assertEqual(seq[0], a)
+        self.assertEqual(seq[-1], a+c)
+
+        seq = list(range(b, a, -c))
+        self.assertIn(b, seq)
+        self.assertNotIn(a, seq)
+        self.assertEqual(len(seq), 2)
+        self.assertEqual(seq[0], b)
+        self.assertEqual(seq[-1], b-c)
+
+        seq = list(range(-a, -b, -c))
+        self.assertIn(-a, seq)
+        self.assertNotIn(-b, seq)
+        self.assertEqual(len(seq), 2)
+        self.assertEqual(seq[0], -a)
+        self.assertEqual(seq[-1], -a-c)
+
+    def test_large_range(self):
+        # Check long ranges (len > sys.maxsize)
+        # len() is expected to fail due to limitations of the __len__ protocol
+        def _range_len(x):
+            try:
+                length = len(x)
+            except OverflowError:
+                step = x[1] - x[0]
+                length = 1 + ((x[-1] - x[0]) // step)
+            return length
+        a = -sys.maxsize
+        b = sys.maxsize
+        expected_len = b - a
+        x = range(a, b)
+        self.assertIn(a, x)
+        self.assertNotIn(b, x)
+        self.assertRaises(OverflowError, len, x)
+        self.assertEqual(_range_len(x), expected_len)
+        self.assertEqual(x[0], a)
+        idx = sys.maxsize+1
+        self.assertEqual(x[idx], a+idx)
+        self.assertEqual(x[idx:idx+1][0], a+idx)
+        with self.assertRaises(IndexError):
+            x[-expected_len-1]
+        with self.assertRaises(IndexError):
+            x[expected_len]
+
+        a = 0
+        b = 2 * sys.maxsize
+        expected_len = b - a
+        x = range(a, b)
+        self.assertIn(a, x)
+        self.assertNotIn(b, x)
+        self.assertRaises(OverflowError, len, x)
+        self.assertEqual(_range_len(x), expected_len)
+        self.assertEqual(x[0], a)
+        idx = sys.maxsize+1
+        self.assertEqual(x[idx], a+idx)
+        self.assertEqual(x[idx:idx+1][0], a+idx)
+        with self.assertRaises(IndexError):
+            x[-expected_len-1]
+        with self.assertRaises(IndexError):
+            x[expected_len]
+
+        a = 0
+        b = sys.maxsize**10
+        c = 2*sys.maxsize
+        expected_len = 1 + (b - a) // c
+        x = range(a, b, c)
+        self.assertIn(a, x)
+        self.assertNotIn(b, x)
+        self.assertRaises(OverflowError, len, x)
+        self.assertEqual(_range_len(x), expected_len)
+        self.assertEqual(x[0], a)
+        idx = sys.maxsize+1
+        self.assertEqual(x[idx], a+(idx*c))
+        self.assertEqual(x[idx:idx+1][0], a+(idx*c))
+        with self.assertRaises(IndexError):
+            x[-expected_len-1]
+        with self.assertRaises(IndexError):
+            x[expected_len]
+
+        a = sys.maxsize**10
+        b = 0
+        c = -2*sys.maxsize
+        expected_len = 1 + (b - a) // c
+        x = range(a, b, c)
+        self.assertIn(a, x)
+        self.assertNotIn(b, x)
+        self.assertRaises(OverflowError, len, x)
+        self.assertEqual(_range_len(x), expected_len)
+        self.assertEqual(x[0], a)
+        idx = sys.maxsize+1
+        self.assertEqual(x[idx], a+(idx*c))
+        self.assertEqual(x[idx:idx+1][0], a+(idx*c))
+        with self.assertRaises(IndexError):
+            x[-expected_len-1]
+        with self.assertRaises(IndexError):
+            x[expected_len]
+
+    def test_invalid_invocation(self):
+        self.assertRaises(TypeError, range)
+        self.assertRaises(TypeError, range, 1, 2, 3, 4)
+        self.assertRaises(ValueError, range, 1, 2, 0)
+        a = int(10 * sys.maxsize)
+        self.assertRaises(ValueError, range, a, a + 1, int(0))
+        self.assertRaises(TypeError, range, 1., 1., 1.)
+        self.assertRaises(TypeError, range, 1e100, 1e101, 1e101)
+        self.assertRaises(TypeError, range, 0, "spam")
+        self.assertRaises(TypeError, range, 0, 42, "spam")
+        # Exercise various combinations of bad arguments, to check
+        # refcounting logic
+        self.assertRaises(TypeError, range, 0.0)
+        self.assertRaises(TypeError, range, 0, 0.0)
+        self.assertRaises(TypeError, range, 0.0, 0)
+        self.assertRaises(TypeError, range, 0.0, 0.0)
+        self.assertRaises(TypeError, range, 0, 0, 1.0)
+        self.assertRaises(TypeError, range, 0, 0.0, 1)
+        self.assertRaises(TypeError, range, 0, 0.0, 1.0)
+        self.assertRaises(TypeError, range, 0.0, 0, 1)
+        self.assertRaises(TypeError, range, 0.0, 0, 1.0)
+        self.assertRaises(TypeError, range, 0.0, 0.0, 1)
+        self.assertRaises(TypeError, range, 0.0, 0.0, 1.0)
+
+    def test_index(self):
+        u = range(2)
+        self.assertEqual(u.index(0), 0)
+        self.assertEqual(u.index(1), 1)
+        self.assertRaises(ValueError, u.index, 2)
+
+        u = range(-2, 3)
+        self.assertEqual(u.count(0), 1)
+        self.assertEqual(u.index(0), 2)
+        self.assertRaises(TypeError, u.index)
+
+        class BadExc(Exception):
+            pass
+
+        class BadCmp:
+            def __eq__(self, other):
+                if other == 2:
+                    raise BadExc()
+                return False
+
+        a = range(4)
+        self.assertRaises(BadExc, a.index, BadCmp())
+
+        a = range(-2, 3)
+        self.assertEqual(a.index(0), 2)
+        self.assertEqual(range(1, 10, 3).index(4), 1)
+        self.assertEqual(range(1, -10, -3).index(-5), 2)
+
+        self.assertEqual(range(10**20).index(1), 1)
+        self.assertEqual(range(10**20).index(10**20 - 1), 10**20 - 1)
+
+        self.assertRaises(ValueError, range(1, 2**100, 2).index, 2**87)
+        self.assertEqual(range(1, 2**100, 2).index(2**87+1), 2**86)
+
+        class AlwaysEqual(object):
+            def __eq__(self, other):
+                return True
+        always_equal = AlwaysEqual()
+        self.assertEqual(range(10).index(always_equal), 0)
+
+    def test_user_index_method(self):
+        bignum = 2*sys.maxsize
+        smallnum = 42
+
+        # User-defined class with an __index__ method
+        class I:
+            def __init__(self, n):
+                self.n = int(n)
+            def __index__(self):
+                return self.n
+        self.assertEqual(list(range(I(bignum), I(bignum + 1))), [bignum])
+        self.assertEqual(list(range(I(smallnum), I(smallnum + 1))), [smallnum])
+
+        # User-defined class with a failing __index__ method
+        class IX:
+            def __index__(self):
+                raise RuntimeError
+        self.assertRaises(RuntimeError, range, IX())
+
+        # User-defined class with an invalid __index__ method
+        class IN:
+            def __index__(self):
+                return "not a number"
+
+        self.assertRaises(TypeError, range, IN())
+
+    def test_count(self):
+        self.assertEqual(range(3).count(-1), 0)
+        self.assertEqual(range(3).count(0), 1)
+        self.assertEqual(range(3).count(1), 1)
+        self.assertEqual(range(3).count(2), 1)
+        self.assertEqual(range(3).count(3), 0)
+        self.assertIs(type(range(3).count(-1)), int)
+        self.assertIs(type(range(3).count(1)), int)
+        self.assertEqual(range(10**20).count(1), 1)
+        self.assertEqual(range(10**20).count(10**20), 0)
+        self.assertEqual(range(3).index(1), 1)
+        self.assertEqual(range(1, 2**100, 2).count(2**87), 0)
+        self.assertEqual(range(1, 2**100, 2).count(2**87+1), 1)
+
+        class AlwaysEqual(object):
+            def __eq__(self, other):
+                return True
+        always_equal = AlwaysEqual()
+        self.assertEqual(range(10).count(always_equal), 10)
+
+        self.assertEqual(len(range(sys.maxsize, sys.maxsize+10)), 10)
+
     def test_repr(self):
         self.assertEqual(repr(range(1)), 'range(0, 1)')
         self.assertEqual(repr(range(1, 2)), 'range(1, 2)')
@@ -101,8 +345,8 @@
         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
             for t in testcases:
                 r = range(*t)
-                self.assertEquals(list(pickle.loads(pickle.dumps(r, proto))),
-                                  list(r))
+                self.assertEqual(list(pickle.loads(pickle.dumps(r, proto))),
+                                 list(r))
 
     def test_odd_bug(self):
         # This used to raise a "SystemError: NULL result without error"
@@ -191,6 +435,70 @@
             test_id = "reversed(range({}, {}, {}))".format(start, end, step)
             self.assert_iterators_equal(iter1, iter2, test_id, limit=100)
 
+    def test_slice(self):
+        def check(start, stop, step=None):
+            i = slice(start, stop, step)
+            self.assertEqual(list(r[i]), list(r)[i])
+            self.assertEqual(len(r[i]), len(list(r)[i]))
+        for r in [range(10),
+                  range(0),
+                  range(1, 9, 3),
+                  range(8, 0, -3),
+                  range(sys.maxsize+1, sys.maxsize+10),
+                  ]:
+            check(0, 2)
+            check(0, 20)
+            check(1, 2)
+            check(20, 30)
+            check(-30, -20)
+            check(-1, 100, 2)
+            check(0, -1)
+            check(-1, -3, -1)
+
+    def test_contains(self):
+        r = range(10)
+        self.assertIn(0, r)
+        self.assertIn(1, r)
+        self.assertIn(5.0, r)
+        self.assertNotIn(5.1, r)
+        self.assertNotIn(-1, r)
+        self.assertNotIn(10, r)
+        self.assertNotIn("", r)
+        r = range(9, -1, -1)
+        self.assertIn(0, r)
+        self.assertIn(1, r)
+        self.assertIn(5.0, r)
+        self.assertNotIn(5.1, r)
+        self.assertNotIn(-1, r)
+        self.assertNotIn(10, r)
+        self.assertNotIn("", r)
+        r = range(0, 10, 2)
+        self.assertIn(0, r)
+        self.assertNotIn(1, r)
+        self.assertNotIn(5.0, r)
+        self.assertNotIn(5.1, r)
+        self.assertNotIn(-1, r)
+        self.assertNotIn(10, r)
+        self.assertNotIn("", r)
+        r = range(9, -1, -2)
+        self.assertNotIn(0, r)
+        self.assertIn(1, r)
+        self.assertIn(5.0, r)
+        self.assertNotIn(5.1, r)
+        self.assertNotIn(-1, r)
+        self.assertNotIn(10, r)
+        self.assertNotIn("", r)
+
+    def test_reverse_iteration(self):
+        for r in [range(10),
+                  range(0),
+                  range(1, 9, 3),
+                  range(8, 0, -3),
+                  range(sys.maxsize+1, sys.maxsize+10),
+                  ]:
+            self.assertEqual(list(reversed(r)), list(r)[::-1])
+
+
 def test_main():
     test.support.run_unittest(RangeTest)
 

Modified: python/branches/pep-3151/Lib/test/test_reprlib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_reprlib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_reprlib.py	Sat Feb 26 08:16:32 2011
@@ -23,7 +23,7 @@
 class ReprTests(unittest.TestCase):
 
     def test_string(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         eq(r("abc"), "'abc'")
         eq(r("abcdefghijklmnop"),"'abcdefghijklmnop'")
 
@@ -37,7 +37,7 @@
         eq(r(s), expected)
 
     def test_tuple(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         eq(r((1,)), "(1,)")
 
         t3 = (1, 2, 3)
@@ -52,7 +52,7 @@
         from array import array
         from collections import deque
 
-        eq = self.assertEquals
+        eq = self.assertEqual
         # Tuples give up after 6 elements
         eq(r(()), "()")
         eq(r((1,)), "(1,)")
@@ -102,7 +102,7 @@
                    "array('i', [1, 2, 3, 4, 5, ...])")
 
     def test_numbers(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         eq(r(123), repr(123))
         eq(r(123), repr(123))
         eq(r(1.0/3), repr(1.0/3))
@@ -112,7 +112,7 @@
         eq(r(n), expected)
 
     def test_instance(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         i1 = ClassWithRepr("a")
         eq(r(i1), repr(i1))
 
@@ -134,7 +134,7 @@
         # XXX anonymous functions?  see func_repr
 
     def test_builtin_function(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         # Functions
         eq(repr(hash), '<built-in function hash>')
         # Methods
@@ -142,13 +142,13 @@
             '<built-in method split of str object at 0x'))
 
     def test_range(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         eq(repr(range(1)), 'range(0, 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
+        eq = self.assertEqual
         # everything is meant to give up after 6 levels.
         eq(r([[[[[[[]]]]]]]), "[[[[[[[]]]]]]]")
         eq(r([[[[[[[[]]]]]]]]), "[[[[[[[...]]]]]]]")
@@ -169,7 +169,7 @@
         pass
 
     def test_descriptors(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         # method descriptors
         eq(repr(dict.items), "<method 'items' of 'dict' objects>")
         # XXX member descriptors
@@ -230,15 +230,15 @@
         del sys.path[0]
 
     def test_module(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         touch(os.path.join(self.subpkgname, self.pkgname + '.py'))
         from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation
         eq(repr(areallylongpackageandmodulenametotestreprtruncation),
-           "<module '%s' from '%s'>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__))
+           "<module %r from %r>" % (areallylongpackageandmodulenametotestreprtruncation.__name__, areallylongpackageandmodulenametotestreprtruncation.__file__))
         eq(repr(sys), "<module 'sys' (built-in)>")
 
     def test_type(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         touch(os.path.join(self.subpkgname, 'foo.py'), '''\
 class foo(object):
     pass
@@ -259,7 +259,7 @@
 ''')
         from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import bar
         # Module name may be prefixed with "test.", depending on how run.
-        self.assertEquals(repr(bar.bar), "<class '%s.bar'>" % bar.__name__)
+        self.assertEqual(repr(bar.bar), "<class '%s.bar'>" % bar.__name__)
 
     def test_instance(self):
         touch(os.path.join(self.subpkgname, 'baz.py'), '''\
@@ -272,7 +272,7 @@
             "<%s.baz object at 0x" % baz.__name__))
 
     def test_method(self):
-        eq = self.assertEquals
+        eq = self.assertEqual
         touch(os.path.join(self.subpkgname, 'qux.py'), '''\
 class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:
     def amethod(self): pass

Modified: python/branches/pep-3151/Lib/test/test_resource.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_resource.py	(original)
+++ python/branches/pep-3151/Lib/test/test_resource.py	Sat Feb 26 08:16:32 2011
@@ -102,6 +102,10 @@
             usageboth = resource.getrusage(resource.RUSAGE_BOTH)
         except (ValueError, AttributeError):
             pass
+        try:
+            usage_thread = resource.getrusage(resource.RUSAGE_THREAD)
+        except (ValueError, AttributeError):
+            pass
 
 def test_main(verbose=None):
     support.run_unittest(ResourceTest)

Modified: python/branches/pep-3151/Lib/test/test_richcmp.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_richcmp.py	(original)
+++ python/branches/pep-3151/Lib/test/test_richcmp.py	Sat Feb 26 08:16:32 2011
@@ -220,6 +220,7 @@
         for func in (do, operator.not_):
             self.assertRaises(Exc, func, Bad())
 
+    @support.no_tracing
     def test_recursion(self):
         # Check that comparison for recursive objects fails gracefully
         from collections import UserList

Modified: python/branches/pep-3151/Lib/test/test_runpy.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_runpy.py	(original)
+++ python/branches/pep-3151/Lib/test/test_runpy.py	Sat Feb 26 08:16:32 2011
@@ -6,7 +6,8 @@
 import re
 import tempfile
 import py_compile
-from test.support import forget, make_legacy_pyc, run_unittest, unload, verbose
+from test.support import (
+    forget, make_legacy_pyc, run_unittest, unload, verbose, no_tracing)
 from test.script_helper import (
     make_pkg, make_script, make_zip_pkg, make_zip_script, temp_dir)
 
@@ -329,7 +330,7 @@
 
     def _check_import_error(self, script_name, msg):
         msg = re.escape(msg)
-        self.assertRaisesRegexp(ImportError, msg, run_path, script_name)
+        self.assertRaisesRegex(ImportError, msg, run_path, script_name)
 
     def test_basic_script(self):
         with temp_dir() as script_dir:
@@ -395,6 +396,7 @@
             msg = "can't find '__main__' module in %r" % zip_name
             self._check_import_error(zip_name, msg)
 
+    @no_tracing
     def test_main_recursion_error(self):
         with temp_dir() as script_dir, temp_dir() as dummy_dir:
             mod_name = '__main__'
@@ -403,7 +405,7 @@
             script_name = self._make_test_script(script_dir, mod_name, source)
             zip_name, fname = make_zip_script(script_dir, 'test_zip', script_name)
             msg = "recursion depth exceeded"
-            self.assertRaisesRegexp(RuntimeError, msg, run_path, zip_name)
+            self.assertRaisesRegex(RuntimeError, msg, run_path, zip_name)
 
 
 

Modified: python/branches/pep-3151/Lib/test/test_sax.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_sax.py	(original)
+++ python/branches/pep-3151/Lib/test/test_sax.py	Sat Feb 26 08:16:32 2011
@@ -20,8 +20,8 @@
 TEST_XMLFILE = findfile("test.xml", subdir="xmltestdata")
 TEST_XMLFILE_OUT = findfile("test.xml.out", subdir="xmltestdata")
 try:
-    TEST_XMLFILE.encode("utf8")
-    TEST_XMLFILE_OUT.encode("utf8")
+    TEST_XMLFILE.encode("utf-8")
+    TEST_XMLFILE_OUT.encode("utf-8")
 except UnicodeEncodeError:
     raise unittest.SkipTest("filename is not encodable to utf8")
 
@@ -34,16 +34,16 @@
         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.assertEqual(attrs.getLength(), 0)
+        self.assertEqual(attrs.getNames(), [])
+        self.assertEqual(attrs.getQNames(), [])
+        self.assertEqual(len(attrs), 0)
         self.assertNotIn("attr", 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()), [])
+        self.assertEqual(list(attrs.keys()), [])
+        self.assertEqual(attrs.get("attrs"), None)
+        self.assertEqual(attrs.get("attrs", 25), 25)
+        self.assertEqual(list(attrs.items()), [])
+        self.assertEqual(list(attrs.values()), [])
 
     def verify_empty_nsattrs(self, attrs):
         self.assertRaises(KeyError, attrs.getValue, (ns_uri, "attr"))
@@ -51,33 +51,33 @@
         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.assertEqual(attrs.getLength(), 0)
+        self.assertEqual(attrs.getNames(), [])
+        self.assertEqual(attrs.getQNames(), [])
+        self.assertEqual(len(attrs), 0)
         self.assertNotIn((ns_uri, "attr"), 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()), [])
+        self.assertEqual(list(attrs.keys()), [])
+        self.assertEqual(attrs.get((ns_uri, "attr")), None)
+        self.assertEqual(attrs.get((ns_uri, "attr"), 25), 25)
+        self.assertEqual(list(attrs.items()), [])
+        self.assertEqual(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.assertEqual(attrs.getLength(), 1)
+        self.assertEqual(attrs.getNames(), ["attr"])
+        self.assertEqual(attrs.getQNames(), ["attr"])
+        self.assertEqual(len(attrs), 1)
         self.assertIn("attr", 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")
+        self.assertEqual(list(attrs.keys()), ["attr"])
+        self.assertEqual(attrs.get("attr"), "val")
+        self.assertEqual(attrs.get("attr", 25), "val")
+        self.assertEqual(list(attrs.items()), [("attr", "val")])
+        self.assertEqual(list(attrs.values()), ["val"])
+        self.assertEqual(attrs.getValue("attr"), "val")
+        self.assertEqual(attrs.getValueByQName("attr"), "val")
+        self.assertEqual(attrs.getNameByQName("attr"), "attr")
+        self.assertEqual(attrs["attr"], "val")
+        self.assertEqual(attrs.getQNameByName("attr"), "attr")
 
 class MakeParserTest(unittest.TestCase):
     def test_make_parser2(self):
@@ -107,47 +107,47 @@
 class SaxutilsTest(unittest.TestCase):
     # ===== escape
     def test_escape_basic(self):
-        self.assertEquals(escape("Donald Duck & Co"), "Donald Duck &amp; Co")
+        self.assertEqual(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;")
+        self.assertEqual(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")
+        self.assertEqual(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")
+        self.assertEqual(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>")
+        self.assertEqual(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")
+        self.assertEqual(unescape("Hei på deg", {"å" : "&aring;"}),
+                         "Hei p&aring; deg")
 
     def test_unescape_amp_extra(self):
-        self.assertEquals(unescape("&amp;foo;", {"&foo;": "splat"}), "&foo;")
+        self.assertEqual(unescape("&amp;foo;", {"&foo;": "splat"}), "&foo;")
 
     # ===== quoteattr
     def test_quoteattr_basic(self):
-        self.assertEquals(quoteattr("Donald Duck & Co"),
-                          '"Donald Duck &amp; Co"')
+        self.assertEqual(quoteattr("Donald Duck & Co"),
+                         '"Donald Duck &amp; Co"')
 
     def test_single_quoteattr(self):
-        self.assertEquals(quoteattr('Includes "double" quotes'),
-                          '\'Includes "double" quotes\'')
+        self.assertEqual(quoteattr('Includes "double" quotes'),
+                         '\'Includes "double" quotes\'')
 
     def test_double_quoteattr(self):
-        self.assertEquals(quoteattr("Includes 'single' quotes"),
-                          "\"Includes 'single' quotes\"")
+        self.assertEqual(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\"")
+        self.assertEqual(quoteattr("Includes 'single' and \"double\" quotes"),
+                         "\"Includes 'single' and &quot;double&quot; quotes\"")
 
     # ===== make_parser
     def test_make_parser(self):
@@ -169,7 +169,7 @@
         gen.endElement("doc")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start + "<doc></doc>")
+        self.assertEqual(result.getvalue(), start + "<doc></doc>")
 
     def test_xmlgen_basic_empty(self):
         result = StringIO()
@@ -179,7 +179,7 @@
         gen.endElement("doc")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start + "<doc/>")
+        self.assertEqual(result.getvalue(), start + "<doc/>")
 
     def test_xmlgen_content(self):
         result = StringIO()
@@ -191,7 +191,7 @@
         gen.endElement("doc")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start + "<doc>huhei</doc>")
+        self.assertEqual(result.getvalue(), start + "<doc>huhei</doc>")
 
     def test_xmlgen_content_empty(self):
         result = StringIO()
@@ -203,7 +203,7 @@
         gen.endElement("doc")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start + "<doc>huhei</doc>")
+        self.assertEqual(result.getvalue(), start + "<doc>huhei</doc>")
 
     def test_xmlgen_pi(self):
         result = StringIO()
@@ -215,7 +215,7 @@
         gen.endElement("doc")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start + "<?test data?><doc></doc>")
+        self.assertEqual(result.getvalue(), start + "<?test data?><doc></doc>")
 
     def test_xmlgen_content_escape(self):
         result = StringIO()
@@ -227,7 +227,7 @@
         gen.endElement("doc")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(),
+        self.assertEqual(result.getvalue(),
             start + "<doc>&lt;huhei&amp;</doc>")
 
     def test_xmlgen_attr_escape(self):
@@ -245,7 +245,7 @@
         gen.endElement("doc")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start +
+        self.assertEqual(result.getvalue(), start +
             ("<doc a='\"'><e a=\"'\"></e>"
              "<e a=\"'&quot;\"></e>"
              "<e a=\"&#10;&#13;&#9;\"></e></doc>"))
@@ -260,7 +260,7 @@
         gen.endElement("doc")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start + "<doc> </doc>")
+        self.assertEqual(result.getvalue(), start + "<doc> </doc>")
 
     def test_xmlgen_ignorable_empty(self):
         result = StringIO()
@@ -272,7 +272,7 @@
         gen.endElement("doc")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start + "<doc> </doc>")
+        self.assertEqual(result.getvalue(), start + "<doc> </doc>")
 
     def test_xmlgen_ns(self):
         result = StringIO()
@@ -288,7 +288,7 @@
         gen.endPrefixMapping("ns1")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start + \
+        self.assertEqual(result.getvalue(), start + \
            ('<ns1:doc xmlns:ns1="%s"><udoc></udoc></ns1:doc>' %
                                          ns_uri))
 
@@ -306,7 +306,7 @@
         gen.endPrefixMapping("ns1")
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start + \
+        self.assertEqual(result.getvalue(), start + \
            ('<ns1:doc xmlns:ns1="%s"><udoc/></ns1:doc>' %
                                          ns_uri))
 
@@ -319,7 +319,7 @@
         gen.endElementNS((None, 'a'), 'a')
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start+'<a b="c"></a>')
+        self.assertEqual(result.getvalue(), start+'<a b="c"></a>')
 
     def test_1463026_1_empty(self):
         result = StringIO()
@@ -330,7 +330,7 @@
         gen.endElementNS((None, 'a'), 'a')
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start+'<a b="c"/>')
+        self.assertEqual(result.getvalue(), start+'<a b="c"/>')
 
     def test_1463026_2(self):
         result = StringIO()
@@ -343,7 +343,7 @@
         gen.endPrefixMapping(None)
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start+'<a xmlns="qux"></a>')
+        self.assertEqual(result.getvalue(), start+'<a xmlns="qux"></a>')
 
     def test_1463026_2_empty(self):
         result = StringIO()
@@ -356,7 +356,7 @@
         gen.endPrefixMapping(None)
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(), start+'<a xmlns="qux"/>')
+        self.assertEqual(result.getvalue(), start+'<a xmlns="qux"/>')
 
     def test_1463026_3(self):
         result = StringIO()
@@ -369,7 +369,7 @@
         gen.endPrefixMapping('my')
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(),
+        self.assertEqual(result.getvalue(),
             start+'<my:a xmlns:my="qux" b="c"></my:a>')
 
     def test_1463026_3_empty(self):
@@ -383,7 +383,7 @@
         gen.endPrefixMapping('my')
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(),
+        self.assertEqual(result.getvalue(),
             start+'<my:a xmlns:my="qux" b="c"/>')
 
     def test_5027_1(self):
@@ -406,11 +406,11 @@
         parser.setContentHandler(gen)
         parser.parse(test_xml)
 
-        self.assertEquals(result.getvalue(),
-                          start + (
-                          '<a:g1 xmlns:a="http://example.com/ns">'
-                           '<a:g2 xml:lang="en">Hello</a:g2>'
-                          '</a:g1>'))
+        self.assertEqual(result.getvalue(),
+                         start + (
+                         '<a:g1 xmlns:a="http://example.com/ns">'
+                          '<a:g2 xml:lang="en">Hello</a:g2>'
+                         '</a:g1>'))
 
     def test_5027_2(self):
         # The xml prefix (as in xml:lang below) is reserved and bound by
@@ -434,11 +434,11 @@
         gen.endPrefixMapping('a')
         gen.endDocument()
 
-        self.assertEquals(result.getvalue(),
-                          start + (
-                          '<a:g1 xmlns:a="http://example.com/ns">'
-                           '<a:g2 xml:lang="en">Hello</a:g2>'
-                          '</a:g1>'))
+        self.assertEqual(result.getvalue(),
+                         start + (
+                         '<a:g1 xmlns:a="http://example.com/ns">'
+                          '<a:g2 xml:lang="en">Hello</a:g2>'
+                         '</a:g1>'))
 
 
 class XMLFilterBaseTest(unittest.TestCase):
@@ -455,7 +455,7 @@
         filter.endElement("doc")
         filter.endDocument()
 
-        self.assertEquals(result.getvalue(), start + "<doc>content </doc>")
+        self.assertEqual(result.getvalue(), start + "<doc>content </doc>")
 
 # ===========================================================================
 #
@@ -479,7 +479,7 @@
         with open(TEST_XMLFILE) as f:
             parser.parse(f)
 
-        self.assertEquals(result.getvalue(), xml_test_out)
+        self.assertEqual(result.getvalue(), xml_test_out)
 
     # ===== DTDHandler support
 
@@ -507,9 +507,9 @@
         parser.feed('<doc></doc>')
         parser.close()
 
-        self.assertEquals(handler._notations,
+        self.assertEqual(handler._notations,
             [("GIF", "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN", None)])
-        self.assertEquals(handler._entities, [("img", None, "expat.gif", "GIF")])
+        self.assertEqual(handler._entities, [("img", None, "expat.gif", "GIF")])
 
     # ===== EntityResolver support
 
@@ -532,8 +532,8 @@
         parser.feed('<doc>&test;</doc>')
         parser.close()
 
-        self.assertEquals(result.getvalue(), start +
-                          "<doc><entity></entity></doc>")
+        self.assertEqual(result.getvalue(), start +
+                         "<doc><entity></entity></doc>")
 
     # ===== Attributes support
 
@@ -585,18 +585,18 @@
 
         attrs = gather._attrs
 
-        self.assertEquals(attrs.getLength(), 1)
-        self.assertEquals(attrs.getNames(), [(ns_uri, "attr")])
+        self.assertEqual(attrs.getLength(), 1)
+        self.assertEqual(attrs.getNames(), [(ns_uri, "attr")])
         self.assertTrue((attrs.getQNames() == [] or
                          attrs.getQNames() == ["ns:attr"]))
-        self.assertEquals(len(attrs), 1)
+        self.assertEqual(len(attrs), 1)
         self.assertIn((ns_uri, "attr"), 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")
+        self.assertEqual(attrs.get((ns_uri, "attr")), "val")
+        self.assertEqual(attrs.get((ns_uri, "attr"), 25), "val")
+        self.assertEqual(list(attrs.items()), [((ns_uri, "attr"), "val")])
+        self.assertEqual(list(attrs.values()), ["val"])
+        self.assertEqual(attrs.getValue((ns_uri, "attr")), "val")
+        self.assertEqual(attrs[(ns_uri, "attr")], "val")
 
     # ===== InputSource support
 
@@ -608,7 +608,7 @@
         parser.setContentHandler(xmlgen)
         parser.parse(TEST_XMLFILE)
 
-        self.assertEquals(result.getvalue(), xml_test_out)
+        self.assertEqual(result.getvalue(), xml_test_out)
 
     def test_expat_inpsource_sysid(self):
         parser = create_parser()
@@ -618,7 +618,7 @@
         parser.setContentHandler(xmlgen)
         parser.parse(InputSource(TEST_XMLFILE))
 
-        self.assertEquals(result.getvalue(), xml_test_out)
+        self.assertEqual(result.getvalue(), xml_test_out)
 
     def test_expat_inpsource_stream(self):
         parser = create_parser()
@@ -631,7 +631,7 @@
             inpsrc.setByteStream(f)
             parser.parse(inpsrc)
 
-        self.assertEquals(result.getvalue(), xml_test_out)
+        self.assertEqual(result.getvalue(), xml_test_out)
 
     # ===== IncrementalParser support
 
@@ -645,7 +645,7 @@
         parser.feed("</doc>")
         parser.close()
 
-        self.assertEquals(result.getvalue(), start + "<doc></doc>")
+        self.assertEqual(result.getvalue(), start + "<doc></doc>")
 
     def test_expat_incremental_reset(self):
         result = StringIO()
@@ -666,7 +666,7 @@
         parser.feed("</doc>")
         parser.close()
 
-        self.assertEquals(result.getvalue(), start + "<doc>text</doc>")
+        self.assertEqual(result.getvalue(), start + "<doc>text</doc>")
 
     # ===== Locator support
 
@@ -680,9 +680,9 @@
         parser.feed("</doc>")
         parser.close()
 
-        self.assertEquals(parser.getSystemId(), None)
-        self.assertEquals(parser.getPublicId(), None)
-        self.assertEquals(parser.getLineNumber(), 1)
+        self.assertEqual(parser.getSystemId(), None)
+        self.assertEqual(parser.getPublicId(), None)
+        self.assertEqual(parser.getLineNumber(), 1)
 
     def test_expat_locator_withinfo(self):
         result = StringIO()
@@ -691,8 +691,8 @@
         parser.setContentHandler(xmlgen)
         parser.parse(TEST_XMLFILE)
 
-        self.assertEquals(parser.getSystemId(), TEST_XMLFILE)
-        self.assertEquals(parser.getPublicId(), None)
+        self.assertEqual(parser.getSystemId(), TEST_XMLFILE)
+        self.assertEqual(parser.getPublicId(), None)
 
 
 # ===========================================================================
@@ -713,7 +713,7 @@
             parser.parse(source)
             self.fail()
         except SAXException as e:
-            self.assertEquals(e.getSystemId(), name)
+            self.assertEqual(e.getSystemId(), name)
 
     def test_expat_incomplete(self):
         parser = create_parser()
@@ -777,21 +777,21 @@
         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.assertEqual(attrs.getLength(), 1)
+        self.assertEqual(attrs.getNames(), [(ns_uri, "attr")])
+        self.assertEqual(attrs.getQNames(), ["ns:attr"])
+        self.assertEqual(len(attrs), 1)
         self.assertIn((ns_uri, "attr"), 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")
+        self.assertEqual(list(attrs.keys()), [(ns_uri, "attr")])
+        self.assertEqual(attrs.get((ns_uri, "attr")), "val")
+        self.assertEqual(attrs.get((ns_uri, "attr"), 25), "val")
+        self.assertEqual(list(attrs.items()), [((ns_uri, "attr"), "val")])
+        self.assertEqual(list(attrs.values()), ["val"])
+        self.assertEqual(attrs.getValue((ns_uri, "attr")), "val")
+        self.assertEqual(attrs.getValueByQName("ns:attr"), "val")
+        self.assertEqual(attrs.getNameByQName("ns:attr"), (ns_uri, "attr"))
+        self.assertEqual(attrs[(ns_uri, "attr")], "val")
+        self.assertEqual(attrs.getQNameByName((ns_uri, "attr")), "ns:attr")
 
 
     # During the development of Python 2.5, an attempt to move the "xml"
@@ -827,7 +827,7 @@
         try:
             import xml.sax.expatreader
             module = xml.sax.expatreader
-            self.assertEquals(module.__name__, "xml.sax.expatreader")
+            self.assertEqual(module.__name__, "xml.sax.expatreader")
         finally:
             sys.modules.update(old_modules)
 

Modified: python/branches/pep-3151/Lib/test/test_scope.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_scope.py	(original)
+++ python/branches/pep-3151/Lib/test/test_scope.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,5 @@
 import unittest
-from test.support import check_syntax_error, run_unittest
+from test.support import check_syntax_error, cpython_only, run_unittest
 
 
 class ScopeTests(unittest.TestCase):
@@ -496,23 +496,22 @@
         self.assertNotIn("x", varnames)
         self.assertIn("y", varnames)
 
+    @cpython_only
     def testLocalsClass_WithTrace(self):
         # Issue23728: after the trace function returns, the locals()
         # dictionary is used to update all variables, this used to
         # include free variables. But in class statements, free
         # variables are not inserted...
         import sys
+        self.addCleanup(sys.settrace, sys.gettrace())
         sys.settrace(lambda a,b,c:None)
-        try:
-            x = 12
+        x = 12
 
-            class C:
-                def f(self):
-                    return x
+        class C:
+            def f(self):
+                return x
 
-            self.assertEquals(x, 12) # Used to raise UnboundLocalError
-        finally:
-            sys.settrace(None)
+        self.assertEqual(x, 12) # Used to raise UnboundLocalError
 
     def testBoundAndFree(self):
         # var is bound and free in class
@@ -527,6 +526,7 @@
         inst = f(3)()
         self.assertEqual(inst.a, inst.m())
 
+    @cpython_only
     def testInteractionWithTraceFunc(self):
 
         import sys
@@ -543,6 +543,7 @@
         class TestClass:
             pass
 
+        self.addCleanup(sys.settrace, sys.gettrace())
         sys.settrace(tracer)
         adaptgetter("foo", TestClass, (1, ""))
         sys.settrace(None)

Modified: python/branches/pep-3151/Lib/test/test_shelve.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_shelve.py	(original)
+++ python/branches/pep-3151/Lib/test/test_shelve.py	Sat Feb 26 08:16:32 2011
@@ -2,7 +2,7 @@
 import shelve
 import glob
 from test import support
-from collections import MutableMapping
+from collections.abc import MutableMapping
 from test.test_dbm import dbm_iterator
 
 def L1(s):
@@ -122,6 +122,19 @@
         self.assertEqual(len(d1), 1)
         self.assertEqual(len(d2), 1)
 
+    def test_keyencoding(self):
+        d = {}
+        key = 'Pöp'
+        # the default keyencoding is utf-8
+        shelve.Shelf(d)[key] = [1]
+        self.assertIn(key.encode('utf-8'), d)
+        # but a different one can be given
+        shelve.Shelf(d, keyencoding='latin-1')[key] = [1]
+        self.assertIn(key.encode('latin-1'), d)
+        # with all consequences
+        s = shelve.Shelf(d, keyencoding='ascii')
+        self.assertRaises(UnicodeEncodeError, s.__setitem__, key, [1])
+
     def test_writeback_also_writes_immediately(self):
         # Issue 5754
         d = {}

Modified: python/branches/pep-3151/Lib/test/test_shutil.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_shutil.py	(original)
+++ python/branches/pep-3151/Lib/test/test_shutil.py	Sat Feb 26 08:16:32 2011
@@ -271,24 +271,35 @@
             shutil.rmtree(src_dir)
             shutil.rmtree(os.path.dirname(dst_dir))
 
-    @support.skip_unless_symlink
+    @unittest.skipUnless(hasattr(os, 'link'), 'requires os.link')
     def test_dont_copy_file_onto_link_to_itself(self):
+        # Temporarily disable test on Windows.
+        if os.name == 'nt':
+            return
         # bug 851123.
         os.mkdir(TESTFN)
         src = os.path.join(TESTFN, 'cheese')
         dst = os.path.join(TESTFN, 'shop')
         try:
-            f = open(src, 'w')
-            f.write('cheddar')
-            f.close()
-
-            if hasattr(os, "link"):
-                os.link(src, dst)
-                self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
-                with open(src, 'r') as f:
-                    self.assertEqual(f.read(), 'cheddar')
-                os.remove(dst)
+            with open(src, 'w') as f:
+                f.write('cheddar')
+            os.link(src, dst)
+            self.assertRaises(shutil.Error, shutil.copyfile, src, dst)
+            with open(src, 'r') as f:
+                self.assertEqual(f.read(), 'cheddar')
+            os.remove(dst)
+        finally:
+            shutil.rmtree(TESTFN, ignore_errors=True)
 
+    @support.skip_unless_symlink
+    def test_dont_copy_file_onto_symlink_to_itself(self):
+        # bug 851123.
+        os.mkdir(TESTFN)
+        src = os.path.join(TESTFN, 'cheese')
+        dst = os.path.join(TESTFN, 'shop')
+        try:
+            with open(src, 'w') as f:
+                f.write('cheddar')
             # Using `src` here would mean we end up with a symlink pointing
             # to TESTFN/TESTFN/cheese, while it should point at
             # TESTFN/cheese.
@@ -298,10 +309,7 @@
                 self.assertEqual(f.read(), 'cheddar')
             os.remove(dst)
         finally:
-            try:
-                shutil.rmtree(TESTFN)
-            except OSError:
-                pass
+            shutil.rmtree(TESTFN, ignore_errors=True)
 
     @support.skip_unless_symlink
     def test_rmtree_on_symlink(self):
@@ -328,26 +336,26 @@
             finally:
                 os.remove(TESTFN)
 
-    @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo')
-    def test_copytree_named_pipe(self):
-        os.mkdir(TESTFN)
-        try:
-            subdir = os.path.join(TESTFN, "subdir")
-            os.mkdir(subdir)
-            pipe = os.path.join(subdir, "mypipe")
-            os.mkfifo(pipe)
+        @support.skip_unless_symlink
+        def test_copytree_named_pipe(self):
+            os.mkdir(TESTFN)
             try:
-                shutil.copytree(TESTFN, TESTFN2)
-            except shutil.Error as e:
-                errors = e.args[0]
-                self.assertEqual(len(errors), 1)
-                src, dst, error_msg = errors[0]
-                self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
-            else:
-                self.fail("shutil.Error should have been raised")
-        finally:
-            shutil.rmtree(TESTFN, ignore_errors=True)
-            shutil.rmtree(TESTFN2, ignore_errors=True)
+                subdir = os.path.join(TESTFN, "subdir")
+                os.mkdir(subdir)
+                pipe = os.path.join(subdir, "mypipe")
+                os.mkfifo(pipe)
+                try:
+                    shutil.copytree(TESTFN, TESTFN2)
+                except shutil.Error as e:
+                    errors = e.args[0]
+                    self.assertEqual(len(errors), 1)
+                    src, dst, error_msg = errors[0]
+                    self.assertEqual("`%s` is a named pipe" % pipe, error_msg)
+                else:
+                    self.fail("shutil.Error should have been raised")
+            finally:
+                shutil.rmtree(TESTFN, ignore_errors=True)
+                shutil.rmtree(TESTFN2, ignore_errors=True)
 
     def test_copytree_special_func(self):
 
@@ -362,7 +370,7 @@
             copied.append((src, dst))
 
         shutil.copytree(src_dir, dst_dir, copy_function=_copy)
-        self.assertEquals(len(copied), 2)
+        self.assertEqual(len(copied), 2)
 
     @support.skip_unless_symlink
     def test_copytree_dangling_symlinks(self):
@@ -477,7 +485,7 @@
 
         self.assertTrue(os.path.exists(tarball2))
         # let's compare both tarballs
-        self.assertEquals(self._tarinfo(tarball), self._tarinfo(tarball2))
+        self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
 
         # trying an uncompressed one
         base_name = os.path.join(tmpdir2, 'archive')
@@ -572,8 +580,8 @@
         archive = tarfile.open(archive_name)
         try:
             for member in archive.getmembers():
-                self.assertEquals(member.uid, 0)
-                self.assertEquals(member.gid, 0)
+                self.assertEqual(member.uid, 0)
+                self.assertEqual(member.gid, 0)
         finally:
             archive.close()
 
@@ -588,7 +596,7 @@
                 make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
             except Exception:
                 pass
-            self.assertEquals(os.getcwd(), current_dir)
+            self.assertEqual(os.getcwd(), current_dir)
         finally:
             unregister_archive_format('xxx')
 
@@ -635,16 +643,16 @@
             # let's try to unpack it now
             unpack_archive(filename, tmpdir2)
             diff = self._compare_dirs(tmpdir, tmpdir2)
-            self.assertEquals(diff, [])
+            self.assertEqual(diff, [])
 
     def test_unpack_registery(self):
 
         formats = get_unpack_formats()
 
         def _boo(filename, extract_dir, extra):
-            self.assertEquals(extra, 1)
-            self.assertEquals(filename, 'stuff.boo')
-            self.assertEquals(extract_dir, 'xx')
+            self.assertEqual(extra, 1)
+            self.assertEqual(filename, 'stuff.boo')
+            self.assertEqual(extract_dir, 'xx')
 
         register_unpack_format('Boo', ['.boo', '.b2'], _boo, [('extra', 1)])
         unpack_archive('stuff.boo', 'xx')
@@ -661,7 +669,7 @@
 
         # let's leave a clean state
         unregister_unpack_format('Boo2')
-        self.assertEquals(get_unpack_formats(), formats)
+        self.assertEqual(get_unpack_formats(), formats)
 
 
 class TestMove(unittest.TestCase):

Modified: python/branches/pep-3151/Lib/test/test_signal.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_signal.py	(original)
+++ python/branches/pep-3151/Lib/test/test_signal.py	Sat Feb 26 08:16:32 2011
@@ -203,10 +203,10 @@
 
     def test_getsignal(self):
         hup = signal.signal(signal.SIGHUP, self.trivial_signal_handler)
-        self.assertEquals(signal.getsignal(signal.SIGHUP),
-                          self.trivial_signal_handler)
+        self.assertEqual(signal.getsignal(signal.SIGHUP),
+                         self.trivial_signal_handler)
         signal.signal(signal.SIGHUP, hup)
-        self.assertEquals(signal.getsignal(signal.SIGHUP), hup)
+        self.assertEqual(signal.getsignal(signal.SIGHUP), hup)
 
 
 @unittest.skipUnless(sys.platform == "win32", "Windows specific")
@@ -456,9 +456,9 @@
                           "high")
 
         # virtual itimer should be (0.0, 0.0) now
-        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
+        self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
         # and the handler should have been called
-        self.assertEquals(self.hndl_called, True)
+        self.assertEqual(self.hndl_called, True)
 
     # Issue 3864, unknown if this affects earlier versions of freebsd also
     @unittest.skipIf(sys.platform=='freebsd6',
@@ -479,7 +479,7 @@
                           "high")
 
         # profiling itimer should be (0.0, 0.0) now
-        self.assertEquals(signal.getitimer(self.itimer), (0.0, 0.0))
+        self.assertEqual(signal.getitimer(self.itimer), (0.0, 0.0))
         # and the handler should have been called
         self.assertEqual(self.hndl_called, True)
 

Modified: python/branches/pep-3151/Lib/test/test_site.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_site.py	(original)
+++ python/branches/pep-3151/Lib/test/test_site.py	Sat Feb 26 08:16:32 2011
@@ -6,9 +6,11 @@
 """
 import unittest
 from test.support import run_unittest, TESTFN, EnvironmentVarGuard
+from test.support import captured_stderr
 import builtins
 import os
 import sys
+import re
 import encodings
 import subprocess
 import sysconfig
@@ -90,6 +92,58 @@
         finally:
             pth_file.cleanup()
 
+    def make_pth(self, contents, pth_dir='.', pth_name=TESTFN):
+        # Create a .pth file and return its (abspath, basename).
+        pth_dir = os.path.abspath(pth_dir)
+        pth_basename = pth_name + '.pth'
+        pth_fn = os.path.join(pth_dir, pth_basename)
+        pth_file = open(pth_fn, 'w', encoding='utf-8')
+        self.addCleanup(lambda: os.remove(pth_fn))
+        pth_file.write(contents)
+        pth_file.close()
+        return pth_dir, pth_basename
+
+    def test_addpackage_import_bad_syntax(self):
+        # Issue 10642
+        pth_dir, pth_fn = self.make_pth("import bad)syntax\n")
+        with captured_stderr() as err_out:
+            site.addpackage(pth_dir, pth_fn, set())
+        self.assertRegex(err_out.getvalue(), "line 1")
+        self.assertRegex(err_out.getvalue(),
+            re.escape(os.path.join(pth_dir, pth_fn)))
+        # XXX: the previous two should be independent checks so that the
+        # order doesn't matter.  The next three could be a single check
+        # but my regex foo isn't good enough to write it.
+        self.assertRegex(err_out.getvalue(), 'Traceback')
+        self.assertRegex(err_out.getvalue(), r'import bad\)syntax')
+        self.assertRegex(err_out.getvalue(), 'SyntaxError')
+
+    def test_addpackage_import_bad_exec(self):
+        # Issue 10642
+        pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n")
+        with captured_stderr() as err_out:
+            site.addpackage(pth_dir, pth_fn, set())
+        self.assertRegex(err_out.getvalue(), "line 2")
+        self.assertRegex(err_out.getvalue(),
+            re.escape(os.path.join(pth_dir, pth_fn)))
+        # XXX: ditto previous XXX comment.
+        self.assertRegex(err_out.getvalue(), 'Traceback')
+        self.assertRegex(err_out.getvalue(), 'ImportError')
+
+    @unittest.skipIf(sys.platform == "win32", "Windows does not raise an "
+                      "error for file paths containing null characters")
+    def test_addpackage_import_bad_pth_file(self):
+        # Issue 5258
+        pth_dir, pth_fn = self.make_pth("abc\x00def\n")
+        with captured_stderr() as err_out:
+            site.addpackage(pth_dir, pth_fn, set())
+        self.assertRegex(err_out.getvalue(), "line 1")
+        self.assertRegex(err_out.getvalue(),
+            re.escape(os.path.join(pth_dir, pth_fn)))
+        # XXX: ditto previous XXX comment.
+        self.assertRegex(err_out.getvalue(), 'Traceback')
+        self.assertRegex(err_out.getvalue(), 'TypeError')
+
     def test_addsitedir(self):
         # Same tests for test_addpackage since addsitedir() essentially just
         # calls addpackage() for every .pth file in the directory
@@ -107,12 +161,16 @@
         usersite = site.USER_SITE
         self.assertIn(usersite, sys.path)
 
+        env = os.environ.copy()
         rc = subprocess.call([sys.executable, '-c',
-            'import sys; sys.exit(%r in sys.path)' % usersite])
+            'import sys; sys.exit(%r in sys.path)' % usersite],
+            env=env)
         self.assertEqual(rc, 1)
 
+        env = os.environ.copy()
         rc = subprocess.call([sys.executable, '-s', '-c',
-            'import sys; sys.exit(%r in sys.path)' % usersite])
+            'import sys; sys.exit(%r in sys.path)' % usersite],
+            env=env)
         self.assertEqual(rc, 0)
 
         env = os.environ.copy()
@@ -134,7 +192,7 @@
         user_base = site.getuserbase()
 
         # the call sets site.USER_BASE
-        self.assertEquals(site.USER_BASE, user_base)
+        self.assertEqual(site.USER_BASE, user_base)
 
         # let's set PYTHONUSERBASE and see if it uses it
         site.USER_BASE = None
@@ -152,7 +210,7 @@
         user_site = site.getusersitepackages()
 
         # the call sets USER_BASE *and* USER_SITE
-        self.assertEquals(site.USER_SITE, user_site)
+        self.assertEqual(site.USER_SITE, user_site)
         self.assertTrue(user_site.startswith(site.USER_BASE), user_site)
 
     def test_getsitepackages(self):
@@ -162,19 +220,19 @@
         if sys.platform in ('os2emx', 'riscos'):
             self.assertEqual(len(dirs), 1)
             wanted = os.path.join('xoxo', 'Lib', 'site-packages')
-            self.assertEquals(dirs[0], wanted)
+            self.assertEqual(dirs[0], wanted)
         elif os.sep == '/':
             self.assertEqual(len(dirs), 2)
             wanted = os.path.join('xoxo', 'lib', 'python' + sys.version[:3],
                                   'site-packages')
-            self.assertEquals(dirs[0], wanted)
+            self.assertEqual(dirs[0], wanted)
             wanted = os.path.join('xoxo', 'lib', 'site-python')
-            self.assertEquals(dirs[1], wanted)
+            self.assertEqual(dirs[1], wanted)
         else:
             self.assertEqual(len(dirs), 2)
-            self.assertEquals(dirs[0], 'xoxo')
+            self.assertEqual(dirs[0], 'xoxo')
             wanted = os.path.join('xoxo', 'lib', 'site-packages')
-            self.assertEquals(dirs[1], wanted)
+            self.assertEqual(dirs[1], wanted)
 
         # let's try the specific Apple location
         if (sys.platform == "darwin" and
@@ -184,7 +242,7 @@
             self.assertEqual(len(dirs), 3)
             wanted = os.path.join('/Library', 'Python', sys.version[:3],
                                   'site-packages')
-            self.assertEquals(dirs[2], wanted)
+            self.assertEqual(dirs[2], wanted)
 
 class PthFile(object):
     """Helper class for handling testing of .pth files"""

Modified: python/branches/pep-3151/Lib/test/test_slice.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_slice.py	(original)
+++ python/branches/pep-3151/Lib/test/test_slice.py	Sat Feb 26 08:16:32 2011
@@ -118,7 +118,7 @@
 
         x = X()
         x[1:2] = 42
-        self.assertEquals(tmp, [(slice(1, 2), 42)])
+        self.assertEqual(tmp, [(slice(1, 2), 42)])
 
     def test_pickle(self):
         s = slice(10, 20, 3)

Modified: python/branches/pep-3151/Lib/test/test_smtpd.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_smtpd.py	(original)
+++ python/branches/pep-3151/Lib/test/test_smtpd.py	Sat Feb 26 08:16:32 2011
@@ -121,6 +121,24 @@
         self.assertEqual(self.channel.socket.last,
                          b'451 Internal confusion\r\n')
 
+    def test_command_too_long(self):
+        self.write_line(b'MAIL from ' +
+                        b'a' * self.channel.command_size_limit +
+                        b'@example')
+        self.assertEqual(self.channel.socket.last,
+                         b'500 Error: line too long\r\n')
+
+    def test_data_too_long(self):
+        # Small hack. Setting limit to 2K octets here will save us some time.
+        self.channel.data_size_limit = 2048
+        self.write_line(b'MAIL From:eggs at example')
+        self.write_line(b'RCPT To:spam at example')
+        self.write_line(b'DATA')
+        self.write_line(b'A' * self.channel.data_size_limit +
+                        b'A\r\n.')
+        self.assertEqual(self.channel.socket.last,
+                         b'552 Error: Too much mail data\r\n')
+
     def test_need_MAIL(self):
         self.write_line(b'RCPT to:spam at example')
         self.assertEqual(self.channel.socket.last,

Modified: python/branches/pep-3151/Lib/test/test_smtplib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_smtplib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_smtplib.py	Sat Feb 26 08:16:32 2011
@@ -319,12 +319,12 @@
         self.assertEqual(self.output.getvalue(), mexpect)
         debugout = smtpd.DEBUGSTREAM.getvalue()
         sender = re.compile("^sender: foo at bar.com$", re.MULTILINE)
-        self.assertRegexpMatches(debugout, sender)
+        self.assertRegex(debugout, sender)
         for addr in ('John', 'Sally', 'Fred', 'root at localhost',
                      'warped at silly.walks.com'):
             to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
                                  re.MULTILINE)
-            self.assertRegexpMatches(debugout, to_addr)
+            self.assertRegex(debugout, to_addr)
 
     def testSendMessageWithSomeAddresses(self):
         # Make sure nothing breaks if not all of the three 'to' headers exist
@@ -347,11 +347,11 @@
         self.assertEqual(self.output.getvalue(), mexpect)
         debugout = smtpd.DEBUGSTREAM.getvalue()
         sender = re.compile("^sender: foo at bar.com$", re.MULTILINE)
-        self.assertRegexpMatches(debugout, sender)
+        self.assertRegex(debugout, sender)
         for addr in ('John', 'Dinsdale'):
             to_addr = re.compile(r"^recips: .*'{}'.*$".format(addr),
                                  re.MULTILINE)
-            self.assertRegexpMatches(debugout, to_addr)
+            self.assertRegex(debugout, to_addr)
 
 
 class NonConnectingTests(unittest.TestCase):

Modified: python/branches/pep-3151/Lib/test/test_socket.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_socket.py	(original)
+++ python/branches/pep-3151/Lib/test/test_socket.py	Sat Feb 26 08:16:32 2011
@@ -44,7 +44,7 @@
         return 0, 0, 0
 
 HOST = support.HOST
-MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf8') ## test unicode string and carriage return
+MSG = 'Michael Gilfix was here\u1234\r\n'.encode('utf-8') ## test unicode string and carriage return
 SUPPORTS_IPV6 = socket.has_ipv6 and try_address('::1', family=socket.AF_INET6)
 
 try:
@@ -446,8 +446,8 @@
             return  # No inet_aton, nothing to check
         # Test that issue1008086 and issue767150 are fixed.
         # It must return 4 bytes.
-        self.assertEquals(b'\x00'*4, socket.inet_aton('0.0.0.0'))
-        self.assertEquals(b'\xff'*4, socket.inet_aton('255.255.255.255'))
+        self.assertEqual(b'\x00'*4, socket.inet_aton('0.0.0.0'))
+        self.assertEqual(b'\xff'*4, socket.inet_aton('255.255.255.255'))
 
     def testIPv4toString(self):
         if not hasattr(socket, 'inet_pton'):
@@ -455,16 +455,16 @@
         from socket import inet_aton as f, inet_pton, AF_INET
         g = lambda a: inet_pton(AF_INET, a)
 
-        self.assertEquals(b'\x00\x00\x00\x00', f('0.0.0.0'))
-        self.assertEquals(b'\xff\x00\xff\x00', f('255.0.255.0'))
-        self.assertEquals(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
-        self.assertEquals(b'\x01\x02\x03\x04', f('1.2.3.4'))
-        self.assertEquals(b'\xff\xff\xff\xff', f('255.255.255.255'))
-
-        self.assertEquals(b'\x00\x00\x00\x00', g('0.0.0.0'))
-        self.assertEquals(b'\xff\x00\xff\x00', g('255.0.255.0'))
-        self.assertEquals(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
-        self.assertEquals(b'\xff\xff\xff\xff', g('255.255.255.255'))
+        self.assertEqual(b'\x00\x00\x00\x00', f('0.0.0.0'))
+        self.assertEqual(b'\xff\x00\xff\x00', f('255.0.255.0'))
+        self.assertEqual(b'\xaa\xaa\xaa\xaa', f('170.170.170.170'))
+        self.assertEqual(b'\x01\x02\x03\x04', f('1.2.3.4'))
+        self.assertEqual(b'\xff\xff\xff\xff', f('255.255.255.255'))
+
+        self.assertEqual(b'\x00\x00\x00\x00', g('0.0.0.0'))
+        self.assertEqual(b'\xff\x00\xff\x00', g('255.0.255.0'))
+        self.assertEqual(b'\xaa\xaa\xaa\xaa', g('170.170.170.170'))
+        self.assertEqual(b'\xff\xff\xff\xff', g('255.255.255.255'))
 
     def testIPv6toString(self):
         if not hasattr(socket, 'inet_pton'):
@@ -477,10 +477,10 @@
             return
         f = lambda a: inet_pton(AF_INET6, a)
 
-        self.assertEquals(b'\x00' * 16, f('::'))
-        self.assertEquals(b'\x00' * 16, f('0::0'))
-        self.assertEquals(b'\x00\x01' + b'\x00' * 14, f('1::'))
-        self.assertEquals(
+        self.assertEqual(b'\x00' * 16, f('::'))
+        self.assertEqual(b'\x00' * 16, f('0::0'))
+        self.assertEqual(b'\x00\x01' + b'\x00' * 14, f('1::'))
+        self.assertEqual(
             b'\x45\xef\x76\xcb\x00\x1a\x56\xef\xaf\xeb\x0b\xac\x19\x24\xae\xae',
             f('45ef:76cb:1a:56ef:afeb:bac:1924:aeae')
         )
@@ -491,14 +491,14 @@
         from socket import inet_ntoa as f, inet_ntop, AF_INET
         g = lambda a: inet_ntop(AF_INET, a)
 
-        self.assertEquals('1.0.1.0', f(b'\x01\x00\x01\x00'))
-        self.assertEquals('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
-        self.assertEquals('255.255.255.255', f(b'\xff\xff\xff\xff'))
-        self.assertEquals('1.2.3.4', f(b'\x01\x02\x03\x04'))
-
-        self.assertEquals('1.0.1.0', g(b'\x01\x00\x01\x00'))
-        self.assertEquals('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
-        self.assertEquals('255.255.255.255', g(b'\xff\xff\xff\xff'))
+        self.assertEqual('1.0.1.0', f(b'\x01\x00\x01\x00'))
+        self.assertEqual('170.85.170.85', f(b'\xaa\x55\xaa\x55'))
+        self.assertEqual('255.255.255.255', f(b'\xff\xff\xff\xff'))
+        self.assertEqual('1.2.3.4', f(b'\x01\x02\x03\x04'))
+
+        self.assertEqual('1.0.1.0', g(b'\x01\x00\x01\x00'))
+        self.assertEqual('170.85.170.85', g(b'\xaa\x55\xaa\x55'))
+        self.assertEqual('255.255.255.255', g(b'\xff\xff\xff\xff'))
 
     def testStringToIPv6(self):
         if not hasattr(socket, 'inet_ntop'):
@@ -511,9 +511,9 @@
             return
         f = lambda a: inet_ntop(AF_INET6, a)
 
-        self.assertEquals('::', f(b'\x00' * 16))
-        self.assertEquals('::1', f(b'\x00' * 15 + b'\x01'))
-        self.assertEquals(
+        self.assertEqual('::', f(b'\x00' * 16))
+        self.assertEqual('::1', f(b'\x00' * 15 + b'\x01'))
+        self.assertEqual(
             'aef:b01:506:1001:ffff:9997:55:170',
             f(b'\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')
         )
@@ -544,7 +544,11 @@
         # XXX(nnorwitz): http://tinyurl.com/os5jz seems to indicate
         # it reasonable to get the host's addr in addition to 0.0.0.0.
         # At least for eCos.  This is required for the S/390 to pass.
-        my_ip_addr = socket.gethostbyname(socket.gethostname())
+        try:
+            my_ip_addr = socket.gethostbyname(socket.gethostname())
+        except socket.error:
+            # Probably name lookup wasn't set up right; skip this test
+            return
         self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
         self.assertEqual(name[1], port)
 
@@ -663,6 +667,8 @@
                                type=socket.SOCK_STREAM, proto=0,
                                flags=socket.AI_PASSIVE)
         self.assertEqual(a, b)
+        # Issue #6697.
+        self.assertRaises(UnicodeEncodeError, socket.getaddrinfo, 'localhost', '\uD800')
 
     def test_getnameinfo(self):
         # only IP addresses are allowed
@@ -732,6 +738,12 @@
             f = None
             support.gc_collect()
 
+    def test_name_closed_socketio(self):
+        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
+            fp = sock.makefile("rb")
+            fp.close()
+            self.assertEqual(repr(fp), "<_io.BufferedReader name=-1>")
+
 
 @unittest.skipUnless(thread, 'Threading required for this test.')
 class BasicTCPTest(SocketConnectedTest):
@@ -970,6 +982,23 @@
         def _testInitNonBlocking(self):
             pass
 
+    def testInheritFlags(self):
+        # Issue #7995: when calling accept() on a listening socket with a
+        # timeout, the resulting socket should not be non-blocking.
+        self.serv.settimeout(10)
+        try:
+            conn, addr = self.serv.accept()
+            message = conn.recv(len(MSG))
+        finally:
+            conn.close()
+            self.serv.settimeout(None)
+
+    def _testInheritFlags(self):
+        time.sleep(0.1)
+        self.cli.connect((HOST, self.port))
+        time.sleep(0.5)
+        self.cli.send(MSG)
+
     def testAccept(self):
         # Testing non-blocking accept
         self.serv.setblocking(0)
@@ -1036,7 +1065,7 @@
     """
 
     bufsize = -1 # Use default buffer size
-    encoding = 'utf8'
+    encoding = 'utf-8'
     errors = 'strict'
     newline = None
 
@@ -1080,6 +1109,23 @@
         self.write_file = None
         SocketConnectedTest.clientTearDown(self)
 
+    def testReadAfterTimeout(self):
+        # Issue #7322: A file object must disallow further reads
+        # after a timeout has occurred.
+        self.cli_conn.settimeout(1)
+        self.read_file.read(3)
+        # First read raises a timeout
+        self.assertRaises(socket.timeout, self.read_file.read, 1)
+        # Second read is disallowed
+        with self.assertRaises(IOError) as ctx:
+            self.read_file.read(1)
+        self.assertIn("cannot read from timed out object", str(ctx.exception))
+
+    def _testReadAfterTimeout(self):
+        self.write_file.write(self.write_msg[0:3])
+        self.write_file.flush()
+        self.serv_finished.wait()
+
     def testSmallRead(self):
         # Performing small file read test
         first_seg = self.read_file.read(len(self.read_msg)-3)
@@ -1222,8 +1268,8 @@
                 lambda : b"",  # XXX(gps): io library does an extra EOF read
             ])
         fo = mock_sock._textiowrap_for_test(buffering=buffering)
-        self.assertEquals(fo.readline(size), "This is the first line\n")
-        self.assertEquals(fo.readline(size), "And the second line is here\n")
+        self.assertEqual(fo.readline(size), "This is the first line\n")
+        self.assertEqual(fo.readline(size), "And the second line is here\n")
 
     def _test_read(self, size=-1, buffering=-1):
         mock_sock = self.MockSocket(recv_funcs=[
@@ -1240,13 +1286,13 @@
             data = b''
         else:
             data = ''
-            expecting = expecting.decode('utf8')
+            expecting = expecting.decode('utf-8')
         while len(data) != len(expecting):
             part = fo.read(size)
             if not part:
                 break
             data += part
-        self.assertEquals(data, expecting)
+        self.assertEqual(data, expecting)
 
     def test_default(self):
         self._test_readline()
@@ -1270,8 +1316,8 @@
                 lambda : b"",
             ])
         fo = mock_sock._textiowrap_for_test(buffering=0)
-        self.assertEquals(fo.readline(size), b"a\n")
-        self.assertEquals(fo.readline(size), b"Bb")
+        self.assertEqual(fo.readline(size), b"a\n")
+        self.assertEqual(fo.readline(size), b"Bb")
 
     def test_no_buffer(self):
         self._test_readline_no_buffer()
@@ -1398,7 +1444,7 @@
     """Tests for socket.makefile() in text mode (rather than binary)"""
 
     read_mode = 'r'
-    read_msg = MSG.decode('utf8')
+    read_msg = MSG.decode('utf-8')
     write_mode = 'wb'
     write_msg = MSG
     newline = ''
@@ -1410,7 +1456,7 @@
     read_mode = 'rb'
     read_msg = MSG
     write_mode = 'w'
-    write_msg = MSG.decode('utf8')
+    write_msg = MSG.decode('utf-8')
     newline = ''
 
 
@@ -1418,9 +1464,9 @@
     """Tests for socket.makefile() in text mode (rather than binary)"""
 
     read_mode = 'r'
-    read_msg = MSG.decode('utf8')
+    read_msg = MSG.decode('utf-8')
     write_mode = 'w'
-    write_msg = MSG.decode('utf8')
+    write_msg = MSG.decode('utf-8')
     newline = ''
 
 
@@ -1521,7 +1567,7 @@
             self.addCleanup(self.cli.close)
         finally:
             socket.setdefaulttimeout(None)
-        self.assertEquals(self.cli.gettimeout(), 42)
+        self.assertEqual(self.cli.gettimeout(), 42)
 
     testTimeoutNone = _justAccept
     def _testTimeoutNone(self):
@@ -1672,25 +1718,25 @@
 
     def testLinuxAbstractNamespace(self):
         address = b"\x00python-test-hello\x00\xff"
-        s1 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-        s1.bind(address)
-        s1.listen(1)
-        s2 = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-        s2.connect(s1.getsockname())
-        s1.accept()
-        self.assertEqual(s1.getsockname(), address)
-        self.assertEqual(s2.getpeername(), address)
+        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s1:
+            s1.bind(address)
+            s1.listen(1)
+            with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s2:
+                s2.connect(s1.getsockname())
+                with s1.accept()[0] as s3:
+                    self.assertEqual(s1.getsockname(), address)
+                    self.assertEqual(s2.getpeername(), address)
 
     def testMaxName(self):
         address = b"\x00" + b"h" * (self.UNIX_PATH_MAX - 1)
-        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-        s.bind(address)
-        self.assertEqual(s.getsockname(), address)
+        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
+            s.bind(address)
+            self.assertEqual(s.getsockname(), address)
 
     def testNameOverflow(self):
         address = "\x00" + "h" * self.UNIX_PATH_MAX
-        s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
-        self.assertRaises(socket.error, s.bind, address)
+        with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
+            self.assertRaises(socket.error, s.bind, address)
 
 
 @unittest.skipUnless(thread, 'Threading required for this test.')
@@ -1892,10 +1938,10 @@
         if v < (2, 6, 28):
             self.skipTest("Linux kernel 2.6.28 or higher required, not %s"
                           % ".".join(map(str, v)))
-        s = socket.socket(socket.AF_INET,
-                          socket.SOCK_STREAM | socket.SOCK_CLOEXEC)
-        self.assertTrue(s.type & socket.SOCK_CLOEXEC)
-        self.assertTrue(fcntl.fcntl(s, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
+        with socket.socket(socket.AF_INET,
+                           socket.SOCK_STREAM | socket.SOCK_CLOEXEC) as s:
+            self.assertTrue(s.type & socket.SOCK_CLOEXEC)
+            self.assertTrue(fcntl.fcntl(s, fcntl.F_GETFD) & fcntl.FD_CLOEXEC)
 
 
 @unittest.skipUnless(hasattr(socket, "SOCK_NONBLOCK"),
@@ -1916,29 +1962,33 @@
                           % ".".join(map(str, v)))
         # a lot of it seems silly and redundant, but I wanted to test that
         # changing back and forth worked ok
-        s = socket.socket(socket.AF_INET,
-                          socket.SOCK_STREAM | socket.SOCK_NONBLOCK)
-        self.checkNonblock(s)
-        s.setblocking(1)
-        self.checkNonblock(s, False)
-        s.setblocking(0)
-        self.checkNonblock(s)
-        s.settimeout(None)
-        self.checkNonblock(s, False)
-        s.settimeout(2.0)
-        self.checkNonblock(s, timeout=2.0)
-        s.setblocking(1)
-        self.checkNonblock(s, False)
+        with socket.socket(socket.AF_INET,
+                           socket.SOCK_STREAM | socket.SOCK_NONBLOCK) as s:
+            self.checkNonblock(s)
+            s.setblocking(1)
+            self.checkNonblock(s, False)
+            s.setblocking(0)
+            self.checkNonblock(s)
+            s.settimeout(None)
+            self.checkNonblock(s, False)
+            s.settimeout(2.0)
+            self.checkNonblock(s, timeout=2.0)
+            s.setblocking(1)
+            self.checkNonblock(s, False)
         # defaulttimeout
         t = socket.getdefaulttimeout()
         socket.setdefaulttimeout(0.0)
-        self.checkNonblock(socket.socket())
+        with socket.socket() as s:
+            self.checkNonblock(s)
         socket.setdefaulttimeout(None)
-        self.checkNonblock(socket.socket(), False)
+        with socket.socket() as s:
+            self.checkNonblock(s, False)
         socket.setdefaulttimeout(2.0)
-        self.checkNonblock(socket.socket(), timeout=2.0)
+        with socket.socket() as s:
+            self.checkNonblock(s, timeout=2.0)
         socket.setdefaulttimeout(None)
-        self.checkNonblock(socket.socket(), False)
+        with socket.socket() as s:
+            self.checkNonblock(s, False)
         socket.setdefaulttimeout(t)
 
 

Modified: python/branches/pep-3151/Lib/test/test_socketserver.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_socketserver.py	(original)
+++ python/branches/pep-3151/Lib/test/test_socketserver.py	Sat Feb 26 08:16:32 2011
@@ -57,8 +57,8 @@
         os._exit(72)
     yield None
     pid2, status = os.waitpid(pid, 0)
-    testcase.assertEquals(pid2, pid)
-    testcase.assertEquals(72 << 8, status)
+    testcase.assertEqual(pid2, pid)
+    testcase.assertEqual(72 << 8, status)
 
 
 @unittest.skipUnless(threading, 'Threading required for this test.')
@@ -120,7 +120,7 @@
 
         if verbose: print("creating server")
         server = MyServer(addr, MyHandler)
-        self.assertEquals(server.server_address, server.socket.getsockname())
+        self.assertEqual(server.server_address, server.socket.getsockname())
         return server
 
     @unittest.skipUnless(threading, 'Threading required for this test.')
@@ -151,6 +151,7 @@
         if verbose: print("waiting for server")
         server.shutdown()
         t.join()
+        server.server_close()
         if verbose: print("done")
 
     def stream_examine(self, proto, addr):
@@ -161,7 +162,7 @@
         while data and b'\n' not in buf:
             data = receive(s, 100)
             buf += data
-        self.assertEquals(buf, TEST_STR)
+        self.assertEqual(buf, TEST_STR)
         s.close()
 
     def dgram_examine(self, proto, addr):
@@ -171,7 +172,7 @@
         while data and b'\n' not in buf:
             data = receive(s, 100)
             buf += data
-        self.assertEquals(buf, TEST_STR)
+        self.assertEqual(buf, TEST_STR)
         s.close()
 
     def test_TCPServer(self):
@@ -270,6 +271,7 @@
             s.shutdown()
         for t, s in threads:
             t.join()
+            s.server_close()
 
 
 def test_main():

Modified: python/branches/pep-3151/Lib/test/test_ssl.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_ssl.py	(original)
+++ python/branches/pep-3151/Lib/test/test_ssl.py	Sat Feb 26 08:16:32 2011
@@ -185,17 +185,17 @@
 
     def test_errors(self):
         sock = socket.socket()
-        self.assertRaisesRegexp(ValueError,
+        self.assertRaisesRegex(ValueError,
                         "certfile must be specified",
                         ssl.wrap_socket, sock, keyfile=CERTFILE)
-        self.assertRaisesRegexp(ValueError,
+        self.assertRaisesRegex(ValueError,
                         "certfile must be specified for server-side operations",
                         ssl.wrap_socket, sock, server_side=True)
-        self.assertRaisesRegexp(ValueError,
+        self.assertRaisesRegex(ValueError,
                         "certfile must be specified for server-side operations",
                         ssl.wrap_socket, sock, server_side=True, certfile="")
         s = ssl.wrap_socket(sock, server_side=True, certfile=CERTFILE)
-        self.assertRaisesRegexp(ValueError, "can't connect in server-side mode",
+        self.assertRaisesRegex(ValueError, "can't connect in server-side mode",
                                 s.connect, (HOST, 8080))
         with self.assertRaises(IOError) as cm:
             with socket.socket() as sock:
@@ -310,7 +310,7 @@
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
         ctx.set_ciphers("ALL")
         ctx.set_ciphers("DEFAULT")
-        with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
+        with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"):
             ctx.set_ciphers("^$:,;?*'dorothyx")
 
     @skip_if_broken_ubuntu_ssl
@@ -358,24 +358,24 @@
         with self.assertRaises(IOError) as cm:
             ctx.load_cert_chain(WRONGCERT)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
-        with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+        with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
             ctx.load_cert_chain(BADCERT)
-        with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+        with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
             ctx.load_cert_chain(EMPTYCERT)
         # Separate key and cert
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
         ctx.load_cert_chain(ONLYCERT, ONLYKEY)
         ctx.load_cert_chain(certfile=ONLYCERT, keyfile=ONLYKEY)
         ctx.load_cert_chain(certfile=BYTES_ONLYCERT, keyfile=BYTES_ONLYKEY)
-        with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+        with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
             ctx.load_cert_chain(ONLYCERT)
-        with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+        with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
             ctx.load_cert_chain(ONLYKEY)
-        with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+        with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
             ctx.load_cert_chain(certfile=ONLYKEY, keyfile=ONLYCERT)
         # Mismatching key and cert
         ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
-        with self.assertRaisesRegexp(ssl.SSLError, "key values mismatch"):
+        with self.assertRaisesRegex(ssl.SSLError, "key values mismatch"):
             ctx.load_cert_chain(SVN_PYTHON_ORG_ROOT_CERT, ONLYKEY)
 
     def test_load_verify_locations(self):
@@ -389,11 +389,14 @@
         with self.assertRaises(IOError) as cm:
             ctx.load_verify_locations(WRONGCERT)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
-        with self.assertRaisesRegexp(ssl.SSLError, "PEM lib"):
+        with self.assertRaisesRegex(ssl.SSLError, "PEM lib"):
             ctx.load_verify_locations(BADCERT)
         ctx.load_verify_locations(CERTFILE, CAPATH)
         ctx.load_verify_locations(CERTFILE, capath=BYTES_CAPATH)
 
+        # Issue #10989: crash if the second argument type is invalid
+        self.assertRaises(TypeError, ctx.load_verify_locations, None, True)
+
     @skip_if_broken_ubuntu_ssl
     def test_session_stats(self):
         for proto in PROTOCOLS:
@@ -412,6 +415,12 @@
                 'cache_full': 0,
             })
 
+    def test_set_default_verify_paths(self):
+        # There's not much we can do to test that it acts as expected,
+        # so just check it doesn't crash or raise an exception.
+        ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
+        ctx.set_default_verify_paths()
+
 
 class NetworkedTests(unittest.TestCase):
 
@@ -428,8 +437,8 @@
             # this should fail because we have no verification certs
             s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                 cert_reqs=ssl.CERT_REQUIRED)
-            self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed",
-                                    s.connect, ("svn.python.org", 443))
+            self.assertRaisesRegex(ssl.SSLError, "certificate verify failed",
+                                   s.connect, ("svn.python.org", 443))
             s.close()
 
             # this should succeed because we specify the root cert
@@ -463,7 +472,7 @@
             # This should fail because we have no verification certs
             ctx.verify_mode = ssl.CERT_REQUIRED
             s = ctx.wrap_socket(socket.socket(socket.AF_INET))
-            self.assertRaisesRegexp(ssl.SSLError, "certificate verify failed",
+            self.assertRaisesRegex(ssl.SSLError, "certificate verify failed",
                                     s.connect, ("svn.python.org", 443))
             s.close()
             # This should succeed because we specify the root cert
@@ -581,7 +590,7 @@
                                 cert_reqs=ssl.CERT_NONE, ciphers="DEFAULT")
             s.connect(remote)
             # Error checking can happen at instantiation or when connecting
-            with self.assertRaisesRegexp(ssl.SSLError, "No cipher can be selected"):
+            with self.assertRaisesRegex(ssl.SSLError, "No cipher can be selected"):
                 with socket.socket(socket.AF_INET) as sock:
                     s = ssl.wrap_socket(sock,
                                         cert_reqs=ssl.CERT_NONE, ciphers="^$:,;?*'dorothyx")
@@ -593,10 +602,10 @@
         # SHA256 was added in OpenSSL 0.9.8
         if ssl.OPENSSL_VERSION_INFO < (0, 9, 8, 0, 15):
             self.skipTest("SHA256 not available on %r" % ssl.OPENSSL_VERSION)
-        # NOTE: https://sha256.tbs-internet.com is another possible test host
-        remote = ("sha2.hboeck.de", 443)
+        # https://sha2.hboeck.de/ was used until 2011-01-08 (no route to host)
+        remote = ("sha256.tbs-internet.com", 443)
         sha256_cert = os.path.join(os.path.dirname(__file__), "sha256.pem")
-        with support.transient_internet("sha2.hboeck.de"):
+        with support.transient_internet("sha256.tbs-internet.com"):
             s = ssl.wrap_socket(socket.socket(socket.AF_INET),
                                 cert_reqs=ssl.CERT_REQUIRED,
                                 ca_certs=sha256_cert,)
@@ -1493,8 +1502,8 @@
                     c.settimeout(0.2)
                     c.connect((host, port))
                     # Will attempt handshake and time out
-                    self.assertRaisesRegexp(ssl.SSLError, "timed out",
-                                            ssl.wrap_socket, c)
+                    self.assertRaisesRegex(socket.timeout, "timed out",
+                                           ssl.wrap_socket, c)
                 finally:
                     c.close()
                 try:
@@ -1502,8 +1511,8 @@
                     c = ssl.wrap_socket(c)
                     c.settimeout(0.2)
                     # Will attempt handshake and time out
-                    self.assertRaisesRegexp(ssl.SSLError, "timed out",
-                                            c.connect, (host, port))
+                    self.assertRaisesRegex(socket.timeout, "timed out",
+                                           c.connect, (host, port))
                 finally:
                     c.close()
             finally:

Modified: python/branches/pep-3151/Lib/test/test_strlit.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_strlit.py	(original)
+++ python/branches/pep-3151/Lib/test/test_strlit.py	Sat Feb 26 08:16:32 2011
@@ -130,7 +130,7 @@
         self.assertRaises(SyntaxError, self.check_encoding, "utf-8", extra)
 
     def test_file_utf8(self):
-        self.check_encoding("utf8")
+        self.check_encoding("utf-8")
 
     def test_file_iso_8859_1(self):
         self.check_encoding("iso-8859-1")

Modified: python/branches/pep-3151/Lib/test/test_struct.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_struct.py	(original)
+++ python/branches/pep-3151/Lib/test/test_struct.py	Sat Feb 26 08:16:32 2011
@@ -82,58 +82,52 @@
         # Test some of the new features in detail
         # (format, argument, big-endian result, little-endian result, asymmetric)
         tests = [
-            ('c', 'a', 'a', 'a', 0),
-            ('xc', 'a', '\0a', '\0a', 0),
-            ('cx', 'a', 'a\0', 'a\0', 0),
-            ('s', 'a', 'a', 'a', 0),
-            ('0s', 'helloworld', '', '', 1),
-            ('1s', 'helloworld', 'h', 'h', 1),
-            ('9s', 'helloworld', 'helloworl', 'helloworl', 1),
-            ('10s', 'helloworld', 'helloworld', 'helloworld', 0),
-            ('11s', 'helloworld', 'helloworld\0', 'helloworld\0', 1),
-            ('20s', 'helloworld', 'helloworld'+10*'\0', 'helloworld'+10*'\0', 1),
-            ('b', 7, '\7', '\7', 0),
-            ('b', -7, '\371', '\371', 0),
-            ('B', 7, '\7', '\7', 0),
-            ('B', 249, '\371', '\371', 0),
-            ('h', 700, '\002\274', '\274\002', 0),
-            ('h', -700, '\375D', 'D\375', 0),
-            ('H', 700, '\002\274', '\274\002', 0),
-            ('H', 0x10000-700, '\375D', 'D\375', 0),
-            ('i', 70000000, '\004,\035\200', '\200\035,\004', 0),
-            ('i', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
-            ('I', 70000000, '\004,\035\200', '\200\035,\004', 0),
-            ('I', 0x100000000-70000000, '\373\323\342\200', '\200\342\323\373', 0),
-            ('l', 70000000, '\004,\035\200', '\200\035,\004', 0),
-            ('l', -70000000, '\373\323\342\200', '\200\342\323\373', 0),
-            ('L', 70000000, '\004,\035\200', '\200\035,\004', 0),
-            ('L', 0x100000000-70000000, '\373\323\342\200', '\200\342\323\373', 0),
-            ('f', 2.0, '@\000\000\000', '\000\000\000@', 0),
-            ('d', 2.0, '@\000\000\000\000\000\000\000',
-                       '\000\000\000\000\000\000\000@', 0),
-            ('f', -2.0, '\300\000\000\000', '\000\000\000\300', 0),
-            ('d', -2.0, '\300\000\000\000\000\000\000\000',
-                       '\000\000\000\000\000\000\000\300', 0),
-                ('?', 0, '\0', '\0', 0),
-                ('?', 3, '\1', '\1', 1),
-                ('?', True, '\1', '\1', 0),
-                ('?', [], '\0', '\0', 1),
-                ('?', (1,), '\1', '\1', 1),
+            ('c', b'a', b'a', b'a', 0),
+            ('xc', b'a', b'\0a', b'\0a', 0),
+            ('cx', b'a', b'a\0', b'a\0', 0),
+            ('s', b'a', b'a', b'a', 0),
+            ('0s', b'helloworld', b'', b'', 1),
+            ('1s', b'helloworld', b'h', b'h', 1),
+            ('9s', b'helloworld', b'helloworl', b'helloworl', 1),
+            ('10s', b'helloworld', b'helloworld', b'helloworld', 0),
+            ('11s', b'helloworld', b'helloworld\0', b'helloworld\0', 1),
+            ('20s', b'helloworld', b'helloworld'+10*b'\0', b'helloworld'+10*b'\0', 1),
+            ('b', 7, b'\7', b'\7', 0),
+            ('b', -7, b'\371', b'\371', 0),
+            ('B', 7, b'\7', b'\7', 0),
+            ('B', 249, b'\371', b'\371', 0),
+            ('h', 700, b'\002\274', b'\274\002', 0),
+            ('h', -700, b'\375D', b'D\375', 0),
+            ('H', 700, b'\002\274', b'\274\002', 0),
+            ('H', 0x10000-700, b'\375D', b'D\375', 0),
+            ('i', 70000000, b'\004,\035\200', b'\200\035,\004', 0),
+            ('i', -70000000, b'\373\323\342\200', b'\200\342\323\373', 0),
+            ('I', 70000000, b'\004,\035\200', b'\200\035,\004', 0),
+            ('I', 0x100000000-70000000, b'\373\323\342\200', b'\200\342\323\373', 0),
+            ('l', 70000000, b'\004,\035\200', b'\200\035,\004', 0),
+            ('l', -70000000, b'\373\323\342\200', b'\200\342\323\373', 0),
+            ('L', 70000000, b'\004,\035\200', b'\200\035,\004', 0),
+            ('L', 0x100000000-70000000, b'\373\323\342\200', b'\200\342\323\373', 0),
+            ('f', 2.0, b'@\000\000\000', b'\000\000\000@', 0),
+            ('d', 2.0, b'@\000\000\000\000\000\000\000',
+                       b'\000\000\000\000\000\000\000@', 0),
+            ('f', -2.0, b'\300\000\000\000', b'\000\000\000\300', 0),
+            ('d', -2.0, b'\300\000\000\000\000\000\000\000',
+                        b'\000\000\000\000\000\000\000\300', 0),
+            ('?', 0, b'\0', b'\0', 0),
+            ('?', 3, b'\1', b'\1', 1),
+            ('?', True, b'\1', b'\1', 0),
+            ('?', [], b'\0', b'\0', 1),
+            ('?', (1,), b'\1', b'\1', 1),
         ]
 
         for fmt, arg, big, lil, asy in tests:
-            big = bytes(big, "latin-1")
-            lil = bytes(lil, "latin-1")
             for (xfmt, exp) in [('>'+fmt, big), ('!'+fmt, big), ('<'+fmt, lil),
                                 ('='+fmt, ISBIGENDIAN and big or lil)]:
                 res = struct.pack(xfmt, arg)
                 self.assertEqual(res, exp)
                 self.assertEqual(struct.calcsize(xfmt), len(res))
                 rev = struct.unpack(xfmt, res)[0]
-                if isinstance(arg, str):
-                    # Strings are returned as bytes since you can't know the
-                    # encoding of the string when packed.
-                    arg = bytes(arg, 'latin1')
                 if rev != arg:
                     self.assertTrue(asy)
 
@@ -334,15 +328,14 @@
     def test_p_code(self):
         # Test p ("Pascal string") code.
         for code, input, expected, expectedback in [
-                ('p','abc', '\x00', b''),
-                ('1p', 'abc', '\x00', b''),
-                ('2p', 'abc', '\x01a', b'a'),
-                ('3p', 'abc', '\x02ab', b'ab'),
-                ('4p', 'abc', '\x03abc', b'abc'),
-                ('5p', 'abc', '\x03abc\x00', b'abc'),
-                ('6p', 'abc', '\x03abc\x00\x00', b'abc'),
-                ('1000p', 'x'*1000, '\xff' + 'x'*999, b'x'*255)]:
-            expected = bytes(expected, "latin-1")
+                ('p',  b'abc', b'\x00',            b''),
+                ('1p', b'abc', b'\x00',            b''),
+                ('2p', b'abc', b'\x01a',           b'a'),
+                ('3p', b'abc', b'\x02ab',          b'ab'),
+                ('4p', b'abc', b'\x03abc',         b'abc'),
+                ('5p', b'abc', b'\x03abc\x00',     b'abc'),
+                ('6p', b'abc', b'\x03abc\x00\x00', b'abc'),
+                ('1000p', b'x'*1000, b'\xff' + b'x'*999, b'x'*255)]:
             got = struct.pack(code, input)
             self.assertEqual(got, expected)
             (got,) = struct.unpack(code, got)
@@ -401,15 +394,11 @@
         s = struct.Struct(fmt)
         for cls in (bytes, bytearray):
             data = cls(test_string)
-            if not isinstance(data, (bytes, bytearray)):
-                bytes_data = bytes(data, 'latin1')
-            else:
-                bytes_data = data
             self.assertEqual(s.unpack_from(data), (b'abcd',))
             self.assertEqual(s.unpack_from(data, 2), (b'cd01',))
             self.assertEqual(s.unpack_from(data, 4), (b'0123',))
             for i in range(6):
-                self.assertEqual(s.unpack_from(data, i), (bytes_data[i:i+4],))
+                self.assertEqual(s.unpack_from(data, i), (data[i:i+4],))
             for i in range(6, len(test_string) + 1):
                 self.assertRaises(struct.error, s.unpack_from, data, i)
         for cls in (bytes, bytearray):

Modified: python/branches/pep-3151/Lib/test/test_structmembers.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_structmembers.py	(original)
+++ python/branches/pep-3151/Lib/test/test_structmembers.py	Sat Feb 26 08:16:32 2011
@@ -28,64 +28,64 @@
 
     def test_bool(self):
         ts.T_BOOL = True
-        self.assertEquals(ts.T_BOOL, True)
+        self.assertEqual(ts.T_BOOL, True)
         ts.T_BOOL = False
-        self.assertEquals(ts.T_BOOL, False)
+        self.assertEqual(ts.T_BOOL, False)
         self.assertRaises(TypeError, setattr, ts, 'T_BOOL', 1)
 
     def test_byte(self):
         ts.T_BYTE = CHAR_MAX
-        self.assertEquals(ts.T_BYTE, CHAR_MAX)
+        self.assertEqual(ts.T_BYTE, CHAR_MAX)
         ts.T_BYTE = CHAR_MIN
-        self.assertEquals(ts.T_BYTE, CHAR_MIN)
+        self.assertEqual(ts.T_BYTE, CHAR_MIN)
         ts.T_UBYTE = UCHAR_MAX
-        self.assertEquals(ts.T_UBYTE, UCHAR_MAX)
+        self.assertEqual(ts.T_UBYTE, UCHAR_MAX)
 
     def test_short(self):
         ts.T_SHORT = SHRT_MAX
-        self.assertEquals(ts.T_SHORT, SHRT_MAX)
+        self.assertEqual(ts.T_SHORT, SHRT_MAX)
         ts.T_SHORT = SHRT_MIN
-        self.assertEquals(ts.T_SHORT, SHRT_MIN)
+        self.assertEqual(ts.T_SHORT, SHRT_MIN)
         ts.T_USHORT = USHRT_MAX
-        self.assertEquals(ts.T_USHORT, USHRT_MAX)
+        self.assertEqual(ts.T_USHORT, USHRT_MAX)
 
     def test_int(self):
         ts.T_INT = INT_MAX
-        self.assertEquals(ts.T_INT, INT_MAX)
+        self.assertEqual(ts.T_INT, INT_MAX)
         ts.T_INT = INT_MIN
-        self.assertEquals(ts.T_INT, INT_MIN)
+        self.assertEqual(ts.T_INT, INT_MIN)
         ts.T_UINT = UINT_MAX
-        self.assertEquals(ts.T_UINT, UINT_MAX)
+        self.assertEqual(ts.T_UINT, UINT_MAX)
 
     def test_long(self):
         ts.T_LONG = LONG_MAX
-        self.assertEquals(ts.T_LONG, LONG_MAX)
+        self.assertEqual(ts.T_LONG, LONG_MAX)
         ts.T_LONG = LONG_MIN
-        self.assertEquals(ts.T_LONG, LONG_MIN)
+        self.assertEqual(ts.T_LONG, LONG_MIN)
         ts.T_ULONG = ULONG_MAX
-        self.assertEquals(ts.T_ULONG, ULONG_MAX)
+        self.assertEqual(ts.T_ULONG, ULONG_MAX)
 
     def test_py_ssize_t(self):
         ts.T_PYSSIZET = PY_SSIZE_T_MAX
-        self.assertEquals(ts.T_PYSSIZET, PY_SSIZE_T_MAX)
+        self.assertEqual(ts.T_PYSSIZET, PY_SSIZE_T_MAX)
         ts.T_PYSSIZET = PY_SSIZE_T_MIN
-        self.assertEquals(ts.T_PYSSIZET, PY_SSIZE_T_MIN)
+        self.assertEqual(ts.T_PYSSIZET, PY_SSIZE_T_MIN)
 
     @unittest.skipUnless(hasattr(ts, "T_LONGLONG"), "long long not present")
     def test_longlong(self):
         ts.T_LONGLONG = LLONG_MAX
-        self.assertEquals(ts.T_LONGLONG, LLONG_MAX)
+        self.assertEqual(ts.T_LONGLONG, LLONG_MAX)
         ts.T_LONGLONG = LLONG_MIN
-        self.assertEquals(ts.T_LONGLONG, LLONG_MIN)
+        self.assertEqual(ts.T_LONGLONG, LLONG_MIN)
 
         ts.T_ULONGLONG = ULLONG_MAX
-        self.assertEquals(ts.T_ULONGLONG, ULLONG_MAX)
+        self.assertEqual(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)
+        self.assertEqual(ts.T_LONGLONG, 3)
         ts.T_ULONGLONG = 4
-        self.assertEquals(ts.T_ULONGLONG, 4)
+        self.assertEqual(ts.T_ULONGLONG, 4)
 
     def test_bad_assignments(self):
         integer_attributes = [
@@ -106,7 +106,7 @@
                 self.assertRaises(TypeError, setattr, ts, attr, nonint)
 
     def test_inplace_string(self):
-        self.assertEquals(ts.T_STRING_INPLACE, "hi")
+        self.assertEqual(ts.T_STRING_INPLACE, "hi")
         self.assertRaises(TypeError, setattr, ts, "T_STRING_INPLACE", "s")
         self.assertRaises(TypeError, delattr, ts, "T_STRING_INPLACE")
 

Modified: python/branches/pep-3151/Lib/test/test_subprocess.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_subprocess.py	(original)
+++ python/branches/pep-3151/Lib/test/test_subprocess.py	Sat Feb 26 08:16:32 2011
@@ -9,6 +9,8 @@
 import time
 import re
 import sysconfig
+import warnings
+import select
 try:
     import gc
 except ImportError:
@@ -364,22 +366,28 @@
         self.assertEqual(stdout, b"banana")
         self.assertStderrEqual(stderr, b"pineapple")
 
-    # This test is Linux specific for simplicity to at least have
-    # some coverage.  It is not a platform specific bug.
-    @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
-                         "Linux specific")
     # Test for the fd leak reported in http://bugs.python.org/issue2791.
     def test_communicate_pipe_fd_leak(self):
-        fd_directory = '/proc/%d/fd' % os.getpid()
-        num_fds_before_popen = len(os.listdir(fd_directory))
-        p = subprocess.Popen([sys.executable, "-c", "print()"],
-                             stdout=subprocess.PIPE)
-        p.communicate()
-        num_fds_after_communicate = len(os.listdir(fd_directory))
-        del p
-        num_fds_after_destruction = len(os.listdir(fd_directory))
-        self.assertEqual(num_fds_before_popen, num_fds_after_destruction)
-        self.assertEqual(num_fds_before_popen, num_fds_after_communicate)
+        for stdin_pipe in (False, True):
+            for stdout_pipe in (False, True):
+                for stderr_pipe in (False, True):
+                    options = {}
+                    if stdin_pipe:
+                        options['stdin'] = subprocess.PIPE
+                    if stdout_pipe:
+                        options['stdout'] = subprocess.PIPE
+                    if stderr_pipe:
+                        options['stderr'] = subprocess.PIPE
+                    if not options:
+                        continue
+                    p = subprocess.Popen((sys.executable, "-c", "pass"), **options)
+                    p.communicate()
+                    if p.stdin is not None:
+                        self.assertTrue(p.stdin.closed)
+                    if p.stdout is not None:
+                        self.assertTrue(p.stdout.closed)
+                    if p.stderr is not None:
+                        self.assertTrue(p.stderr.closed)
 
     def test_communicate_returns(self):
         # communicate() should return None if no redirection is active
@@ -591,7 +599,7 @@
                 "[sys.executable, '-c', 'print(\"Hello World!\")'])",
             'assert retcode == 0'))
         output = subprocess.check_output([sys.executable, '-c', code])
-        self.assert_(output.startswith(b'Hello World!'), ascii(output))
+        self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
 
     def test_handles_closed_on_exception(self):
         # If CreateProcess exits with an error, ensure the
@@ -666,6 +674,7 @@
             # string and instead capture the exception that we want to see
             # below for comparison.
             desired_exception = e
+            desired_exception.strerror += ': ' + repr(sys.executable)
         else:
             self.fail("chdir to nonexistant directory %s succeeded." %
                       nonexistent_dir)
@@ -894,6 +903,106 @@
         self.assertStderrEqual(stderr, b'')
         self.assertEqual(p.wait(), -signal.SIGTERM)
 
+    def check_close_std_fds(self, fds):
+        # Issue #9905: test that subprocess pipes still work properly with
+        # some standard fds closed
+        stdin = 0
+        newfds = []
+        for a in fds:
+            b = os.dup(a)
+            newfds.append(b)
+            if a == 0:
+                stdin = b
+        try:
+            for fd in fds:
+                os.close(fd)
+            out, err = subprocess.Popen([sys.executable, "-c",
+                              'import sys;'
+                              'sys.stdout.write("apple");'
+                              'sys.stdout.flush();'
+                              'sys.stderr.write("orange")'],
+                       stdin=stdin,
+                       stdout=subprocess.PIPE,
+                       stderr=subprocess.PIPE).communicate()
+            err = support.strip_python_stderr(err)
+            self.assertEqual((out, err), (b'apple', b'orange'))
+        finally:
+            for b, a in zip(newfds, fds):
+                os.dup2(b, a)
+            for b in newfds:
+                os.close(b)
+
+    def test_close_fd_0(self):
+        self.check_close_std_fds([0])
+
+    def test_close_fd_1(self):
+        self.check_close_std_fds([1])
+
+    def test_close_fd_2(self):
+        self.check_close_std_fds([2])
+
+    def test_close_fds_0_1(self):
+        self.check_close_std_fds([0, 1])
+
+    def test_close_fds_0_2(self):
+        self.check_close_std_fds([0, 2])
+
+    def test_close_fds_1_2(self):
+        self.check_close_std_fds([1, 2])
+
+    def test_close_fds_0_1_2(self):
+        # Issue #10806: test that subprocess pipes still work properly with
+        # all standard fds closed.
+        self.check_close_std_fds([0, 1, 2])
+
+    def test_remapping_std_fds(self):
+        # open up some temporary files
+        temps = [mkstemp() for i in range(3)]
+        try:
+            temp_fds = [fd for fd, fname in temps]
+
+            # unlink the files -- we won't need to reopen them
+            for fd, fname in temps:
+                os.unlink(fname)
+
+            # write some data to what will become stdin, and rewind
+            os.write(temp_fds[1], b"STDIN")
+            os.lseek(temp_fds[1], 0, 0)
+
+            # move the standard file descriptors out of the way
+            saved_fds = [os.dup(fd) for fd in range(3)]
+            try:
+                # duplicate the file objects over the standard fd's
+                for fd, temp_fd in enumerate(temp_fds):
+                    os.dup2(temp_fd, fd)
+
+                # now use those files in the "wrong" order, so that subprocess
+                # has to rearrange them in the child
+                p = subprocess.Popen([sys.executable, "-c",
+                    'import sys; got = sys.stdin.read();'
+                    'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
+                    stdin=temp_fds[1],
+                    stdout=temp_fds[2],
+                    stderr=temp_fds[0])
+                p.wait()
+            finally:
+                # restore the original fd's underneath sys.stdin, etc.
+                for std, saved in enumerate(saved_fds):
+                    os.dup2(saved, std)
+                    os.close(saved)
+
+            for fd in temp_fds:
+                os.lseek(fd, 0, 0)
+
+            out = os.read(temp_fds[2], 1024)
+            err = support.strip_python_stderr(os.read(temp_fds[0], 1024))
+            self.assertEqual(out, b"got STDIN")
+            self.assertEqual(err, b"err")
+
+        finally:
+            for fd in temp_fds:
+                os.close(fd)
+
     def test_surrogates_error_message(self):
         def prepare():
             raise ValueError("surrogate:\uDCff")
@@ -927,7 +1036,7 @@
                 [sys.executable, "-c", script],
                 env=env)
             stdout = stdout.rstrip(b'\n\r')
-            self.assertEquals(stdout.decode('ascii'), ascii(value))
+            self.assertEqual(stdout.decode('ascii'), ascii(value))
 
             # test bytes
             key = key.encode("ascii", "surrogateescape")
@@ -939,7 +1048,7 @@
                 [sys.executable, "-c", script],
                 env=env)
             stdout = stdout.rstrip(b'\n\r')
-            self.assertEquals(stdout.decode('ascii'), ascii(value))
+            self.assertEqual(stdout.decode('ascii'), ascii(value))
 
     def test_bytes_program(self):
         abs_program = os.fsencode(sys.executable)
@@ -948,19 +1057,141 @@
 
         # absolute bytes path
         exitcode = subprocess.call([abs_program, "-c", "pass"])
-        self.assertEquals(exitcode, 0)
+        self.assertEqual(exitcode, 0)
 
         # bytes program, unicode PATH
         env = os.environ.copy()
         env["PATH"] = path
         exitcode = subprocess.call([program, "-c", "pass"], env=env)
-        self.assertEquals(exitcode, 0)
+        self.assertEqual(exitcode, 0)
 
         # bytes program, bytes PATH
         envb = os.environb.copy()
         envb[b"PATH"] = os.fsencode(path)
         exitcode = subprocess.call([program, "-c", "pass"], env=envb)
-        self.assertEquals(exitcode, 0)
+        self.assertEqual(exitcode, 0)
+
+    def test_pipe_cloexec(self):
+        sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
+        fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
+
+        p1 = subprocess.Popen([sys.executable, sleeper],
+                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                              stderr=subprocess.PIPE, close_fds=False)
+
+        self.addCleanup(p1.communicate, b'')
+
+        p2 = subprocess.Popen([sys.executable, fd_status],
+                              stdout=subprocess.PIPE, close_fds=False)
+
+        output, error = p2.communicate()
+        result_fds = set(map(int, output.split(b',')))
+        unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
+                            p1.stderr.fileno()])
+
+        self.assertFalse(result_fds & unwanted_fds,
+                         "Expected no fds from %r to be open in child, "
+                         "found %r" %
+                              (unwanted_fds, result_fds & unwanted_fds))
+
+    def test_pipe_cloexec_real_tools(self):
+        qcat = support.findfile("qcat.py", subdir="subprocessdata")
+        qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
+
+        subdata = b'zxcvbn'
+        data = subdata * 4 + b'\n'
+
+        p1 = subprocess.Popen([sys.executable, qcat],
+                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+                              close_fds=False)
+
+        p2 = subprocess.Popen([sys.executable, qgrep, subdata],
+                              stdin=p1.stdout, stdout=subprocess.PIPE,
+                              close_fds=False)
+
+        self.addCleanup(p1.wait)
+        self.addCleanup(p2.wait)
+        self.addCleanup(p1.terminate)
+        self.addCleanup(p2.terminate)
+
+        p1.stdin.write(data)
+        p1.stdin.close()
+
+        readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
+
+        self.assertTrue(readfiles, "The child hung")
+        self.assertEqual(p2.stdout.read(), data)
+
+        p1.stdout.close()
+        p2.stdout.close()
+
+    def test_close_fds(self):
+        fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
+
+        fds = os.pipe()
+        self.addCleanup(os.close, fds[0])
+        self.addCleanup(os.close, fds[1])
+
+        open_fds = set(fds)
+
+        p = subprocess.Popen([sys.executable, fd_status],
+                             stdout=subprocess.PIPE, close_fds=False)
+        output, ignored = p.communicate()
+        remaining_fds = set(map(int, output.split(b',')))
+
+        self.assertEqual(remaining_fds & open_fds, open_fds,
+                         "Some fds were closed")
+
+        p = subprocess.Popen([sys.executable, fd_status],
+                             stdout=subprocess.PIPE, close_fds=True)
+        output, ignored = p.communicate()
+        remaining_fds = set(map(int, output.split(b',')))
+
+        self.assertFalse(remaining_fds & open_fds,
+                         "Some fds were left open")
+        self.assertIn(1, remaining_fds, "Subprocess failed")
+
+    def test_pass_fds(self):
+        fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
+
+        open_fds = set()
+
+        for x in range(5):
+            fds = os.pipe()
+            self.addCleanup(os.close, fds[0])
+            self.addCleanup(os.close, fds[1])
+            open_fds.update(fds)
+
+        for fd in open_fds:
+            p = subprocess.Popen([sys.executable, fd_status],
+                                 stdout=subprocess.PIPE, close_fds=True,
+                                 pass_fds=(fd, ))
+            output, ignored = p.communicate()
+
+            remaining_fds = set(map(int, output.split(b',')))
+            to_be_closed = open_fds - {fd}
+
+            self.assertIn(fd, remaining_fds, "fd to be passed not passed")
+            self.assertFalse(remaining_fds & to_be_closed,
+                             "fd to be closed passed")
+
+            # pass_fds overrides close_fds with a warning.
+            with self.assertWarns(RuntimeWarning) as context:
+                self.assertFalse(subprocess.call(
+                        [sys.executable, "-c", "import sys; sys.exit(0)"],
+                        close_fds=False, pass_fds=(fd, )))
+            self.assertIn('overriding close_fds', str(context.warning))
+
+    def test_wait_when_sigchild_ignored(self):
+        # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
+        sigchild_ignore = support.findfile("sigchild_ignore.py",
+                                           subdir="subprocessdata")
+        p = subprocess.Popen([sys.executable, sigchild_ignore],
+                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+        stdout, stderr = p.communicate()
+        self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
+                         " non-zero with this error:\n%s" %
+                         stderr.decode('utf-8'))
 
 
 @unittest.skipUnless(mswindows, "Windows specific tests")
@@ -1182,6 +1413,47 @@
         # call() function with sequence argument with spaces on Windows
         self.with_spaces([sys.executable, self.fname, "ab cd"])
 
+
+class ContextManagerTests(ProcessTestCase):
+
+    def test_pipe(self):
+        with subprocess.Popen([sys.executable, "-c",
+                               "import sys;"
+                               "sys.stdout.write('stdout');"
+                               "sys.stderr.write('stderr');"],
+                              stdout=subprocess.PIPE,
+                              stderr=subprocess.PIPE) as proc:
+            self.assertEqual(proc.stdout.read(), b"stdout")
+            self.assertStderrEqual(proc.stderr.read(), b"stderr")
+
+        self.assertTrue(proc.stdout.closed)
+        self.assertTrue(proc.stderr.closed)
+
+    def test_returncode(self):
+        with subprocess.Popen([sys.executable, "-c",
+                               "import sys; sys.exit(100)"]) as proc:
+            proc.wait()
+        self.assertEqual(proc.returncode, 100)
+
+    def test_communicate_stdin(self):
+        with subprocess.Popen([sys.executable, "-c",
+                              "import sys;"
+                              "sys.exit(sys.stdin.read() == 'context')"],
+                             stdin=subprocess.PIPE) as proc:
+            proc.communicate(b"context")
+            self.assertEqual(proc.returncode, 1)
+
+    def test_invalid_args(self):
+        with self.assertRaises(EnvironmentError) as c:
+            with subprocess.Popen(['nonexisting_i_hope'],
+                                  stdout=subprocess.PIPE,
+                                  stderr=subprocess.PIPE) as proc:
+                pass
+
+            if c.exception.errno != errno.ENOENT:  # ignore "no such file"
+                raise c.exception
+
+
 def test_main():
     unit_tests = (ProcessTestCase,
                   POSIXProcessTestCase,
@@ -1190,7 +1462,8 @@
                   CommandTests,
                   ProcessTestCaseNoPoll,
                   HelperFunctionTests,
-                  CommandsWithSpaces)
+                  CommandsWithSpaces,
+                  ContextManagerTests)
 
     support.run_unittest(*unit_tests)
     support.reap_children()

Modified: python/branches/pep-3151/Lib/test/test_sys.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_sys.py	(original)
+++ python/branches/pep-3151/Lib/test/test_sys.py	Sat Feb 26 08:16:32 2011
@@ -93,7 +93,7 @@
         try:
             sys.exit(0)
         except SystemExit as exc:
-            self.assertEquals(exc.code, 0)
+            self.assertEqual(exc.code, 0)
         except:
             self.fail("wrong exception")
         else:
@@ -104,7 +104,7 @@
         try:
             sys.exit(42)
         except SystemExit as exc:
-            self.assertEquals(exc.code, 42)
+            self.assertEqual(exc.code, 42)
         except:
             self.fail("wrong exception")
         else:
@@ -114,7 +114,7 @@
         try:
             sys.exit((42,))
         except SystemExit as exc:
-            self.assertEquals(exc.code, 42)
+            self.assertEqual(exc.code, 42)
         except:
             self.fail("wrong exception")
         else:
@@ -124,7 +124,7 @@
         try:
             sys.exit("exit")
         except SystemExit as exc:
-            self.assertEquals(exc.code, "exit")
+            self.assertEqual(exc.code, "exit")
         except:
             self.fail("wrong exception")
         else:
@@ -134,7 +134,7 @@
         try:
             sys.exit((17, 23))
         except SystemExit as exc:
-            self.assertEquals(exc.code, (17, 23))
+            self.assertEqual(exc.code, (17, 23))
         except:
             self.fail("wrong exception")
         else:
@@ -188,7 +188,7 @@
             orig = sys.getcheckinterval()
             for n in 0, 100, 120, orig: # orig last to restore starting state
                 sys.setcheckinterval(n)
-                self.assertEquals(sys.getcheckinterval(), n)
+                self.assertEqual(sys.getcheckinterval(), n)
 
     @unittest.skipUnless(threading, 'Threading required for this test.')
     def test_switchinterval(self):
@@ -202,7 +202,7 @@
         try:
             for n in 0.00001, 0.05, 3.0, orig:
                 sys.setswitchinterval(n)
-                self.assertAlmostEquals(sys.getswitchinterval(), n)
+                self.assertAlmostEqual(sys.getswitchinterval(), n)
         finally:
             sys.setswitchinterval(orig)
 
@@ -215,6 +215,8 @@
         self.assertEqual(sys.getrecursionlimit(), 10000)
         sys.setrecursionlimit(oldlimit)
 
+    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
+                     'fatal error if run with a trace function')
     def test_recursionlimit_recovery(self):
         # NOTE: this test is slightly fragile in that it depends on the current
         # recursion count when executing the test being low enough so as to
@@ -301,6 +303,7 @@
             self.assertEqual(sys.getdlopenflags(), oldflags+1)
             sys.setdlopenflags(oldflags)
 
+    @test.support.refcount_test
     def test_refcount(self):
         # n here must be a global in order for this test to pass while
         # tracing with a python function.  Tracing calls PyFrame_FastToLocals
@@ -501,7 +504,7 @@
         attrs = ("debug", "division_warning",
                  "inspect", "interactive", "optimize", "dont_write_bytecode",
                  "no_user_site", "no_site", "ignore_environment", "verbose",
-                 "bytes_warning")
+                 "bytes_warning", "quiet")
         for attr in attrs:
             self.assertTrue(hasattr(sys.flags, attr), attr)
             self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
@@ -569,7 +572,7 @@
     TPFLAGS_HEAPTYPE = 1<<9
 
     def setUp(self):
-        self.c = len(struct.pack('c', ' '))
+        self.c = len(struct.pack('c', b' '))
         self.H = len(struct.pack('H', 0))
         self.i = len(struct.pack('i', 0))
         self.l = len(struct.pack('l', 0))
@@ -782,8 +785,8 @@
         # reverse
         check(reversed(''), size(h + 'PP'))
         # range
-        check(range(1), size(h + '3P'))
-        check(range(66000), size(h + '3P'))
+        check(range(1), size(h + '4P'))
+        check(range(66000), size(h + '4P'))
         # set
         # frozenset
         PySet_MINSIZE = 8

Modified: python/branches/pep-3151/Lib/test/test_sys_settrace.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_sys_settrace.py	(original)
+++ python/branches/pep-3151/Lib/test/test_sys_settrace.py	Sat Feb 26 08:16:32 2011
@@ -251,6 +251,7 @@
     def setUp(self):
         self.using_gc = gc.isenabled()
         gc.disable()
+        self.addCleanup(sys.settrace, sys.gettrace())
 
     def tearDown(self):
         if self.using_gc:
@@ -389,6 +390,9 @@
 
 
 class RaisingTraceFuncTestCase(unittest.TestCase):
+    def setUp(self):
+        self.addCleanup(sys.settrace, sys.gettrace())
+
     def trace(self, frame, event, arg):
         """A trace function that raises an exception in response to a
         specific trace event."""
@@ -688,6 +692,10 @@
 
 
 class JumpTestCase(unittest.TestCase):
+    def setUp(self):
+        self.addCleanup(sys.settrace, sys.gettrace())
+        sys.settrace(None)
+
     def compare_jump_output(self, expected, received):
         if received != expected:
             self.fail( "Outputs don't match:\n" +
@@ -739,6 +747,8 @@
     def test_18_no_jump_to_non_integers(self):
         self.run_test(no_jump_to_non_integers)
     def test_19_no_jump_without_trace_function(self):
+        # Must set sys.settrace(None) in setUp(), else condition is not
+        # triggered.
         no_jump_without_trace_function()
 
     def test_20_large_function(self):

Modified: python/branches/pep-3151/Lib/test/test_sysconfig.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_sysconfig.py	(original)
+++ python/branches/pep-3151/Lib/test/test_sysconfig.py	Sat Feb 26 08:16:32 2011
@@ -88,7 +88,7 @@
             shutil.rmtree(path)
 
     def test_get_path_names(self):
-        self.assertEquals(get_path_names(), sysconfig._SCHEME_KEYS)
+        self.assertEqual(get_path_names(), sysconfig._SCHEME_KEYS)
 
     def test_get_paths(self):
         scheme = get_paths()
@@ -98,7 +98,7 @@
         wanted.sort()
         scheme = list(scheme.items())
         scheme.sort()
-        self.assertEquals(scheme, wanted)
+        self.assertEqual(scheme, wanted)
 
     def test_get_path(self):
         # xxx make real tests here
@@ -117,21 +117,21 @@
         sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
                        '[MSC v.1310 32 bit (Intel)]')
         sys.platform = 'win32'
-        self.assertEquals(get_platform(), 'win32')
+        self.assertEqual(get_platform(), 'win32')
 
         # windows XP, amd64
         os.name = 'nt'
         sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
                        '[MSC v.1310 32 bit (Amd64)]')
         sys.platform = 'win32'
-        self.assertEquals(get_platform(), 'win-amd64')
+        self.assertEqual(get_platform(), 'win-amd64')
 
         # windows XP, itanium
         os.name = 'nt'
         sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
                        '[MSC v.1310 32 bit (Itanium)]')
         sys.platform = 'win32'
-        self.assertEquals(get_platform(), 'win-ia64')
+        self.assertEqual(get_platform(), 'win-ia64')
 
         # macbook
         os.name = 'posix'
@@ -150,9 +150,9 @@
         maxint = sys.maxsize
         try:
             sys.maxsize = 2147483647
-            self.assertEquals(get_platform(), 'macosx-10.3-ppc')
+            self.assertEqual(get_platform(), 'macosx-10.3-ppc')
             sys.maxsize = 9223372036854775807
-            self.assertEquals(get_platform(), 'macosx-10.3-ppc64')
+            self.assertEqual(get_platform(), 'macosx-10.3-ppc64')
         finally:
             sys.maxsize = maxint
 
@@ -169,9 +169,9 @@
         maxint = sys.maxsize
         try:
             sys.maxsize = 2147483647
-            self.assertEquals(get_platform(), 'macosx-10.3-i386')
+            self.assertEqual(get_platform(), 'macosx-10.3-i386')
             sys.maxsize = 9223372036854775807
-            self.assertEquals(get_platform(), 'macosx-10.3-x86_64')
+            self.assertEqual(get_platform(), 'macosx-10.3-x86_64')
         finally:
             sys.maxsize = maxint
 
@@ -182,33 +182,33 @@
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
 
-        self.assertEquals(get_platform(), 'macosx-10.4-fat')
+        self.assertEqual(get_platform(), 'macosx-10.4-fat')
 
         get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
                                        '/Developer/SDKs/MacOSX10.4u.sdk  '
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
 
-        self.assertEquals(get_platform(), 'macosx-10.4-intel')
+        self.assertEqual(get_platform(), 'macosx-10.4-intel')
 
         get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
                                        '/Developer/SDKs/MacOSX10.4u.sdk  '
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
-        self.assertEquals(get_platform(), 'macosx-10.4-fat3')
+        self.assertEqual(get_platform(), 'macosx-10.4-fat3')
 
         get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
                                        '/Developer/SDKs/MacOSX10.4u.sdk  '
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
-        self.assertEquals(get_platform(), 'macosx-10.4-universal')
+        self.assertEqual(get_platform(), 'macosx-10.4-universal')
 
         get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
                                        '/Developer/SDKs/MacOSX10.4u.sdk  '
                                        '-fno-strict-aliasing -fno-common '
                                        '-dynamic -DNDEBUG -g -O3')
 
-        self.assertEquals(get_platform(), 'macosx-10.4-fat64')
+        self.assertEqual(get_platform(), 'macosx-10.4-fat64')
 
         for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
             get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
@@ -216,7 +216,7 @@
                                            '-fno-strict-aliasing -fno-common '
                                            '-dynamic -DNDEBUG -g -O3'%(arch,))
 
-            self.assertEquals(get_platform(), 'macosx-10.4-%s'%(arch,))
+            self.assertEqual(get_platform(), 'macosx-10.4-%s'%(arch,))
 
         # linux debian sarge
         os.name = 'posix'
@@ -226,7 +226,7 @@
         self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
                     '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
 
-        self.assertEquals(get_platform(), 'linux-i686')
+        self.assertEqual(get_platform(), 'linux-i686')
 
         # XXX more platforms to tests here
 
@@ -243,7 +243,7 @@
     def test_get_scheme_names(self):
         wanted = ('nt', 'nt_user', 'os2', 'os2_home', 'osx_framework_user',
                   'posix_home', 'posix_prefix', 'posix_user')
-        self.assertEquals(get_scheme_names(), wanted)
+        self.assertEqual(get_scheme_names(), wanted)
 
     @skip_unless_symlink
     def test_symlink(self):
@@ -275,7 +275,7 @@
         for name in ('stdlib', 'platstdlib', 'purelib', 'platlib'):
             global_path = get_path(name, 'posix_prefix')
             user_path = get_path(name, 'posix_user')
-            self.assertEquals(user_path, global_path.replace(base, user))
+            self.assertEqual(user_path, global_path.replace(base, user))
 
     def test_main(self):
         # just making sure _main() runs and returns things in the stdout

Modified: python/branches/pep-3151/Lib/test/test_syslog.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_syslog.py	(original)
+++ python/branches/pep-3151/Lib/test/test_syslog.py	Sat Feb 26 08:16:32 2011
@@ -11,6 +11,8 @@
 
     def test_openlog(self):
         syslog.openlog('python')
+        # Issue #6697.
+        self.assertRaises(UnicodeEncodeError, syslog.openlog, '\uD800')
 
     def test_syslog(self):
         syslog.openlog('python')

Modified: python/branches/pep-3151/Lib/test/test_tarfile.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_tarfile.py	(original)
+++ python/branches/pep-3151/Lib/test/test_tarfile.py	Sat Feb 26 08:16:32 2011
@@ -419,6 +419,22 @@
 
     mode="r|"
 
+    def test_read_through(self):
+        # Issue #11224: A poorly designed _FileInFile.read() method
+        # caused seeking errors with stream tar files.
+        for tarinfo in self.tar:
+            if not tarinfo.isreg():
+                continue
+            fobj = self.tar.extractfile(tarinfo)
+            while True:
+                try:
+                    buf = fobj.read(512)
+                except tarfile.StreamError:
+                    self.fail("simple read-through using TarFile.extractfile() failed")
+                if not buf:
+                    break
+            fobj.close()
+
     def test_fileobj_regular_file(self):
         tarinfo = self.tar.next() # get "regtype" (can't use getmember)
         fobj = self.tar.extractfile(tarinfo)
@@ -919,6 +935,10 @@
             finally:
                 tar.close()
 
+            # Verify that filter is a keyword-only argument
+            with self.assertRaises(TypeError):
+                tar.add(tempdir, "empty_dir", True, None, filter)
+
             tar = tarfile.open(tmpname, "r")
             try:
                 for tarinfo in tar:
@@ -1000,7 +1020,7 @@
             tar = tarfile.open(tmpname, "r")
             try:
                 for t in tar:
-                    self.assert_(t.name == "." or t.name.startswith("./"))
+                    self.assertTrue(t.name == "." or t.name.startswith("./"))
             finally:
                 tar.close()
         finally:
@@ -1269,7 +1289,7 @@
         self._test_unicode_filename("utf7")
 
     def test_utf8_filename(self):
-        self._test_unicode_filename("utf8")
+        self._test_unicode_filename("utf-8")
 
     def _test_unicode_filename(self, encoding):
         tar = tarfile.open(tmpname, "w", format=self.format, encoding=encoding, errors="strict")
@@ -1348,7 +1368,7 @@
     def test_bad_pax_header(self):
         # Test for issue #8633. GNU tar <= 1.23 creates raw binary fields
         # without a hdrcharset=BINARY header.
-        for encoding, name in (("utf8", "pax/bad-pax-\udce4\udcf6\udcfc"),
+        for encoding, name in (("utf-8", "pax/bad-pax-\udce4\udcf6\udcfc"),
                 ("iso8859-1", "pax/bad-pax-\xe4\xf6\xfc"),):
             with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
                 try:
@@ -1363,7 +1383,7 @@
 
     def test_binary_header(self):
         # Test a POSIX.1-2008 compatible header with a hdrcharset=BINARY field.
-        for encoding, name in (("utf8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
+        for encoding, name in (("utf-8", "pax/hdrcharset-\udce4\udcf6\udcfc"),
                 ("iso8859-1", "pax/hdrcharset-\xe4\xf6\xfc"),):
             with tarfile.open(tarname, encoding=encoding, errors="surrogateescape") as tar:
                 try:

Modified: python/branches/pep-3151/Lib/test/test_telnetlib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_telnetlib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_telnetlib.py	Sat Feb 26 08:16:32 2011
@@ -342,6 +342,16 @@
         expected = "send b'xxx'\n"
         self.assertIn(expected, telnet._messages)
 
+    def test_debug_accepts_str_port(self):
+        # Issue 10695
+        with test_socket([]):
+            telnet = TelnetAlike('dummy', '0')
+            telnet._messages = ''
+        telnet.set_debuglevel(1)
+        telnet.msg('test')
+        self.assertRegex(telnet._messages, r'0.*test')
+
+
 def test_main(verbose=None):
     support.run_unittest(GeneralTests, ReadTests, WriteTests, OptionTests)
 

Modified: python/branches/pep-3151/Lib/test/test_tempfile.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_tempfile.py	(original)
+++ python/branches/pep-3151/Lib/test/test_tempfile.py	Sat Feb 26 08:16:32 2011
@@ -319,7 +319,7 @@
         f.write(b"blat\x1a")
         f.write(b"extra\n")
         os.lseek(f.fd, 0, os.SEEK_SET)
-        self.assertEquals(os.read(f.fd, 20), b"blat")
+        self.assertEqual(os.read(f.fd, 20), b"blat")
 
 test_classes.append(test__mkstemp_inner)
 
@@ -879,7 +879,7 @@
             with tempfile.TemporaryFile(*args, **kwargs) as fileobj:
                 fileobj.write(input)
                 fileobj.seek(0)
-                self.assertEquals(input, fileobj.read())
+                self.assertEqual(input, fileobj.read())
 
         roundtrip(b"1234", "w+b")
         roundtrip("abdc\n", "w+")
@@ -925,6 +925,15 @@
             f.write(b"Hello world!")
         return tmp
 
+    def test_mkdtemp_failure(self):
+        # Check no additional exception if mkdtemp fails
+        # Previously would raise AttributeError instead
+        # (noted as part of Issue #10188)
+        with tempfile.TemporaryDirectory() as nonexistent:
+            pass
+        with self.assertRaises(os.error):
+            tempfile.TemporaryDirectory(dir=nonexistent)
+
     def test_explicit_cleanup(self):
         # A TemporaryDirectory is deleted when cleaned up
         dir = tempfile.mkdtemp()
@@ -955,20 +964,56 @@
     def test_del_on_shutdown(self):
         # A TemporaryDirectory may be cleaned up during shutdown
         # Make sure it works with the relevant modules nulled out
-        dir = tempfile.mkdtemp()
-        try:
+        with self.do_create() as dir:
             d = self.do_create(dir=dir)
             # Mimic the nulling out of modules that
             # occurs during system shutdown
             modules = [os, os.path]
             if has_stat:
                 modules.append(stat)
-            with NulledModules(*modules):
-                d.cleanup()
+            # Currently broken, so suppress the warning
+            # that is otherwise emitted on stdout
+            with support.captured_stderr() as err:
+                with NulledModules(*modules):
+                    d.cleanup()
+            # Currently broken, so stop spurious exception by
+            # indicating the object has already been closed
+            d._closed = True
+            # And this assert will fail, as expected by the
+            # unittest decorator...
             self.assertFalse(os.path.exists(d.name),
                         "TemporaryDirectory %s exists after cleanup" % d.name)
-        finally:
-            os.rmdir(dir)
+
+    def test_warnings_on_cleanup(self):
+        # Two kinds of warning on shutdown
+        #   Issue 10888: may write to stderr if modules are nulled out
+        #   ResourceWarning will be triggered by __del__
+        with self.do_create() as dir:
+            if os.sep != '\\':
+                # Embed a backslash in order to make sure string escaping
+                # in the displayed error message is dealt with correctly
+                suffix = '\\check_backslash_handling'
+            else:
+                suffix = ''
+            d = self.do_create(dir=dir, suf=suffix)
+
+            #Check for the Issue 10888 message
+            modules = [os, os.path]
+            if has_stat:
+                modules.append(stat)
+            with support.captured_stderr() as err:
+                with NulledModules(*modules):
+                    d.cleanup()
+            message = err.getvalue().replace('\\\\', '\\')
+            self.assertIn("while cleaning up",  message)
+            self.assertIn(d.name,  message)
+
+            # Check for the resource warning
+            with support.check_warnings(('Implicitly', ResourceWarning), quiet=False):
+                warnings.filterwarnings("always", category=ResourceWarning)
+                d.__del__()
+            self.assertFalse(os.path.exists(d.name),
+                        "TemporaryDirectory %s exists after __del__" % d.name)
 
     def test_multiple_close(self):
         # Can be cleaned-up many times without error

Modified: python/branches/pep-3151/Lib/test/test_textwrap.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_textwrap.py	(original)
+++ python/branches/pep-3151/Lib/test/test_textwrap.py	Sat Feb 26 08:16:32 2011
@@ -29,7 +29,7 @@
 
 
     def check(self, result, expect):
-        self.assertEquals(result, expect,
+        self.assertEqual(result, expect,
             'expected:\n%s\nbut got:\n%s' % (
                 self.show(expect), self.show(result)))
 
@@ -39,9 +39,9 @@
 
     def check_split(self, text, expect):
         result = self.wrapper._split(text)
-        self.assertEquals(result, expect,
-                          "\nexpected %r\n"
-                          "but got  %r" % (expect, result))
+        self.assertEqual(result, expect,
+                         "\nexpected %r\n"
+                         "but got  %r" % (expect, result))
 
 
 class WrapTestCase(BaseTestCase):
@@ -490,7 +490,7 @@
 
     def assertUnchanged(self, text):
         """assert that dedent() has no effect on 'text'"""
-        self.assertEquals(text, dedent(text))
+        self.assertEqual(text, dedent(text))
 
     def test_dedent_nomargin(self):
         # No lines indented.
@@ -513,17 +513,17 @@
         # All lines indented by two spaces.
         text = "  Hello there.\n  How are ya?\n  Oh good."
         expect = "Hello there.\nHow are ya?\nOh good."
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
         # Same, with blank lines.
         text = "  Hello there.\n\n  How are ya?\n  Oh good.\n"
         expect = "Hello there.\n\nHow are ya?\nOh good.\n"
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
         # Now indent one of the blank lines.
         text = "  Hello there.\n  \n  How are ya?\n  Oh good.\n"
         expect = "Hello there.\n\nHow are ya?\nOh good.\n"
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
     def test_dedent_uneven(self):
         # Lines indented unevenly.
@@ -537,27 +537,27 @@
     while 1:
         return foo
 '''
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
         # Uneven indentation with a blank line.
         text = "  Foo\n    Bar\n\n   Baz\n"
         expect = "Foo\n  Bar\n\n Baz\n"
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
         # Uneven indentation with a whitespace-only line.
         text = "  Foo\n    Bar\n \n   Baz\n"
         expect = "Foo\n  Bar\n\n Baz\n"
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
     # dedent() should not mangle internal tabs
     def test_dedent_preserve_internal_tabs(self):
         text = "  hello\tthere\n  how are\tyou?"
         expect = "hello\tthere\nhow are\tyou?"
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
         # make sure that it preserves tabs when it's not making any
         # changes at all
-        self.assertEquals(expect, dedent(expect))
+        self.assertEqual(expect, dedent(expect))
 
     # dedent() should not mangle tabs in the margin (i.e.
     # tabs and spaces both count as margin, but are *not*
@@ -573,17 +573,17 @@
         # dedent() only removes whitespace that can be uniformly removed!
         text = "\thello there\n\thow are you?"
         expect = "hello there\nhow are you?"
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
         text = "  \thello there\n  \thow are you?"
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
         text = "  \t  hello there\n  \t  how are you?"
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
         text = "  \thello there\n  \t  how are you?"
         expect = "hello there\n  how are you?"
-        self.assertEquals(expect, dedent(text))
+        self.assertEqual(expect, dedent(text))
 
 
 def test_main():

Modified: python/branches/pep-3151/Lib/test/test_threadedtempfile.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_threadedtempfile.py	(original)
+++ python/branches/pep-3151/Lib/test/test_threadedtempfile.py	Sat Feb 26 08:16:32 2011
@@ -68,8 +68,8 @@
 
         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)
+        self.assertEqual(errors, [], msg)
+        self.assertEqual(ok, NUM_THREADS * FILES_PER_THREAD)
 
 def test_main():
     run_unittest(ThreadedTempFileTest)

Modified: python/branches/pep-3151/Lib/test/test_threading.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_threading.py	(original)
+++ python/branches/pep-3151/Lib/test/test_threading.py	Sat Feb 26 08:16:32 2011
@@ -11,6 +11,7 @@
 import unittest
 import weakref
 import os
+import subprocess
 
 from test import lock_tests
 
@@ -272,7 +273,6 @@
         except ImportError:
             raise unittest.SkipTest("cannot import ctypes")
 
-        import subprocess
         rc = subprocess.call([sys.executable, "-c", """if 1:
             import ctypes, sys, time, _thread
 
@@ -303,7 +303,6 @@
     def test_finalize_with_trace(self):
         # Issue1733757
         # Avoid a deadlock when sys.settrace steps into threading._shutdown
-        import subprocess
         p = subprocess.Popen([sys.executable, "-c", """if 1:
             import sys, threading
 
@@ -338,7 +337,6 @@
     def test_join_nondaemon_on_shutdown(self):
         # Issue 1722344
         # Raising SystemExit skipped threading._shutdown
-        import subprocess
         p = subprocess.Popen([sys.executable, "-c", """if 1:
                 import threading
                 from time import sleep
@@ -398,17 +396,17 @@
         weak_cyclic_object = weakref.ref(cyclic_object)
         cyclic_object.thread.join()
         del cyclic_object
-        self.assertEquals(None, weak_cyclic_object(),
-                          msg=('%d references still around' %
-                               sys.getrefcount(weak_cyclic_object())))
+        self.assertIsNone(weak_cyclic_object(),
+                         msg=('%d references still around' %
+                              sys.getrefcount(weak_cyclic_object())))
 
         raising_cyclic_object = RunSelfFunction(should_raise=True)
         weak_raising_cyclic_object = weakref.ref(raising_cyclic_object)
         raising_cyclic_object.thread.join()
         del raising_cyclic_object
-        self.assertEquals(None, weak_raising_cyclic_object(),
-                          msg=('%d references still around' %
-                               sys.getrefcount(weak_raising_cyclic_object())))
+        self.assertIsNone(weak_raising_cyclic_object(),
+                         msg=('%d references still around' %
+                              sys.getrefcount(weak_raising_cyclic_object())))
 
     def test_old_threading_api(self):
         # Just a quick sanity check to make sure the old method names are
@@ -429,6 +427,14 @@
         t.daemon = True
         self.assertTrue('daemon' in repr(t))
 
+    def test_deamon_param(self):
+        t = threading.Thread()
+        self.assertFalse(t.daemon)
+        t = threading.Thread(daemon=False)
+        self.assertFalse(t.daemon)
+        t = threading.Thread(daemon=True)
+        self.assertTrue(t.daemon)
+
 
 class ThreadJoinOnShutdown(BaseTestCase):
 
@@ -445,7 +451,6 @@
                 sys.stdout.flush()
         \n""" + script
 
-        import subprocess
         p = subprocess.Popen([sys.executable, "-c", script], stdout=subprocess.PIPE)
         rc = p.wait()
         data = p.stdout.read().decode().replace('\r', '')
@@ -512,6 +517,152 @@
             """
         self._run_and_join(script)
 
+    def assertScriptHasOutput(self, script, expected_output):
+        p = subprocess.Popen([sys.executable, "-c", script],
+                             stdout=subprocess.PIPE)
+        stdout, stderr = p.communicate()
+        data = stdout.decode().replace('\r', '')
+        self.assertEqual(p.returncode, 0, "Unexpected error")
+        self.assertEqual(data, expected_output)
+
+    @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
+    def test_4_joining_across_fork_in_worker_thread(self):
+        # There used to be a possible deadlock when forking from a child
+        # thread.  See http://bugs.python.org/issue6643.
+
+        # Skip platforms with known problems forking from a worker thread.
+        # See http://bugs.python.org/issue3863.
+        if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
+            raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
+
+        # The script takes the following steps:
+        # - The main thread in the parent process starts a new thread and then
+        #   tries to join it.
+        # - The join operation acquires the Lock inside the thread's _block
+        #   Condition.  (See threading.py:Thread.join().)
+        # - We stub out the acquire method on the condition to force it to wait
+        #   until the child thread forks.  (See LOCK ACQUIRED HERE)
+        # - The child thread forks.  (See LOCK HELD and WORKER THREAD FORKS
+        #   HERE)
+        # - The main thread of the parent process enters Condition.wait(),
+        #   which releases the lock on the child thread.
+        # - The child process returns.  Without the necessary fix, when the
+        #   main thread of the child process (which used to be the child thread
+        #   in the parent process) attempts to exit, it will try to acquire the
+        #   lock in the Thread._block Condition object and hang, because the
+        #   lock was held across the fork.
+
+        script = """if 1:
+            import os, time, threading
+
+            finish_join = False
+            start_fork = False
+
+            def worker():
+                # Wait until this thread's lock is acquired before forking to
+                # create the deadlock.
+                global finish_join
+                while not start_fork:
+                    time.sleep(0.01)
+                # LOCK HELD: Main thread holds lock across this call.
+                childpid = os.fork()
+                finish_join = True
+                if childpid != 0:
+                    # Parent process just waits for child.
+                    os.waitpid(childpid, 0)
+                # Child process should just return.
+
+            w = threading.Thread(target=worker)
+
+            # Stub out the private condition variable's lock acquire method.
+            # This acquires the lock and then waits until the child has forked
+            # before returning, which will release the lock soon after.  If
+            # someone else tries to fix this test case by acquiring this lock
+            # before forking instead of reseting it, the test case will
+            # deadlock when it shouldn't.
+            condition = w._block
+            orig_acquire = condition.acquire
+            call_count_lock = threading.Lock()
+            call_count = 0
+            def my_acquire():
+                global call_count
+                global start_fork
+                orig_acquire()  # LOCK ACQUIRED HERE
+                start_fork = True
+                if call_count == 0:
+                    while not finish_join:
+                        time.sleep(0.01)  # WORKER THREAD FORKS HERE
+                with call_count_lock:
+                    call_count += 1
+            condition.acquire = my_acquire
+
+            w.start()
+            w.join()
+            print('end of main')
+            """
+        self.assertScriptHasOutput(script, "end of main\n")
+
+    @unittest.skipUnless(hasattr(os, 'fork'), "needs os.fork()")
+    def test_5_clear_waiter_locks_to_avoid_crash(self):
+        # Check that a spawned thread that forks doesn't segfault on certain
+        # platforms, namely OS X.  This used to happen if there was a waiter
+        # lock in the thread's condition variable's waiters list.  Even though
+        # we know the lock will be held across the fork, it is not safe to
+        # release locks held across forks on all platforms, so releasing the
+        # waiter lock caused a segfault on OS X.  Furthermore, since locks on
+        # OS X are (as of this writing) implemented with a mutex + condition
+        # variable instead of a semaphore, while we know that the Python-level
+        # lock will be acquired, we can't know if the internal mutex will be
+        # acquired at the time of the fork.
+
+        # Skip platforms with known problems forking from a worker thread.
+        # See http://bugs.python.org/issue3863.
+        if sys.platform in ('freebsd4', 'freebsd5', 'freebsd6', 'os2emx'):
+            raise unittest.SkipTest('due to known OS bugs on ' + sys.platform)
+        script = """if True:
+            import os, time, threading
+
+            start_fork = False
+
+            def worker():
+                # Wait until the main thread has attempted to join this thread
+                # before continuing.
+                while not start_fork:
+                    time.sleep(0.01)
+                childpid = os.fork()
+                if childpid != 0:
+                    # Parent process just waits for child.
+                    (cpid, rc) = os.waitpid(childpid, 0)
+                    assert cpid == childpid
+                    assert rc == 0
+                    print('end of worker thread')
+                else:
+                    # Child process should just return.
+                    pass
+
+            w = threading.Thread(target=worker)
+
+            # Stub out the private condition variable's _release_save method.
+            # This releases the condition's lock and flips the global that
+            # causes the worker to fork.  At this point, the problematic waiter
+            # lock has been acquired once by the waiter and has been put onto
+            # the waiters list.
+            condition = w._block
+            orig_release_save = condition._release_save
+            def my_release_save():
+                global start_fork
+                orig_release_save()
+                # Waiter lock held here, condition lock released.
+                start_fork = True
+            condition._release_save = my_release_save
+
+            w.start()
+            w.join()
+            print('end of main thread')
+            """
+        output = "end of worker thread\nend of main thread\n"
+        self.assertScriptHasOutput(script, output)
+
 
 class ThreadingExceptionTests(BaseTestCase):
     # A RuntimeError should be raised if Thread.start() is called

Modified: python/branches/pep-3151/Lib/test/test_threadsignals.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_threadsignals.py	(original)
+++ python/branches/pep-3151/Lib/test/test_threadsignals.py	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,7 @@
 import sys
 from test.support import run_unittest, import_module
 thread = import_module('_thread')
+import time
 
 if sys.platform[:3] in ('win', 'os2') or sys.platform=='riscos':
     raise unittest.SkipTest("Can't test signal on %s" % sys.platform)
@@ -34,12 +35,12 @@
     signalled_all.release()
 
 class ThreadSignals(unittest.TestCase):
-    """Test signal handling semantics of threads.
-       We spawn a thread, have the thread send two signals, and
-       wait for it to finish. Check that we got both signals
-       and that they were run by the main thread.
-    """
+
     def test_signals(self):
+        # Test signal handling semantics of threads.
+        # We spawn a thread, have the thread send two signals, and
+        # wait for it to finish. Check that we got both signals
+        # and that they were run by the main thread.
         signalled_all.acquire()
         self.spawnSignallingThread()
         signalled_all.acquire()
@@ -66,6 +67,121 @@
     def spawnSignallingThread(self):
         thread.start_new_thread(send_signals, ())
 
+    def alarm_interrupt(self, sig, frame):
+        raise KeyboardInterrupt
+
+    def test_lock_acquire_interruption(self):
+        # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
+        # in a deadlock.
+        oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
+        try:
+            lock = thread.allocate_lock()
+            lock.acquire()
+            signal.alarm(1)
+            self.assertRaises(KeyboardInterrupt, lock.acquire)
+        finally:
+            signal.signal(signal.SIGALRM, oldalrm)
+
+    def test_rlock_acquire_interruption(self):
+        # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck
+        # in a deadlock.
+        oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt)
+        try:
+            rlock = thread.RLock()
+            # For reentrant locks, the initial acquisition must be in another
+            # thread.
+            def other_thread():
+                rlock.acquire()
+            thread.start_new_thread(other_thread, ())
+            # Wait until we can't acquire it without blocking...
+            while rlock.acquire(blocking=False):
+                rlock.release()
+                time.sleep(0.01)
+            signal.alarm(1)
+            self.assertRaises(KeyboardInterrupt, rlock.acquire)
+        finally:
+            signal.signal(signal.SIGALRM, oldalrm)
+
+    def acquire_retries_on_intr(self, lock):
+        self.sig_recvd = False
+        def my_handler(signal, frame):
+            self.sig_recvd = True
+        old_handler = signal.signal(signal.SIGUSR1, my_handler)
+        try:
+            def other_thread():
+                # Acquire the lock in a non-main thread, so this test works for
+                # RLocks.
+                lock.acquire()
+                # Wait until the main thread is blocked in the lock acquire, and
+                # then wake it up with this.
+                time.sleep(0.5)
+                os.kill(process_pid, signal.SIGUSR1)
+                # Let the main thread take the interrupt, handle it, and retry
+                # the lock acquisition.  Then we'll let it run.
+                time.sleep(0.5)
+                lock.release()
+            thread.start_new_thread(other_thread, ())
+            # Wait until we can't acquire it without blocking...
+            while lock.acquire(blocking=False):
+                lock.release()
+                time.sleep(0.01)
+            result = lock.acquire()  # Block while we receive a signal.
+            self.assertTrue(self.sig_recvd)
+            self.assertTrue(result)
+        finally:
+            signal.signal(signal.SIGUSR1, old_handler)
+
+    def test_lock_acquire_retries_on_intr(self):
+        self.acquire_retries_on_intr(thread.allocate_lock())
+
+    def test_rlock_acquire_retries_on_intr(self):
+        self.acquire_retries_on_intr(thread.RLock())
+
+    def test_interrupted_timed_acquire(self):
+        # Test to make sure we recompute lock acquisition timeouts when we
+        # receive a signal.  Check this by repeatedly interrupting a lock
+        # acquire in the main thread, and make sure that the lock acquire times
+        # out after the right amount of time.
+        # NOTE: this test only behaves as expected if C signals get delivered
+        # to the main thread.  Otherwise lock.acquire() itself doesn't get
+        # interrupted and the test trivially succeeds.
+        self.start = None
+        self.end = None
+        self.sigs_recvd = 0
+        done = thread.allocate_lock()
+        done.acquire()
+        lock = thread.allocate_lock()
+        lock.acquire()
+        def my_handler(signum, frame):
+            self.sigs_recvd += 1
+        old_handler = signal.signal(signal.SIGUSR1, my_handler)
+        try:
+            def timed_acquire():
+                self.start = time.time()
+                lock.acquire(timeout=0.5)
+                self.end = time.time()
+            def send_signals():
+                for _ in range(40):
+                    time.sleep(0.02)
+                    os.kill(process_pid, signal.SIGUSR1)
+                done.release()
+
+            # Send the signals from the non-main thread, since the main thread
+            # is the only one that can process signals.
+            thread.start_new_thread(send_signals, ())
+            timed_acquire()
+            # Wait for thread to finish
+            done.acquire()
+            # This allows for some timing and scheduling imprecision
+            self.assertLess(self.end - self.start, 2.0)
+            self.assertGreater(self.end - self.start, 0.3)
+            # If the signal is received several times before PyErr_CheckSignals()
+            # is called, the handler will get called less than 40 times. Just
+            # check it's been called at least once.
+            self.assertGreater(self.sigs_recvd, 0)
+        finally:
+            signal.signal(signal.SIGUSR1, old_handler)
+
 
 def test_main():
     global signal_blackboard

Modified: python/branches/pep-3151/Lib/test/test_time.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_time.py	(original)
+++ python/branches/pep-3151/Lib/test/test_time.py	Sat Feb 26 08:16:32 2011
@@ -2,6 +2,8 @@
 import time
 import unittest
 import locale
+import sysconfig
+import warnings
 
 class TimeTestCase(unittest.TestCase):
 
@@ -18,10 +20,10 @@
         time.clock()
 
     def test_conversions(self):
-        self.assertTrue(time.ctime(self.t)
-                     == time.asctime(time.localtime(self.t)))
-        self.assertTrue(int(time.mktime(time.localtime(self.t)))
-                     == int(self.t))
+        self.assertEqual(time.ctime(self.t),
+                         time.asctime(time.localtime(self.t)))
+        self.assertEqual(int(time.mktime(time.localtime(self.t))),
+                         int(self.t))
 
     def test_sleep(self):
         time.sleep(1.2)
@@ -41,14 +43,8 @@
         # Make sure that strftime() checks the bounds of the various parts
         #of the time tuple (0 is valid for *all* values).
 
-        # Check year [1900, max(int)]
-        self.assertRaises(ValueError, func,
-                            (1899, 1, 1, 0, 0, 0, 0, 1, -1))
-        if time.accept2dyear:
-            self.assertRaises(ValueError, func,
-                                (-1, 1, 1, 0, 0, 0, 0, 1, -1))
-            self.assertRaises(ValueError, func,
-                                (100, 1, 1, 0, 0, 0, 0, 1, -1))
+        # The year field is tested by other test cases above
+
         # Check month [1, 12] + zero support
         self.assertRaises(ValueError, func,
                             (1900, -1, 1, 0, 0, 0, 0, 1, -1))
@@ -96,8 +92,9 @@
         # No test for daylight savings since strftime() does not change output
         # based on its value.
         expected = "2000 01 01 00 00 00 1 001"
-        result = time.strftime("%Y %m %d %H %M %S %w %j", (0,)*9)
-        self.assertEquals(expected, result)
+        with support.check_warnings():
+            result = time.strftime("%Y %m %d %H %M %S %w %j", (0,)*9)
+        self.assertEqual(expected, result)
 
     def test_strptime(self):
         # Should be able to go round-trip from strftime to strptime without
@@ -121,14 +118,38 @@
 
     def test_asctime(self):
         time.asctime(time.gmtime(self.t))
+
+        # Max year is only limited by the size of C int.
+        sizeof_int = sysconfig.get_config_var('SIZEOF_INT') or 4
+        bigyear = (1 << 8 * sizeof_int - 1) - 1
+        asc = time.asctime((bigyear, 6, 1) + (0,)*6)
+        self.assertEqual(asc[-len(str(bigyear)):], str(bigyear))
+        self.assertRaises(OverflowError, time.asctime, (bigyear + 1,) + (0,)*8)
         self.assertRaises(TypeError, time.asctime, 0)
+        self.assertRaises(TypeError, time.asctime, ())
+        self.assertRaises(TypeError, time.asctime, (0,) * 10)
 
     def test_asctime_bounding_check(self):
         self._bounds_checking(time.asctime)
 
+    def test_ctime(self):
+        t = time.mktime((1973, 9, 16, 1, 3, 52, 0, 0, -1))
+        self.assertEqual(time.ctime(t), 'Sun Sep 16 01:03:52 1973')
+        t = time.mktime((2000, 1, 1, 0, 0, 0, 0, 0, -1))
+        self.assertEqual(time.ctime(t), 'Sat Jan  1 00:00:00 2000')
+        for year in [-100, 100, 1000, 2000, 10000]:
+            try:
+                testval = time.mktime((year, 1, 10) + (0,)*6)
+            except (ValueError, OverflowError):
+                # If mktime fails, ctime will fail too.  This may happen
+                # on some platforms.
+                pass
+            else:
+                self.assertEqual(time.ctime(testval)[20:], str(year))
+
+    @unittest.skipIf(not hasattr(time, "tzset"),
+        "time module has no attribute tzset")
     def test_tzset(self):
-        if not hasattr(time, "tzset"):
-            return # Can't test this; don't want the test suite to fail
 
         from os import environ
 
@@ -215,14 +236,14 @@
         gt1 = time.gmtime(None)
         t0 = time.mktime(gt0)
         t1 = time.mktime(gt1)
-        self.assertTrue(0 <= (t1-t0) < 0.2)
+        self.assertAlmostEqual(t1, t0, delta=0.2)
 
     def test_localtime_without_arg(self):
         lt0 = time.localtime()
         lt1 = time.localtime(None)
         t0 = time.mktime(lt0)
         t1 = time.mktime(lt1)
-        self.assertTrue(0 <= (t1-t0) < 0.2)
+        self.assertAlmostEqual(t1, t0, delta=0.2)
 
 class TestLocale(unittest.TestCase):
     def setUp(self):
@@ -240,8 +261,142 @@
         # This should not cause an exception
         time.strftime("%B", (2009,2,1,0,0,0,0,0,0))
 
+
+class _BaseYearTest(unittest.TestCase):
+    accept2dyear = None
+
+    def setUp(self):
+        self.saved_accept2dyear = time.accept2dyear
+        time.accept2dyear = self.accept2dyear
+
+    def tearDown(self):
+        time.accept2dyear = self.saved_accept2dyear
+
+    def yearstr(self, y):
+        raise NotImplementedError()
+
+class _TestAsctimeYear:
+    def yearstr(self, y):
+        return time.asctime((y,) + (0,) * 8).split()[-1]
+
+    def test_large_year(self):
+        # Check that it doesn't crash for year > 9999
+        self.assertEqual(self.yearstr(12345), '12345')
+        self.assertEqual(self.yearstr(123456789), '123456789')
+
+class _TestStrftimeYear:
+    def yearstr(self, y):
+        return time.strftime('%Y', (y,) + (0,) * 8).split()[-1]
+
+    def test_large_year(self):
+        # Check that it doesn't crash for year > 9999
+        try:
+            text = self.yearstr(12345)
+        except ValueError:
+            # strftime() is limited to [1; 9999] with Visual Studio
+            return
+        # Issue #10864: OpenIndiana is limited to 4 digits,
+        # but Python doesn't raise a ValueError
+        #self.assertEqual(text, '12345')
+        #self.assertEqual(self.yearstr(123456789), '123456789')
+        self.assertIn(text, ('2345', '12345'))
+        self.assertIn(self.yearstr(123456789), ('123456789', '6789'))
+
+class _Test2dYear(_BaseYearTest):
+    accept2dyear = 1
+
+    def test_year(self):
+        with support.check_warnings():
+            self.assertEqual(self.yearstr(0), '2000')
+            self.assertEqual(self.yearstr(69), '1969')
+            self.assertEqual(self.yearstr(68), '2068')
+            self.assertEqual(self.yearstr(99), '1999')
+
+    def test_invalid(self):
+        self.assertRaises(ValueError, self.yearstr, -1)
+        self.assertRaises(ValueError, self.yearstr, 100)
+        self.assertRaises(ValueError, self.yearstr, 999)
+
+class _Test4dYear(_BaseYearTest):
+    accept2dyear = 0
+
+    def test_year(self):
+        self.assertIn(self.yearstr(1),     ('1', '0001'))
+        self.assertIn(self.yearstr(68),   ('68', '0068'))
+        self.assertIn(self.yearstr(69),   ('69', '0069'))
+        self.assertIn(self.yearstr(99),   ('99', '0099'))
+        self.assertIn(self.yearstr(999), ('999', '0999'))
+        self.assertEqual(self.yearstr(9999), '9999')
+
+    def test_negative(self):
+        try:
+            text = self.yearstr(-1)
+        except ValueError:
+            # strftime() is limited to [1; 9999] with Visual Studio
+            return
+        self.assertIn(text, ('-1', '-001'))
+
+        self.assertEqual(self.yearstr(-1234), '-1234')
+        self.assertEqual(self.yearstr(-123456), '-123456')
+
+
+    def test_mktime(self):
+        # Issue #1726687
+        for t in (-2, -1, 0, 1):
+            try:
+                tt = time.localtime(t)
+            except (OverflowError, ValueError):
+                pass
+            else:
+                self.assertEqual(time.mktime(tt), t)
+        # It may not be possible to reliably make mktime return error
+        # on all platfom.  This will make sure that no other exception
+        # than OverflowError is raised for an extreme value.
+        try:
+            time.mktime((-1, 1, 1, 0, 0, 0, -1, -1, -1))
+        except OverflowError:
+            pass
+
+class TestAsctimeAccept2dYear(_TestAsctimeYear, _Test2dYear):
+    pass
+
+class TestStrftimeAccept2dYear(_TestStrftimeYear, _Test2dYear):
+    pass
+
+class TestAsctime4dyear(_TestAsctimeYear, _Test4dYear):
+    pass
+
+class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear):
+    pass
+
+class Test2dyearBool(_TestAsctimeYear, _Test2dYear):
+    accept2dyear = True
+
+class Test4dyearBool(_TestAsctimeYear, _Test4dYear):
+    accept2dyear = False
+
+class TestAccept2YearBad(_TestAsctimeYear, _BaseYearTest):
+    class X:
+        def __bool__(self):
+            raise RuntimeError('boo')
+    accept2dyear = X()
+    def test_2dyear(self):
+        pass
+    def test_invalid(self):
+        self.assertRaises(RuntimeError, self.yearstr, 200)
+
+
 def test_main():
-    support.run_unittest(TimeTestCase, TestLocale)
+    support.run_unittest(
+        TimeTestCase,
+        TestLocale,
+        TestAsctimeAccept2dYear,
+        TestStrftimeAccept2dYear,
+        TestAsctime4dyear,
+        TestStrftime4dyear,
+        Test2dyearBool,
+        Test4dyearBool,
+        TestAccept2YearBad)
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/pep-3151/Lib/test/test_timeout.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_timeout.py	(original)
+++ python/branches/pep-3151/Lib/test/test_timeout.py	Sat Feb 26 08:16:32 2011
@@ -7,6 +7,7 @@
 skip_expected = not support.is_resource_enabled('network')
 
 import time
+import errno
 import socket
 
 
@@ -88,8 +89,6 @@
 
 
 class TimeoutTestCase(unittest.TestCase):
-    """Test case for socket.socket() timeout functions"""
-
     # There are a number of tests here trying to make sure that an operation
     # doesn't take too much longer than expected.  But competing machine
     # activity makes it inevitable that such tests will fail at times.
@@ -98,10 +97,42 @@
     # solution.
     fuzz = 2.0
 
+    localhost = '127.0.0.1'
+
+    def setUp(self):
+        raise NotImplementedError()
+
+    tearDown = setUp
+
+    def _sock_operation(self, count, timeout, method, *args):
+        """
+        Test the specified socket method.
+
+        The method is run at most `count` times and must raise a socket.timeout
+        within `timeout` + self.fuzz seconds.
+        """
+        self.sock.settimeout(timeout)
+        method = getattr(self.sock, method)
+        for i in range(count):
+            t1 = time.time()
+            try:
+                method(*args)
+            except socket.timeout as e:
+                delta = time.time() - t1
+                break
+        else:
+            self.fail('socket.timeout was not raised')
+        # These checks should account for timing unprecision
+        self.assertLess(delta, timeout + self.fuzz)
+        self.assertGreater(delta, timeout - 1.0)
+
+
+class TCPTimeoutTestCase(TimeoutTestCase):
+    """TCP test case for socket.socket() timeout functions"""
+
     def setUp(self):
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         self.addr_remote = ('www.python.org.', 80)
-        self.localhost = '127.0.0.1'
 
     def tearDown(self):
         self.sock.close()
@@ -113,90 +144,73 @@
         # with the connect time.  This avoids failing the assertion that
         # the timeout occurred fast enough.
         addr = ('10.0.0.0', 12345)
-
-        # Test connect() timeout
-        _timeout = 0.001
-        self.sock.settimeout(_timeout)
-
-        _t1 = time.time()
-        self.assertRaises(socket.error, self.sock.connect, addr)
-        _t2 = time.time()
-
-        _delta = abs(_t1 - _t2)
-        self.assertTrue(_delta < _timeout + self.fuzz,
-                     "timeout (%g) is more than %g seconds more than expected (%g)"
-                     %(_delta, self.fuzz, _timeout))
+        with support.transient_internet(addr[0]):
+            self._sock_operation(1, 0.001, 'connect', addr)
 
     def testRecvTimeout(self):
         # Test recv() timeout
-        _timeout = 0.02
-
         with support.transient_internet(self.addr_remote[0]):
             self.sock.connect(self.addr_remote)
-            self.sock.settimeout(_timeout)
-
-            _t1 = time.time()
-            self.assertRaises(socket.timeout, self.sock.recv, 1024)
-            _t2 = time.time()
-
-            _delta = abs(_t1 - _t2)
-            self.assertTrue(_delta < _timeout + self.fuzz,
-                         "timeout (%g) is %g seconds more than expected (%g)"
-                         %(_delta, self.fuzz, _timeout))
+            self._sock_operation(1, 1.5, 'recv', 1024)
 
     def testAcceptTimeout(self):
         # Test accept() timeout
-        _timeout = 2
-        self.sock.settimeout(_timeout)
-        # Prevent "Address already in use" socket exceptions
         support.bind_port(self.sock, self.localhost)
         self.sock.listen(5)
-
-        _t1 = time.time()
-        self.assertRaises(socket.error, self.sock.accept)
-        _t2 = time.time()
-
-        _delta = abs(_t1 - _t2)
-        self.assertTrue(_delta < _timeout + self.fuzz,
-                     "timeout (%g) is %g seconds more than expected (%g)"
-                     %(_delta, self.fuzz, _timeout))
-
-    def testRecvfromTimeout(self):
-        # Test recvfrom() timeout
-        _timeout = 2
-        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-        self.sock.settimeout(_timeout)
-        # Prevent "Address already in use" socket exceptions
-        support.bind_port(self.sock, self.localhost)
-
-        _t1 = time.time()
-        self.assertRaises(socket.error, self.sock.recvfrom, 8192)
-        _t2 = time.time()
-
-        _delta = abs(_t1 - _t2)
-        self.assertTrue(_delta < _timeout + self.fuzz,
-                     "timeout (%g) is %g seconds more than expected (%g)"
-                     %(_delta, self.fuzz, _timeout))
+        self._sock_operation(1, 1.5, 'accept')
 
     def testSend(self):
         # Test send() timeout
-        # couldn't figure out how to test it
-        pass
+        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
+            support.bind_port(serv, self.localhost)
+            serv.listen(5)
+            self.sock.connect(serv.getsockname())
+            # Send a lot of data in order to bypass buffering in the TCP stack.
+            self._sock_operation(100, 1.5, 'send', b"X" * 200000)
 
     def testSendto(self):
         # Test sendto() timeout
-        # couldn't figure out how to test it
-        pass
+        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
+            support.bind_port(serv, self.localhost)
+            serv.listen(5)
+            self.sock.connect(serv.getsockname())
+            # The address argument is ignored since we already connected.
+            self._sock_operation(100, 1.5, 'sendto', b"X" * 200000,
+                                 serv.getsockname())
 
     def testSendall(self):
         # Test sendall() timeout
-        # couldn't figure out how to test it
-        pass
+        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as serv:
+            support.bind_port(serv, self.localhost)
+            serv.listen(5)
+            self.sock.connect(serv.getsockname())
+            # Send a lot of data in order to bypass buffering in the TCP stack.
+            self._sock_operation(100, 1.5, 'sendall', b"X" * 200000)
+
+
+class UDPTimeoutTestCase(TimeoutTestCase):
+    """UDP test case for socket.socket() timeout functions"""
+
+    def setUp(self):
+        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+
+    def tearDown(self):
+        self.sock.close()
+
+    def testRecvfromTimeout(self):
+        # Test recvfrom() timeout
+        # Prevent "Address already in use" socket exceptions
+        support.bind_port(self.sock, self.localhost)
+        self._sock_operation(1, 1.5, 'recvfrom', 1024)
 
 
 def test_main():
     support.requires('network')
-    support.run_unittest(CreationTestCase, TimeoutTestCase)
+    support.run_unittest(
+        CreationTestCase,
+        TCPTimeoutTestCase,
+        UDPTimeoutTestCase,
+    )
 
 if __name__ == "__main__":
     test_main()

Modified: python/branches/pep-3151/Lib/test/test_tokenize.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_tokenize.py	(original)
+++ python/branches/pep-3151/Lib/test/test_tokenize.py	Sat Feb 26 08:16:32 2011
@@ -689,8 +689,8 @@
         # skip the initial encoding token and the end token
         tokens = list(_tokenize(readline, encoding='utf-8'))[1:-1]
         expected_tokens = [(3, '"ЉЊЈЁЂ"', (1, 0), (1, 7), '"ЉЊЈЁЂ"')]
-        self.assertEquals(tokens, expected_tokens,
-                          "bytes not decoded with encoding")
+        self.assertEqual(tokens, expected_tokens,
+                         "bytes not decoded with encoding")
 
     def test__tokenize_does_not_decode_with_encoding_none(self):
         literal = '"ЉЊЈЁЂ"'
@@ -706,8 +706,8 @@
         # skip the end token
         tokens = list(_tokenize(readline, encoding=None))[:-1]
         expected_tokens = [(3, '"ЉЊЈЁЂ"', (1, 0), (1, 7), '"ЉЊЈЁЂ"')]
-        self.assertEquals(tokens, expected_tokens,
-                          "string not tokenized when encoding is None")
+        self.assertEqual(tokens, expected_tokens,
+                         "string not tokenized when encoding is None")
 
 
 class TestDetectEncoding(TestCase):
@@ -730,8 +730,8 @@
             b'do_something(else)\n'
         )
         encoding, consumed_lines = detect_encoding(self.get_readline(lines))
-        self.assertEquals(encoding, 'utf-8')
-        self.assertEquals(consumed_lines, list(lines[:2]))
+        self.assertEqual(encoding, 'utf-8')
+        self.assertEqual(consumed_lines, list(lines[:2]))
 
     def test_bom_no_cookie(self):
         lines = (
@@ -740,9 +740,9 @@
             b'do_something(else)\n'
         )
         encoding, consumed_lines = detect_encoding(self.get_readline(lines))
-        self.assertEquals(encoding, 'utf-8-sig')
-        self.assertEquals(consumed_lines,
-                          [b'# something\n', b'print(something)\n'])
+        self.assertEqual(encoding, 'utf-8-sig')
+        self.assertEqual(consumed_lines,
+                         [b'# something\n', b'print(something)\n'])
 
     def test_cookie_first_line_no_bom(self):
         lines = (
@@ -751,8 +751,8 @@
             b'do_something(else)\n'
         )
         encoding, consumed_lines = detect_encoding(self.get_readline(lines))
-        self.assertEquals(encoding, 'iso-8859-1')
-        self.assertEquals(consumed_lines, [b'# -*- coding: latin-1 -*-\n'])
+        self.assertEqual(encoding, 'iso-8859-1')
+        self.assertEqual(consumed_lines, [b'# -*- coding: latin-1 -*-\n'])
 
     def test_matched_bom_and_cookie_first_line(self):
         lines = (
@@ -761,8 +761,8 @@
             b'do_something(else)\n'
         )
         encoding, consumed_lines = detect_encoding(self.get_readline(lines))
-        self.assertEquals(encoding, 'utf-8-sig')
-        self.assertEquals(consumed_lines, [b'# coding=utf-8\n'])
+        self.assertEqual(encoding, 'utf-8-sig')
+        self.assertEqual(consumed_lines, [b'# coding=utf-8\n'])
 
     def test_mismatched_bom_and_cookie_first_line_raises_syntaxerror(self):
         lines = (
@@ -781,9 +781,9 @@
             b'do_something(else)\n'
         )
         encoding, consumed_lines = detect_encoding(self.get_readline(lines))
-        self.assertEquals(encoding, 'ascii')
+        self.assertEqual(encoding, 'ascii')
         expected = [b'#! something\n', b'# vim: set fileencoding=ascii :\n']
-        self.assertEquals(consumed_lines, expected)
+        self.assertEqual(consumed_lines, expected)
 
     def test_matched_bom_and_cookie_second_line(self):
         lines = (
@@ -793,9 +793,9 @@
             b'do_something(else)\n'
         )
         encoding, consumed_lines = detect_encoding(self.get_readline(lines))
-        self.assertEquals(encoding, 'utf-8-sig')
-        self.assertEquals(consumed_lines,
-                          [b'#! something\n', b'f# coding=utf-8\n'])
+        self.assertEqual(encoding, 'utf-8-sig')
+        self.assertEqual(consumed_lines,
+                         [b'#! something\n', b'f# coding=utf-8\n'])
 
     def test_mismatched_bom_and_cookie_second_line_raises_syntaxerror(self):
         lines = (
@@ -820,7 +820,7 @@
                          b"do_something += 4\n")
                 rl = self.get_readline(lines)
                 found, consumed_lines = detect_encoding(rl)
-                self.assertEquals(found, "iso-8859-1")
+                self.assertEqual(found, "iso-8859-1")
 
     def test_utf8_normalization(self):
         # See get_normal_name() in tokenizer.c.
@@ -833,27 +833,27 @@
                          b"1 + 3\n")
                 rl = self.get_readline(lines)
                 found, consumed_lines = detect_encoding(rl)
-                self.assertEquals(found, "utf-8")
+                self.assertEqual(found, "utf-8")
 
     def test_short_files(self):
         readline = self.get_readline((b'print(something)\n',))
         encoding, consumed_lines = detect_encoding(readline)
-        self.assertEquals(encoding, 'utf-8')
-        self.assertEquals(consumed_lines, [b'print(something)\n'])
+        self.assertEqual(encoding, 'utf-8')
+        self.assertEqual(consumed_lines, [b'print(something)\n'])
 
         encoding, consumed_lines = detect_encoding(self.get_readline(()))
-        self.assertEquals(encoding, 'utf-8')
-        self.assertEquals(consumed_lines, [])
+        self.assertEqual(encoding, 'utf-8')
+        self.assertEqual(consumed_lines, [])
 
         readline = self.get_readline((b'\xef\xbb\xbfprint(something)\n',))
         encoding, consumed_lines = detect_encoding(readline)
-        self.assertEquals(encoding, 'utf-8-sig')
-        self.assertEquals(consumed_lines, [b'print(something)\n'])
+        self.assertEqual(encoding, 'utf-8-sig')
+        self.assertEqual(consumed_lines, [b'print(something)\n'])
 
         readline = self.get_readline((b'\xef\xbb\xbf',))
         encoding, consumed_lines = detect_encoding(readline)
-        self.assertEquals(encoding, 'utf-8-sig')
-        self.assertEquals(consumed_lines, [])
+        self.assertEqual(encoding, 'utf-8-sig')
+        self.assertEqual(consumed_lines, [])
 
         readline = self.get_readline((b'# coding: bad\n',))
         self.assertRaises(SyntaxError, detect_encoding, readline)
@@ -912,7 +912,7 @@
         tokenize_module._tokenize = mock__tokenize
         try:
             results = tokenize(mock_readline)
-            self.assertEquals(list(results), ['first', 'second', 1, 2, 3, 4])
+            self.assertEqual(list(results), ['first', 'second', 1, 2, 3, 4])
         finally:
             tokenize_module.detect_encoding = orig_detect_encoding
             tokenize_module._tokenize = orig__tokenize

Modified: python/branches/pep-3151/Lib/test/test_trace.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_trace.py	(original)
+++ python/branches/pep-3151/Lib/test/test_trace.py	Sat Feb 26 08:16:32 2011
@@ -102,6 +102,7 @@
 class TestLineCounts(unittest.TestCase):
     """White-box testing of line-counting, via runfunc"""
     def setUp(self):
+        self.addCleanup(sys.settrace, sys.gettrace())
         self.tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0)
         self.my_py_filename = fix_ext_py(__file__)
 
@@ -192,6 +193,7 @@
     """A simple sanity test of line-counting, via runctx (exec)"""
     def setUp(self):
         self.my_py_filename = fix_ext_py(__file__)
+        self.addCleanup(sys.settrace, sys.gettrace())
 
     def test_exec_counts(self):
         self.tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0)
@@ -218,6 +220,7 @@
 class TestFuncs(unittest.TestCase):
     """White-box testing of funcs tracing"""
     def setUp(self):
+        self.addCleanup(sys.settrace, sys.gettrace())
         self.tracer = Trace(count=0, trace=0, countfuncs=1)
         self.filemod = my_file_and_modname()
 
@@ -242,6 +245,8 @@
         }
         self.assertEqual(self.tracer.results().calledfuncs, expected)
 
+    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
+                     'pre-existing trace function throws off measurements')
     def test_inst_method_calling(self):
         obj = TracedClass(20)
         self.tracer.runfunc(obj.inst_method_calling, 1)
@@ -257,9 +262,12 @@
 class TestCallers(unittest.TestCase):
     """White-box testing of callers tracing"""
     def setUp(self):
+        self.addCleanup(sys.settrace, sys.gettrace())
         self.tracer = Trace(count=0, trace=0, countcallers=1)
         self.filemod = my_file_and_modname()
 
+    @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(),
+                     'pre-existing trace function throws off measurements')
     def test_loop_caller_importing(self):
         self.tracer.runfunc(traced_func_importing_caller, 1)
 
@@ -280,6 +288,9 @@
 
 # Created separately for issue #3821
 class TestCoverage(unittest.TestCase):
+    def setUp(self):
+        self.addCleanup(sys.settrace, sys.gettrace())
+
     def tearDown(self):
         rmtree(TESTFN)
         unlink(TESTFN)
@@ -311,7 +322,7 @@
             self._coverage(tracer)
         if os.path.exists(TESTFN):
             files = os.listdir(TESTFN)
-            self.assertEquals(files, [])
+            self.assertEqual(files, [])
 
     def test_issue9936(self):
         tracer = trace.Trace(trace=0, count=1)
@@ -330,7 +341,7 @@
             lines, cov, module = line.split()[:3]
             coverage[module] = (int(lines), int(cov[:-1]))
         # XXX This is needed to run regrtest.py as a script
-        modname = trace.fullmodname(sys.modules[modname].__file__)
+        modname = trace._fullmodname(sys.modules[modname].__file__)
         self.assertIn(modname, coverage)
         self.assertEqual(coverage[modname], (5, 100))
 
@@ -340,7 +351,7 @@
 class Test_Ignore(unittest.TestCase):
     def test_ignored(self):
         jn = os.path.join
-        ignore = trace.Ignore(['x', 'y.z'], [jn('foo', 'bar')])
+        ignore = trace._Ignore(['x', 'y.z'], [jn('foo', 'bar')])
         self.assertTrue(ignore.names('x.py', 'x'))
         self.assertFalse(ignore.names('xy.py', 'xy'))
         self.assertFalse(ignore.names('y.py', 'y'))

Modified: python/branches/pep-3151/Lib/test/test_traceback.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_traceback.py	(original)
+++ python/branches/pep-3151/Lib/test/test_traceback.py	Sat Feb 26 08:16:32 2011
@@ -164,11 +164,11 @@
             raise Error("unable to create test traceback string")
 
         # Make sure that Python and the traceback module format the same thing
-        self.assertEquals(traceback_fmt, python_fmt)
+        self.assertEqual(traceback_fmt, python_fmt)
 
         # Make sure that the traceback is properly indented.
         tb_lines = python_fmt.splitlines()
-        self.assertEquals(len(tb_lines), 3)
+        self.assertEqual(len(tb_lines), 3)
         banner, location, source_line = tb_lines
         self.assertTrue(banner.startswith('Traceback'))
         self.assertTrue(location.startswith('  File'))
@@ -212,7 +212,7 @@
         except ZeroDivisionError as _:
             e = _
         lines = self.get_report(e).splitlines()
-        self.assertEquals(len(lines), 4)
+        self.assertEqual(len(lines), 4)
         self.assertTrue(lines[0].startswith('Traceback'))
         self.assertTrue(lines[1].startswith('  File'))
         self.assertIn('1/0 # Marker', lines[2])
@@ -227,8 +227,8 @@
         def outer_raise():
             inner_raise() # Marker
         blocks = boundaries.split(self.get_report(outer_raise))
-        self.assertEquals(len(blocks), 3)
-        self.assertEquals(blocks[1], cause_message)
+        self.assertEqual(len(blocks), 3)
+        self.assertEqual(blocks[1], cause_message)
         self.check_zero_div(blocks[0])
         self.assertIn('inner_raise() # Marker', blocks[2])
 
@@ -241,8 +241,8 @@
         def outer_raise():
             inner_raise() # Marker
         blocks = boundaries.split(self.get_report(outer_raise))
-        self.assertEquals(len(blocks), 3)
-        self.assertEquals(blocks[1], context_message)
+        self.assertEqual(len(blocks), 3)
+        self.assertEqual(blocks[1], context_message)
         self.check_zero_div(blocks[0])
         self.assertIn('inner_raise() # Marker', blocks[2])
 
@@ -261,8 +261,8 @@
         def outer_raise():
             inner_raise() # Marker
         blocks = boundaries.split(self.get_report(outer_raise))
-        self.assertEquals(len(blocks), 3)
-        self.assertEquals(blocks[1], cause_message)
+        self.assertEqual(len(blocks), 3)
+        self.assertEqual(blocks[1], cause_message)
         self.check_zero_div(blocks[0])
         self.assertIn('inner_raise() # Marker', blocks[2])
 
@@ -279,8 +279,8 @@
         def outer_raise():
             inner_raise() # Marker
         blocks = boundaries.split(self.get_report(outer_raise))
-        self.assertEquals(len(blocks), 3)
-        self.assertEquals(blocks[1], cause_message)
+        self.assertEqual(len(blocks), 3)
+        self.assertEqual(blocks[1], cause_message)
         # The first block is the KeyError raised from the ZeroDivisionError
         self.assertIn('raise KeyError from e', blocks[0])
         self.assertNotIn('1/0', blocks[0])
@@ -313,7 +313,7 @@
             traceback.format_exception(type(e), e, e.__traceback__))
         with captured_output("stderr") as sio:
             traceback.print_exception(type(e), e, e.__traceback__)
-        self.assertEquals(sio.getvalue(), s)
+        self.assertEqual(sio.getvalue(), s)
         return s
 
 

Modified: python/branches/pep-3151/Lib/test/test_ttk_guionly.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_ttk_guionly.py	(original)
+++ python/branches/pep-3151/Lib/test/test_ttk_guionly.py	Sat Feb 26 08:16:32 2011
@@ -8,6 +8,7 @@
 from _tkinter import TclError
 from tkinter import ttk
 from tkinter.test import runtktests
+from tkinter.test.support import get_tk_root
 
 try:
     ttk.Button()
@@ -22,8 +23,11 @@
         elif 'gui' not in support.use_resources:
             support.use_resources.append('gui')
 
-    support.run_unittest(
-            *runtktests.get_tests(text=False, packages=['test_ttk']))
+    try:
+        support.run_unittest(
+                *runtktests.get_tests(text=False, packages=['test_ttk']))
+    finally:
+        get_tk_root().destroy()
 
 if __name__ == '__main__':
     test_main(enable_gui=True)

Modified: python/branches/pep-3151/Lib/test/test_tuple.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_tuple.py	(original)
+++ python/branches/pep-3151/Lib/test/test_tuple.py	Sat Feb 26 08:16:32 2011
@@ -6,7 +6,7 @@
     type2test = tuple
 
     def test_constructors(self):
-        super().test_len()
+        super().test_constructors()
         # calling built-in types without argument must return empty
         self.assertEqual(tuple(), ())
         t0_3 = (0, 1, 2, 3)

Modified: python/branches/pep-3151/Lib/test/test_types.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_types.py	(original)
+++ python/branches/pep-3151/Lib/test/test_types.py	Sat Feb 26 08:16:32 2011
@@ -396,13 +396,9 @@
             self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt)))
 
     def test_float__format__(self):
-        # these should be rewritten to use both format(x, spec) and
-        # x.__format__(spec)
-
         def test(f, format_spec, result):
-            assert type(f) == float
-            assert type(format_spec) == str
             self.assertEqual(f.__format__(format_spec), result)
+            self.assertEqual(format(f, format_spec), result)
 
         test(0.0, 'f', '0.000000')
 
@@ -516,9 +512,27 @@
                 self.assertRaises(ValueError, format, 1e-100, format_spec)
                 self.assertRaises(ValueError, format, -1e-100, format_spec)
 
-        # Alternate formatting is not supported
-        self.assertRaises(ValueError, format, 0.0, '#')
-        self.assertRaises(ValueError, format, 0.0, '#20f')
+        # Alternate float formatting
+        test(1.0, '.0e', '1e+00')
+        test(1.0, '#.0e', '1.e+00')
+        test(1.0, '.0f', '1')
+        test(1.0, '#.0f', '1.')
+        test(1.1, 'g', '1.1')
+        test(1.1, '#g', '1.10000')
+        test(1.0, '.0%', '100%')
+        test(1.0, '#.0%', '100.%')
+
+        # Issue 7094: Alternate formatting (specified by #)
+        test(1.0, '0e',  '1.000000e+00')
+        test(1.0, '#0e', '1.000000e+00')
+        test(1.0, '0f',  '1.000000' )
+        test(1.0, '#0f', '1.000000')
+        test(1.0, '.1e',  '1.0e+00')
+        test(1.0, '#.1e', '1.0e+00')
+        test(1.0, '.1f',  '1.0')
+        test(1.0, '#.1f', '1.0')
+        test(1.0, '.1%',  '100.0%')
+        test(1.0, '#.1%', '100.0%')
 
         # Issue 6902
         test(12345.6, "0<20", '12345.60000000000000')

Modified: python/branches/pep-3151/Lib/test/test_ucn.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_ucn.py	(original)
+++ python/branches/pep-3151/Lib/test/test_ucn.py	Sat Feb 26 08:16:32 2011
@@ -88,9 +88,13 @@
         self.checkletter("CJK UNIFIED IDEOGRAPH-3400", "\u3400")
         self.checkletter("CJK UNIFIED IDEOGRAPH-4DB5", "\u4db5")
         self.checkletter("CJK UNIFIED IDEOGRAPH-4E00", "\u4e00")
-        self.checkletter("CJK UNIFIED IDEOGRAPH-9FA5", "\u9fa5")
+        self.checkletter("CJK UNIFIED IDEOGRAPH-9FCB", "\u9fCB")
         self.checkletter("CJK UNIFIED IDEOGRAPH-20000", "\U00020000")
         self.checkletter("CJK UNIFIED IDEOGRAPH-2A6D6", "\U0002a6d6")
+        self.checkletter("CJK UNIFIED IDEOGRAPH-2A700", "\U0002A700")
+        self.checkletter("CJK UNIFIED IDEOGRAPH-2B734", "\U0002B734")
+        self.checkletter("CJK UNIFIED IDEOGRAPH-2B740", "\U0002B740")
+        self.checkletter("CJK UNIFIED IDEOGRAPH-2B81D", "\U0002B81D")
 
     def test_bmp_characters(self):
         import unicodedata

Modified: python/branches/pep-3151/Lib/test/test_unicode.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_unicode.py	(original)
+++ python/branches/pep-3151/Lib/test/test_unicode.py	Sat Feb 26 08:16:32 2011
@@ -11,6 +11,7 @@
 import unittest
 import warnings
 from test import support, string_tests
+import _string
 
 # Error handling (bad decoder return)
 def search_function(encoding):
@@ -1168,19 +1169,27 @@
         # Error handling (wrong arguments)
         self.assertRaises(TypeError, "hello".encode, 42, 42, 42)
 
-        # Error handling (PyUnicode_EncodeDecimal())
-        self.assertRaises(UnicodeError, int, "\u0200")
+        # Error handling (lone surrogate in PyUnicode_TransformDecimalToASCII())
+        self.assertRaises(UnicodeError, int, "\ud800")
+        self.assertRaises(UnicodeError, int, "\udf00")
+        self.assertRaises(UnicodeError, float, "\ud800")
+        self.assertRaises(UnicodeError, float, "\udf00")
+        self.assertRaises(UnicodeError, complex, "\ud800")
+        self.assertRaises(UnicodeError, complex, "\udf00")
 
     def test_codecs(self):
         # Encoding
         self.assertEqual('hello'.encode('ascii'), b'hello')
         self.assertEqual('hello'.encode('utf-7'), b'hello')
         self.assertEqual('hello'.encode('utf-8'), b'hello')
-        self.assertEqual('hello'.encode('utf8'), b'hello')
+        self.assertEqual('hello'.encode('utf-8'), b'hello')
         self.assertEqual('hello'.encode('utf-16-le'), b'h\000e\000l\000l\000o\000')
         self.assertEqual('hello'.encode('utf-16-be'), b'\000h\000e\000l\000l\000o')
         self.assertEqual('hello'.encode('latin-1'), b'hello')
 
+        # Default encoding is utf-8
+        self.assertEqual('\u2603'.encode(), b'\xe2\x98\x83')
+
         # Roundtrip safety for BMP (just the first 1024 chars)
         for c in range(1024):
             u = chr(c)
@@ -1418,48 +1427,66 @@
         self.assertEqual("%s" % s, '__str__ overridden')
         self.assertEqual("{}".format(s), '__str__ overridden')
 
+    # Test PyUnicode_FromFormat()
     def test_from_format(self):
-        from _testcapi import format_unicode
+        support.import_module('ctypes')
+        from ctypes import pythonapi, py_object, c_int
+        if sys.maxunicode == 65535:
+            name = "PyUnicodeUCS2_FromFormat"
+        else:
+            name = "PyUnicodeUCS4_FromFormat"
+        _PyUnicode_FromFormat = getattr(pythonapi, name)
+        _PyUnicode_FromFormat.restype = py_object
+
+        def PyUnicode_FromFormat(format, *args):
+            cargs = tuple(
+                py_object(arg) if isinstance(arg, str) else arg
+                for arg in args)
+            return _PyUnicode_FromFormat(format, *cargs)
 
         # ascii format, non-ascii argument
-        text = format_unicode(b'ascii\x7f=%U', 'unicode\xe9')
+        text = PyUnicode_FromFormat(b'ascii\x7f=%U', 'unicode\xe9')
         self.assertEqual(text, 'ascii\x7f=unicode\xe9')
 
-        # non-ascii format, ascii argument: ensure that PyUnicode_FromFormat()
-        # raises an error for a non-ascii format string.
-        self.assertRaisesRegexp(ValueError,
+        # non-ascii format, ascii argument: ensure that PyUnicode_FromFormatV()
+        # raises an error
+        self.assertRaisesRegex(ValueError,
             '^PyUnicode_FromFormatV\(\) expects an ASCII-encoded format '
             'string, got a non-ASCII byte: 0xe9$',
-            format_unicode, b'unicode\xe9=%s', 'ascii')
+            PyUnicode_FromFormat, b'unicode\xe9=%s', 'ascii')
+
+        self.assertEqual(PyUnicode_FromFormat(b'%c', c_int(0xabcd)), '\uabcd')
+        self.assertEqual(PyUnicode_FromFormat(b'%c', c_int(0x10ffff)), '\U0010ffff')
 
         # other tests
-        text = format_unicode(b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
+        text = PyUnicode_FromFormat(b'%%A:%A', 'abc\xe9\uabcd\U0010ffff')
         self.assertEqual(text, r"%A:'abc\xe9\uabcd\U0010ffff'")
 
     # Test PyUnicode_AsWideChar()
     def test_aswidechar(self):
         from _testcapi import unicode_aswidechar
+        support.import_module('ctypes')
         from ctypes import c_wchar, sizeof
 
         wchar, size = unicode_aswidechar('abcdef', 2)
-        self.assertEquals(size, 2)
-        self.assertEquals(wchar, 'ab')
+        self.assertEqual(size, 2)
+        self.assertEqual(wchar, 'ab')
 
         wchar, size = unicode_aswidechar('abc', 3)
-        self.assertEquals(size, 3)
-        self.assertEquals(wchar, 'abc')
+        self.assertEqual(size, 3)
+        self.assertEqual(wchar, 'abc')
 
         wchar, size = unicode_aswidechar('abc', 4)
-        self.assertEquals(size, 3)
-        self.assertEquals(wchar, 'abc\0')
+        self.assertEqual(size, 3)
+        self.assertEqual(wchar, 'abc\0')
 
         wchar, size = unicode_aswidechar('abc', 10)
-        self.assertEquals(size, 3)
-        self.assertEquals(wchar, 'abc\0')
+        self.assertEqual(size, 3)
+        self.assertEqual(wchar, 'abc\0')
 
         wchar, size = unicode_aswidechar('abc\0def', 20)
-        self.assertEquals(size, 7)
-        self.assertEquals(wchar, 'abc\0def\0')
+        self.assertEqual(size, 7)
+        self.assertEqual(wchar, 'abc\0def\0')
 
         nonbmp = chr(0x10ffff)
         if sizeof(c_wchar) == 2:
@@ -1469,21 +1496,22 @@
             buflen = 2
             nchar = 1
         wchar, size = unicode_aswidechar(nonbmp, buflen)
-        self.assertEquals(size, nchar)
-        self.assertEquals(wchar, nonbmp + '\0')
+        self.assertEqual(size, nchar)
+        self.assertEqual(wchar, nonbmp + '\0')
 
     # Test PyUnicode_AsWideCharString()
     def test_aswidecharstring(self):
         from _testcapi import unicode_aswidecharstring
+        support.import_module('ctypes')
         from ctypes import c_wchar, sizeof
 
         wchar, size = unicode_aswidecharstring('abc')
-        self.assertEquals(size, 3)
-        self.assertEquals(wchar, 'abc\0')
+        self.assertEqual(size, 3)
+        self.assertEqual(wchar, 'abc\0')
 
         wchar, size = unicode_aswidecharstring('abc\0def')
-        self.assertEquals(size, 7)
-        self.assertEquals(wchar, 'abc\0def\0')
+        self.assertEqual(size, 7)
+        self.assertEqual(wchar, 'abc\0def\0')
 
         nonbmp = chr(0x10ffff)
         if sizeof(c_wchar) == 2:
@@ -1491,8 +1519,59 @@
         else: # sizeof(c_wchar) == 4
             nchar = 1
         wchar, size = unicode_aswidecharstring(nonbmp)
-        self.assertEquals(size, nchar)
-        self.assertEquals(wchar, nonbmp + '\0')
+        self.assertEqual(size, nchar)
+        self.assertEqual(wchar, nonbmp + '\0')
+
+
+class StringModuleTest(unittest.TestCase):
+    def test_formatter_parser(self):
+        def parse(format):
+            return list(_string.formatter_parser(format))
+
+        formatter = parse("prefix {2!s}xxx{0:^+10.3f}{obj.attr!s} {z[0]!s:10}")
+        self.assertEqual(formatter, [
+            ('prefix ', '2', '', 's'),
+            ('xxx', '0', '^+10.3f', None),
+            ('', 'obj.attr', '', 's'),
+            (' ', 'z[0]', '10', 's'),
+        ])
+
+        formatter = parse("prefix {} suffix")
+        self.assertEqual(formatter, [
+            ('prefix ', '', '', None),
+            (' suffix', None, None, None),
+        ])
+
+        formatter = parse("str")
+        self.assertEqual(formatter, [
+            ('str', None, None, None),
+        ])
+
+        formatter = parse("")
+        self.assertEqual(formatter, [])
+
+        formatter = parse("{0}")
+        self.assertEqual(formatter, [
+            ('', '0', '', None),
+        ])
+
+        self.assertRaises(TypeError, _string.formatter_parser, 1)
+
+    def test_formatter_field_name_split(self):
+        def split(name):
+            items = list(_string.formatter_field_name_split(name))
+            items[1] = list(items[1])
+            return items
+        self.assertEqual(split("obj"), ["obj", []])
+        self.assertEqual(split("obj.arg"), ["obj", [(True, 'arg')]])
+        self.assertEqual(split("obj[key]"), ["obj", [(False, 'key')]])
+        self.assertEqual(split("obj.arg[key1][key2]"), [
+            "obj",
+            [(True, 'arg'),
+             (False, 'key1'),
+             (False, 'key2'),
+            ]])
+        self.assertRaises(TypeError, _string.formatter_field_name_split, 1)
 
 
 def test_main():

Modified: python/branches/pep-3151/Lib/test/test_unicodedata.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_unicodedata.py	(original)
+++ python/branches/pep-3151/Lib/test/test_unicodedata.py	Sat Feb 26 08:16:32 2011
@@ -188,9 +188,22 @@
 
     def test_pr29(self):
         # http://www.unicode.org/review/pr-29.html
-        for text in ("\u0b47\u0300\u0b3e", "\u1100\u0300\u1161"):
+        # See issues #1054943 and #10254.
+        composed = ("\u0b47\u0300\u0b3e", "\u1100\u0300\u1161",
+                    'Li\u030dt-s\u1e73\u0301',
+                    '\u092e\u093e\u0930\u094d\u0915 \u091c\u093c'
+                    + '\u0941\u0915\u0947\u0930\u092c\u0930\u094d\u0917',
+                    '\u0915\u093f\u0930\u094d\u0917\u093f\u091c\u093c'
+                    + '\u0938\u094d\u0924\u093e\u0928')
+        for text in composed:
             self.assertEqual(self.db.normalize('NFC', text), text)
 
+    def test_issue10254(self):
+        # Crash reported in #10254
+        a = 'C\u0338' * 20  + 'C\u0327'
+        b = 'C\u0338' * 20  + '\xC7'
+        self.assertEqual(self.db.normalize('NFC', a), b)
+
     def test_east_asian_width(self):
         eaw = self.db.east_asian_width
         self.assertRaises(TypeError, eaw, b'a')
@@ -254,7 +267,7 @@
         self.assertTrue(count >= 10) # should have tested at least the ASCII digits
 
     def test_bug_1704793(self):
-        self.assertEquals(self.db.lookup("GOTHIC LETTER FAIHU"), '\U00010346')
+        self.assertEqual(self.db.lookup("GOTHIC LETTER FAIHU"), '\U00010346')
 
     def test_ucd_510(self):
         import unicodedata

Modified: python/branches/pep-3151/Lib/test/test_unittest.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_unittest.py	(original)
+++ python/branches/pep-3151/Lib/test/test_unittest.py	Sat Feb 26 08:16:32 2011
@@ -4,8 +4,13 @@
 
 
 def test_main():
+    # used by regrtest
     support.run_unittest(unittest.test.suite())
     support.reap_children()
 
+def load_tests(*_):
+    # used by unittest
+    return unittest.test.suite()
+
 if __name__ == "__main__":
     test_main()

Modified: python/branches/pep-3151/Lib/test/test_urllib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_urllib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_urllib.py	Sat Feb 26 08:16:32 2011
@@ -139,8 +139,10 @@
 
     def fakehttp(self, fakedata):
         class FakeSocket(io.BytesIO):
+            io_refs = 1
             def sendall(self, str): pass
             def makefile(self, *args, **kwds):
+                self.io_refs += 1
                 return self
             def read(self, amt=None):
                 if self.closed: return b""
@@ -148,6 +150,10 @@
             def readline(self, length=None):
                 if self.closed: return b""
                 return io.BytesIO.readline(self, length)
+            def close(self):
+                self.io_refs -= 1
+                if self.io_refs == 0:
+                    io.BytesIO.close(self)
         class FakeHTTPConnection(http.client.HTTPConnection):
             def connect(self):
                 self.sock = FakeSocket(fakedata)
@@ -157,8 +163,8 @@
     def unfakehttp(self):
         http.client.HTTPConnection = self._connection_class
 
-    def test_read(self):
-        self.fakehttp(b"Hello!")
+    def check_read(self, ver):
+        self.fakehttp(b"HTTP/" + ver + b" 200 OK\r\n\r\nHello!")
         try:
             fp = urlopen("http://python.org/")
             self.assertEqual(fp.readline(), b"Hello!")
@@ -168,6 +174,17 @@
         finally:
             self.unfakehttp()
 
+    def test_read_0_9(self):
+        # "0.9" response accepted (but not "simple responses" without
+        # a status line)
+        self.check_read(b"0.9")
+
+    def test_read_1_0(self):
+        self.check_read(b"1.0")
+
+    def test_read_1_1(self):
+        self.check_read(b"1.1")
+
     def test_read_bogus(self):
         # urlopen() should raise IOError for many error codes.
         self.fakehttp(b'''HTTP/1.1 401 Authentication Required
@@ -191,7 +208,7 @@
             self.unfakehttp()
 
     def test_userpass_inurl(self):
-        self.fakehttp(b"Hello!")
+        self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!")
         try:
             fp = urlopen("http://user:pass@python.org/")
             self.assertEqual(fp.readline(), b"Hello!")
@@ -234,7 +251,7 @@
     def constructLocalFileUrl(self, filePath):
         filePath = os.path.abspath(filePath)
         try:
-            filePath.encode("utf8")
+            filePath.encode("utf-8")
         except UnicodeEncodeError:
             raise unittest.SkipTest("filePath is not encodable to utf8")
         return "file://%s" % urllib.request.pathname2url(filePath)

Modified: python/branches/pep-3151/Lib/test/test_urllib2.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_urllib2.py	(original)
+++ python/branches/pep-3151/Lib/test/test_urllib2.py	Sat Feb 26 08:16:32 2011
@@ -4,6 +4,7 @@
 import os
 import io
 import socket
+import array
 
 import urllib.request
 from urllib.request import Request, OpenerDirector
@@ -598,7 +599,7 @@
 
 def sanepathname2url(path):
     try:
-        path.encode("utf8")
+        path.encode("utf-8")
     except UnicodeEncodeError:
         raise unittest.SkipTest("path is not encodable to utf8")
     urlpath = urllib.request.pathname2url(path)
@@ -631,22 +632,32 @@
         h = NullFTPHandler(data)
         o = h.parent = MockOpener()
 
-        for url, host, port, type_, dirs, filename, mimetype in [
+        for url, host, port, user, passwd, type_, dirs, filename, mimetype in [
             ("ftp://localhost/foo/bar/baz.html",
-             "localhost", ftplib.FTP_PORT, "I",
+             "localhost", ftplib.FTP_PORT, "", "", "I",
+             ["foo", "bar"], "baz.html", "text/html"),
+            ("ftp://parrot@localhost/foo/bar/baz.html",
+             "localhost", ftplib.FTP_PORT, "parrot", "", "I",
+             ["foo", "bar"], "baz.html", "text/html"),
+            ("ftp://%25parrot@localhost/foo/bar/baz.html",
+             "localhost", ftplib.FTP_PORT, "%parrot", "", "I",
+             ["foo", "bar"], "baz.html", "text/html"),
+            ("ftp://%2542parrot@localhost/foo/bar/baz.html",
+             "localhost", ftplib.FTP_PORT, "%42parrot", "", "I",
              ["foo", "bar"], "baz.html", "text/html"),
             ("ftp://localhost:80/foo/bar/",
-             "localhost", 80, "D",
+             "localhost", 80, "", "", "D",
              ["foo", "bar"], "", None),
             ("ftp://localhost/baz.gif;type=a",
-             "localhost", ftplib.FTP_PORT, "A",
+             "localhost", ftplib.FTP_PORT, "", "", "A",
              [], "baz.gif", None),  # XXX really this should guess image/gif
             ]:
             req = Request(url)
             req.timeout = None
             r = h.ftp_open(req)
             # ftp authentication not yet implemented by FTPHandler
-            self.assertTrue(h.user == h.passwd == "")
+            self.assertEqual(h.user, user)
+            self.assertEqual(h.passwd, passwd)
             self.assertEqual(h.host, socket.gethostbyname(host))
             self.assertEqual(h.port, port)
             self.assertEqual(h.dirs, dirs)
@@ -747,7 +758,7 @@
             else:
                 self.assertIs(o.req, req)
                 self.assertEqual(req.type, "ftp")
-            self.assertEqual(req.type is "ftp", ftp)
+            self.assertEqual(req.type == "ftp", ftp)
 
     def test_http(self):
 
@@ -755,7 +766,7 @@
         o = h.parent = MockOpener()
 
         url = "http://example.com/"
-        for method, data in [("GET", None), ("POST", "blah")]:
+        for method, data in [("GET", None), ("POST", b"blah")]:
             req = Request(url, data, {"Foo": "bar"})
             req.timeout = None
             req.add_unredirected_header("Spam", "eggs")
@@ -783,9 +794,13 @@
         http.raise_on_endheaders = True
         self.assertRaises(urllib.error.URLError, h.do_open, http, req)
 
+        # Check for TypeError on POST data which is str.
+        req = Request("http://example.com/","badpost")
+        self.assertRaises(TypeError, h.do_request_, req)
+
         # check adding of standard headers
         o.addheaders = [("Spam", "eggs")]
-        for data in "", None:  # POST, GET
+        for data in b"", None:  # POST, GET
             req = Request("http://example.com/", data)
             r = MockResponse(200, "OK", {}, "")
             newreq = h.do_request_(req)
@@ -811,6 +826,48 @@
             self.assertEqual(req.unredirected_hdrs["Host"], "baz")
             self.assertEqual(req.unredirected_hdrs["Spam"], "foo")
 
+        # Check iterable body support
+        def iterable_body():
+            yield b"one"
+            yield b"two"
+            yield b"three"
+
+        for headers in {}, {"Content-Length": 11}:
+            req = Request("http://example.com/", iterable_body(), headers)
+            if not headers:
+                # Having an iterable body without a Content-Length should
+                # raise an exception
+                self.assertRaises(ValueError, h.do_request_, req)
+            else:
+                newreq = h.do_request_(req)
+
+        # A file object.
+        # Test only Content-Length attribute of request.
+
+        file_obj = io.BytesIO()
+        file_obj.write(b"Something\nSomething\nSomething\n")
+
+        for headers in {}, {"Content-Length": 30}:
+            req = Request("http://example.com/", file_obj, headers)
+            if not headers:
+                # Having an iterable body without a Content-Length should
+                # raise an exception
+                self.assertRaises(ValueError, h.do_request_, req)
+            else:
+                newreq = h.do_request_(req)
+                self.assertEqual(int(newreq.get_header('Content-length')),30)
+
+        file_obj.close()
+
+        # array.array Iterable - Content Length is calculated
+
+        iterable_array = array.array("I",[1,2,3,4])
+
+        for headers in {}, {"Content-Length": 16}:
+            req = Request("http://example.com/", iterable_array, headers)
+            newreq = h.do_request_(req)
+            self.assertEqual(int(newreq.get_header('Content-length')),16)
+
     def test_http_doubleslash(self):
         # Checks the presence of any unnecessary double slash in url does not
         # break anything. Previously, a double slash directly after the host
@@ -818,7 +875,7 @@
         h = urllib.request.AbstractHTTPHandler()
         o = h.parent = MockOpener()
 
-        data = ""
+        data = b""
         ds_urls = [
             "http://example.com/foo/bar/baz.html",
             "http://example.com//foo/bar/baz.html",
@@ -838,6 +895,25 @@
             p_ds_req = h.do_request_(ds_req)
             self.assertEqual(p_ds_req.unredirected_hdrs["Host"],"example.com")
 
+    def test_fixpath_in_weirdurls(self):
+        # Issue4493: urllib2 to supply '/' when to urls where path does not
+        # start with'/'
+
+        h = urllib.request.AbstractHTTPHandler()
+        o = h.parent = MockOpener()
+
+        weird_url = 'http://www.python.org?getspam'
+        req = Request(weird_url)
+        newreq = h.do_request_(req)
+        self.assertEqual(newreq.host,'www.python.org')
+        self.assertEqual(newreq.selector,'/?getspam')
+
+        url_without_path = 'http://www.python.org'
+        req = Request(url_without_path)
+        newreq = h.do_request_(req)
+        self.assertEqual(newreq.host,'www.python.org')
+        self.assertEqual(newreq.selector,'')
+
 
     def test_errors(self):
         h = urllib.request.HTTPErrorProcessor()

Modified: python/branches/pep-3151/Lib/test/test_urllibnet.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_urllibnet.py	(original)
+++ python/branches/pep-3151/Lib/test/test_urllibnet.py	Sat Feb 26 08:16:32 2011
@@ -13,7 +13,7 @@
 
 class URLTimeoutTest(unittest.TestCase):
 
-    TIMEOUT = 10.0
+    TIMEOUT = 30.0
 
     def setUp(self):
         socket.setdefaulttimeout(self.TIMEOUT)

Modified: python/branches/pep-3151/Lib/test/test_urlparse.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_urlparse.py	(original)
+++ python/branches/pep-3151/Lib/test/test_urlparse.py	Sat Feb 26 08:16:32 2011
@@ -24,6 +24,17 @@
     ("&a=b", [('a', 'b')]),
     ("a=a+b&b=b+c", [('a', 'a b'), ('b', 'b c')]),
     ("a=1&a=2", [('a', '1'), ('a', '2')]),
+    (b"", []),
+    (b"&", []),
+    (b"&&", []),
+    (b"=", [(b'', b'')]),
+    (b"=a", [(b'', b'a')]),
+    (b"a", [(b'a', b'')]),
+    (b"a=", [(b'a', b'')]),
+    (b"a=", [(b'a', b'')]),
+    (b"&a=b", [(b'a', b'b')]),
+    (b"a=a+b&b=b+c", [(b'a', b'a b'), (b'b', b'b c')]),
+    (b"a=1&a=2", [(b'a', b'1'), (b'a', b'2')]),
 ]
 
 class UrlParseTestCase(unittest.TestCase):
@@ -86,7 +97,7 @@
 
 
     def test_roundtrips(self):
-        testcases = [
+        str_cases = [
             ('file:///tmp/junk.txt',
              ('file', '', '/tmp/junk.txt', '', '', ''),
              ('file', '', '/tmp/junk.txt', '', '')),
@@ -110,16 +121,21 @@
             ('git+ssh', 'git at github.com','/user/project.git',
              '','',''),
             ('git+ssh', 'git at github.com','/user/project.git',
-             '', ''))
+             '', '')),
             ]
-        for url, parsed, split in testcases:
+        def _encode(t):
+            return (t[0].encode('ascii'),
+                    tuple(x.encode('ascii') for x in t[1]),
+                    tuple(x.encode('ascii') for x in t[2]))
+        bytes_cases = [_encode(x) for x in str_cases]
+        for url, parsed, split in str_cases + bytes_cases:
             self.checkRoundtrips(url, parsed, split)
 
     def test_http_roundtrips(self):
         # urllib.parse.urlsplit treats 'http:' as an optimized special case,
         # so we test both 'http:' and 'https:' in all the following.
         # Three cheers for white box knowledge!
-        testcases = [
+        str_cases = [
             ('://www.python.org',
              ('www.python.org', '', '', '', ''),
              ('www.python.org', '', '', '')),
@@ -136,19 +152,34 @@
              ('a', '/b/c/d', 'p', 'q', 'f'),
              ('a', '/b/c/d;p', 'q', 'f')),
             ]
-        for scheme in ('http', 'https'):
-            for url, parsed, split in testcases:
-                url = scheme + url
-                parsed = (scheme,) + parsed
-                split = (scheme,) + split
-                self.checkRoundtrips(url, parsed, split)
+        def _encode(t):
+            return (t[0].encode('ascii'),
+                    tuple(x.encode('ascii') for x in t[1]),
+                    tuple(x.encode('ascii') for x in t[2]))
+        bytes_cases = [_encode(x) for x in str_cases]
+        str_schemes = ('http', 'https')
+        bytes_schemes = (b'http', b'https')
+        str_tests = str_schemes, str_cases
+        bytes_tests = bytes_schemes, bytes_cases
+        for schemes, test_cases in (str_tests, bytes_tests):
+            for scheme in schemes:
+                for url, parsed, split in test_cases:
+                    url = scheme + url
+                    parsed = (scheme,) + parsed
+                    split = (scheme,) + split
+                    self.checkRoundtrips(url, parsed, split)
 
     def checkJoin(self, base, relurl, expected):
-        self.assertEqual(urllib.parse.urljoin(base, relurl), expected,
-                         (base, relurl, expected))
+        str_components = (base, relurl, expected)
+        self.assertEqual(urllib.parse.urljoin(base, relurl), expected)
+        bytes_components = baseb, relurlb, expectedb = [
+                            x.encode('ascii') for x in str_components]
+        self.assertEqual(urllib.parse.urljoin(baseb, relurlb), expectedb)
 
     def test_unparse_parse(self):
-        for u in ['Python', './Python','x-newscheme://foo.com/stuff','x://y','x:/y','x:/','/',]:
+        str_cases = ['Python', './Python','x-newscheme://foo.com/stuff','x://y','x:/y','x:/','/',]
+        bytes_cases = [x.encode('ascii') for x in str_cases]
+        for u in str_cases + bytes_cases:
             self.assertEqual(urllib.parse.urlunsplit(urllib.parse.urlsplit(u)), u)
             self.assertEqual(urllib.parse.urlunparse(urllib.parse.urlparse(u)), u)
 
@@ -296,6 +327,9 @@
         #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser
         self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser
 
+        # Test for issue9721
+        self.checkJoin('http://a/b/c/de', ';x','http://a/b/c/;x')
+
     def test_urljoins(self):
         self.checkJoin(SIMPLE_BASE, 'g:h','g:h')
         self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g')
@@ -328,7 +362,7 @@
         self.checkJoin(SIMPLE_BASE, 'http:g?y/./x','http://a/b/c/g?y/./x')
 
     def test_RFC2732(self):
-        for url, hostname, port in [
+        str_cases = [
             ('http://Test.python.org:5432/foo/', 'test.python.org', 5432),
             ('http://12.34.56.78:5432/foo/', '12.34.56.78', 5432),
             ('http://[::1]:5432/foo/', '::1', 5432),
@@ -349,20 +383,26 @@
             ('http://[::12.34.56.78]/foo/', '::12.34.56.78', None),
             ('http://[::ffff:12.34.56.78]/foo/',
              '::ffff:12.34.56.78', None),
-            ]:
+            ]
+        def _encode(t):
+            return t[0].encode('ascii'), t[1].encode('ascii'), t[2]
+        bytes_cases = [_encode(x) for x in str_cases]
+        for url, hostname, port in str_cases + bytes_cases:
             urlparsed = urllib.parse.urlparse(url)
             self.assertEqual((urlparsed.hostname, urlparsed.port) , (hostname, port))
 
-        for invalid_url in [
+        str_cases = [
                 'http://::12.34.56.78]/',
                 'http://[::1/foo/',
                 'ftp://[::1/foo/bad]/bad',
                 'http://[::1/foo/bad]/bad',
-                'http://[::ffff:12.34.56.78']:
+                'http://[::ffff:12.34.56.78']
+        bytes_cases = [x.encode('ascii') for x in str_cases]
+        for invalid_url in str_cases + bytes_cases:
             self.assertRaises(ValueError, urllib.parse.urlparse, invalid_url)
 
     def test_urldefrag(self):
-        for url, defrag, frag in [
+        str_cases = [
             ('http://python.org#frag', 'http://python.org', 'frag'),
             ('http://python.org', 'http://python.org', ''),
             ('http://python.org/#frag', 'http://python.org/', 'frag'),
@@ -373,8 +413,16 @@
             ('http://python.org/p?q', 'http://python.org/p?q', ''),
             (RFC1808_BASE, 'http://a/b/c/d;p?q', 'f'),
             (RFC2396_BASE, 'http://a/b/c/d;p?q', ''),
-            ]:
-            self.assertEqual(urllib.parse.urldefrag(url), (defrag, frag))
+        ]
+        def _encode(t):
+            return type(t)(x.encode('ascii') for x in t)
+        bytes_cases = [_encode(x) for x in str_cases]
+        for url, defrag, frag in str_cases + bytes_cases:
+            result = urllib.parse.urldefrag(url)
+            self.assertEqual(result.geturl(), url)
+            self.assertEqual(result, (defrag, frag))
+            self.assertEqual(result.url, defrag)
+            self.assertEqual(result.fragment, frag)
 
     def test_urlsplit_attributes(self):
         url = "HTTP://WWW.PYTHON.ORG/doc/#frag"
@@ -390,7 +438,8 @@
         self.assertEqual(p.port, None)
         # geturl() won't return exactly the original URL in this case
         # since the scheme is always case-normalized
-        #self.assertEqual(p.geturl(), url)
+        # We handle this by ignoring the first 4 characters of the URL
+        self.assertEqual(p.geturl()[4:], url[4:])
 
         url = "http://User:Pass@www.python.org:080/doc/?query=yes#frag"
         p = urllib.parse.urlsplit(url)
@@ -422,6 +471,45 @@
         self.assertEqual(p.port, 80)
         self.assertEqual(p.geturl(), url)
 
+        # And check them all again, only with bytes this time
+        url = b"HTTP://WWW.PYTHON.ORG/doc/#frag"
+        p = urllib.parse.urlsplit(url)
+        self.assertEqual(p.scheme, b"http")
+        self.assertEqual(p.netloc, b"WWW.PYTHON.ORG")
+        self.assertEqual(p.path, b"/doc/")
+        self.assertEqual(p.query, b"")
+        self.assertEqual(p.fragment, b"frag")
+        self.assertEqual(p.username, None)
+        self.assertEqual(p.password, None)
+        self.assertEqual(p.hostname, b"www.python.org")
+        self.assertEqual(p.port, None)
+        self.assertEqual(p.geturl()[4:], url[4:])
+
+        url = b"http://User:Pass@www.python.org:080/doc/?query=yes#frag"
+        p = urllib.parse.urlsplit(url)
+        self.assertEqual(p.scheme, b"http")
+        self.assertEqual(p.netloc, b"User:Pass at www.python.org:080")
+        self.assertEqual(p.path, b"/doc/")
+        self.assertEqual(p.query, b"query=yes")
+        self.assertEqual(p.fragment, b"frag")
+        self.assertEqual(p.username, b"User")
+        self.assertEqual(p.password, b"Pass")
+        self.assertEqual(p.hostname, b"www.python.org")
+        self.assertEqual(p.port, 80)
+        self.assertEqual(p.geturl(), url)
+
+        url = b"http://User@example.com:Pass@www.python.org:080/doc/?query=yes#frag"
+        p = urllib.parse.urlsplit(url)
+        self.assertEqual(p.scheme, b"http")
+        self.assertEqual(p.netloc, b"User at example.com:Pass at www.python.org:080")
+        self.assertEqual(p.path, b"/doc/")
+        self.assertEqual(p.query, b"query=yes")
+        self.assertEqual(p.fragment, b"frag")
+        self.assertEqual(p.username, b"User at example.com")
+        self.assertEqual(p.password, b"Pass")
+        self.assertEqual(p.hostname, b"www.python.org")
+        self.assertEqual(p.port, 80)
+        self.assertEqual(p.geturl(), url)
 
     def test_attributes_bad_port(self):
         """Check handling of non-integer ports."""
@@ -433,6 +521,15 @@
         self.assertEqual(p.netloc, "www.example.net:foo")
         self.assertRaises(ValueError, lambda: p.port)
 
+        # Once again, repeat ourselves to test bytes
+        p = urllib.parse.urlsplit(b"http://www.example.net:foo")
+        self.assertEqual(p.netloc, b"www.example.net:foo")
+        self.assertRaises(ValueError, lambda: p.port)
+
+        p = urllib.parse.urlparse(b"http://www.example.net:foo")
+        self.assertEqual(p.netloc, b"www.example.net:foo")
+        self.assertRaises(ValueError, lambda: p.port)
+
     def test_attributes_without_netloc(self):
         # This example is straight from RFC 3261.  It looks like it
         # should allow the username, hostname, and port to be filled
@@ -456,10 +553,30 @@
         self.assertEqual(p.port, None)
         self.assertEqual(p.geturl(), uri)
 
+        # You guessed it, repeating the test with bytes input
+        uri = b"sip:alice at atlanta.com;maddr=239.255.255.1;ttl=15"
+        p = urllib.parse.urlsplit(uri)
+        self.assertEqual(p.netloc, b"")
+        self.assertEqual(p.username, None)
+        self.assertEqual(p.password, None)
+        self.assertEqual(p.hostname, None)
+        self.assertEqual(p.port, None)
+        self.assertEqual(p.geturl(), uri)
+
+        p = urllib.parse.urlparse(uri)
+        self.assertEqual(p.netloc, b"")
+        self.assertEqual(p.username, None)
+        self.assertEqual(p.password, None)
+        self.assertEqual(p.hostname, None)
+        self.assertEqual(p.port, None)
+        self.assertEqual(p.geturl(), uri)
+
     def test_noslash(self):
         # Issue 1637: http://foo.com?query is legal
         self.assertEqual(urllib.parse.urlparse("http://example.com?blahblah=/foo"),
                          ('http', 'example.com', '', '', 'blahblah=/foo', ''))
+        self.assertEqual(urllib.parse.urlparse(b"http://example.com?blahblah=/foo"),
+                         (b'http', b'example.com', b'', b'', b'blahblah=/foo', b''))
 
     def test_withoutscheme(self):
         # Test urlparse without scheme
@@ -472,6 +589,13 @@
                 ('','www.python.org:80','','','',''))
         self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"),
                 ('http','www.python.org:80','','','',''))
+        # Repeat for bytes input
+        self.assertEqual(urllib.parse.urlparse(b"path"),
+                (b'',b'',b'path',b'',b'',b''))
+        self.assertEqual(urllib.parse.urlparse(b"//www.python.org:80"),
+                (b'',b'www.python.org:80',b'',b'',b'',b''))
+        self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"),
+                (b'http',b'www.python.org:80',b'',b'',b'',b''))
 
     def test_portseparator(self):
         # Issue 754016 makes changes for port separator ':' from scheme separator
@@ -481,6 +605,13 @@
         self.assertEqual(urllib.parse.urlparse("https:"),('https','','','','',''))
         self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"),
                 ('http','www.python.org:80','','','',''))
+        # As usual, need to check bytes input as well
+        self.assertEqual(urllib.parse.urlparse(b"path:80"),
+                (b'',b'',b'path:80',b'',b'',b''))
+        self.assertEqual(urllib.parse.urlparse(b"http:"),(b'http',b'',b'',b'',b'',b''))
+        self.assertEqual(urllib.parse.urlparse(b"https:"),(b'https',b'',b'',b'',b'',b''))
+        self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"),
+                (b'http',b'www.python.org:80',b'',b'',b'',b''))
 
     def test_usingsys(self):
         # Issue 3314: sys module is used in the error
@@ -492,6 +623,98 @@
                          ('s3', 'foo.com', '/stuff', '', '', ''))
         self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff"),
                          ('x-newscheme', 'foo.com', '/stuff', '', '', ''))
+        # And for bytes...
+        self.assertEqual(urllib.parse.urlparse(b"s3://foo.com/stuff"),
+                         (b's3', b'foo.com', b'/stuff', b'', b'', b''))
+        self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff"),
+                         (b'x-newscheme', b'foo.com', b'/stuff', b'', b'', b''))
+
+    def test_mixed_types_rejected(self):
+        # Several functions that process either strings or ASCII encoded bytes
+        # accept multiple arguments. Check they reject mixed type input
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urlparse("www.python.org", b"http")
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urlparse(b"www.python.org", "http")
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urlsplit("www.python.org", b"http")
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urlsplit(b"www.python.org", "http")
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urlunparse(( b"http", "www.python.org","","","",""))
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urlunparse(("http", b"www.python.org","","","",""))
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urlunsplit((b"http", "www.python.org","","",""))
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urlunsplit(("http", b"www.python.org","","",""))
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urljoin("http://python.org", b"http://python.org")
+        with self.assertRaisesRegex(TypeError, "Cannot mix str"):
+            urllib.parse.urljoin(b"http://python.org", "http://python.org")
+
+    def _check_result_type(self, str_type):
+        num_args = len(str_type._fields)
+        bytes_type = str_type._encoded_counterpart
+        self.assertIs(bytes_type._decoded_counterpart, str_type)
+        str_args = ('',) * num_args
+        bytes_args = (b'',) * num_args
+        str_result = str_type(*str_args)
+        bytes_result = bytes_type(*bytes_args)
+        encoding = 'ascii'
+        errors = 'strict'
+        self.assertEqual(str_result, str_args)
+        self.assertEqual(bytes_result.decode(), str_args)
+        self.assertEqual(bytes_result.decode(), str_result)
+        self.assertEqual(bytes_result.decode(encoding), str_args)
+        self.assertEqual(bytes_result.decode(encoding), str_result)
+        self.assertEqual(bytes_result.decode(encoding, errors), str_args)
+        self.assertEqual(bytes_result.decode(encoding, errors), str_result)
+        self.assertEqual(bytes_result, bytes_args)
+        self.assertEqual(str_result.encode(), bytes_args)
+        self.assertEqual(str_result.encode(), bytes_result)
+        self.assertEqual(str_result.encode(encoding), bytes_args)
+        self.assertEqual(str_result.encode(encoding), bytes_result)
+        self.assertEqual(str_result.encode(encoding, errors), bytes_args)
+        self.assertEqual(str_result.encode(encoding, errors), bytes_result)
+
+    def test_result_pairs(self):
+        # Check encoding and decoding between result pairs
+        result_types = [
+          urllib.parse.DefragResult,
+          urllib.parse.SplitResult,
+          urllib.parse.ParseResult,
+        ]
+        for result_type in result_types:
+            self._check_result_type(result_type)
+
+    def test_parse_qs_encoding(self):
+        result = urllib.parse.parse_qs("key=\u0141%E9", encoding="latin-1")
+        self.assertEqual(result, {'key': ['\u0141\xE9']})
+        result = urllib.parse.parse_qs("key=\u0141%C3%A9", encoding="utf-8")
+        self.assertEqual(result, {'key': ['\u0141\xE9']})
+        result = urllib.parse.parse_qs("key=\u0141%C3%A9", encoding="ascii")
+        self.assertEqual(result, {'key': ['\u0141\ufffd\ufffd']})
+        result = urllib.parse.parse_qs("key=\u0141%E9-", encoding="ascii")
+        self.assertEqual(result, {'key': ['\u0141\ufffd-']})
+        result = urllib.parse.parse_qs("key=\u0141%E9-", encoding="ascii",
+                                                          errors="ignore")
+        self.assertEqual(result, {'key': ['\u0141-']})
+
+    def test_parse_qsl_encoding(self):
+        result = urllib.parse.parse_qsl("key=\u0141%E9", encoding="latin-1")
+        self.assertEqual(result, [('key', '\u0141\xE9')])
+        result = urllib.parse.parse_qsl("key=\u0141%C3%A9", encoding="utf-8")
+        self.assertEqual(result, [('key', '\u0141\xE9')])
+        result = urllib.parse.parse_qsl("key=\u0141%C3%A9", encoding="ascii")
+        self.assertEqual(result, [('key', '\u0141\ufffd\ufffd')])
+        result = urllib.parse.parse_qsl("key=\u0141%E9-", encoding="ascii")
+        self.assertEqual(result, [('key', '\u0141\ufffd-')])
+        result = urllib.parse.parse_qsl("key=\u0141%E9-", encoding="ascii",
+                                                          errors="ignore")
+        self.assertEqual(result, [('key', '\u0141-')])
+
+
 
 def test_main():
     support.run_unittest(UrlParseTestCase)

Modified: python/branches/pep-3151/Lib/test/test_uuid.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_uuid.py	(original)
+++ python/branches/pep-3151/Lib/test/test_uuid.py	Sat Feb 26 08:16:32 2011
@@ -471,14 +471,14 @@
         if pid == 0:
             os.close(fds[0])
             value = uuid.uuid4()
-            os.write(fds[1], value.hex.encode('latin1'))
+            os.write(fds[1], value.hex.encode('latin-1'))
             os._exit(0)
 
         else:
             os.close(fds[1])
             parent_value = uuid.uuid4().hex
             os.waitpid(pid, 0)
-            child_value = os.read(fds[0], 100).decode('latin1')
+            child_value = os.read(fds[0], 100).decode('latin-1')
 
             self.assertNotEqual(parent_value, child_value)
 

Modified: python/branches/pep-3151/Lib/test/test_warnings.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_warnings.py	(original)
+++ python/branches/pep-3151/Lib/test/test_warnings.py	Sat Feb 26 08:16:32 2011
@@ -80,7 +80,7 @@
             self.module.resetwarnings()
             self.module.filterwarnings("ignore", category=UserWarning)
             self.module.warn("FilterTests.test_ignore", UserWarning)
-            self.assertEquals(len(w), 0)
+            self.assertEqual(len(w), 0)
 
     def test_always(self):
         with original_warnings.catch_warnings(record=True,
@@ -102,10 +102,10 @@
             for x in range(2):
                 self.module.warn(message, UserWarning)
                 if x == 0:
-                    self.assertEquals(w[-1].message, message)
+                    self.assertEqual(w[-1].message, message)
                     del w[:]
                 elif x == 1:
-                    self.assertEquals(len(w), 0)
+                    self.assertEqual(len(w), 0)
                 else:
                     raise ValueError("loop variant unhandled")
 
@@ -116,10 +116,10 @@
             self.module.filterwarnings("module", category=UserWarning)
             message = UserWarning("FilterTests.test_module")
             self.module.warn(message, UserWarning)
-            self.assertEquals(w[-1].message, message)
+            self.assertEqual(w[-1].message, message)
             del w[:]
             self.module.warn(message, UserWarning)
-            self.assertEquals(len(w), 0)
+            self.assertEqual(len(w), 0)
 
     def test_once(self):
         with original_warnings.catch_warnings(record=True,
@@ -129,14 +129,14 @@
             message = UserWarning("FilterTests.test_once")
             self.module.warn_explicit(message, UserWarning, "test_warnings.py",
                                     42)
-            self.assertEquals(w[-1].message, message)
+            self.assertEqual(w[-1].message, message)
             del w[:]
             self.module.warn_explicit(message, UserWarning, "test_warnings.py",
                                     13)
-            self.assertEquals(len(w), 0)
+            self.assertEqual(len(w), 0)
             self.module.warn_explicit(message, UserWarning, "test_warnings2.py",
                                     42)
-            self.assertEquals(len(w), 0)
+            self.assertEqual(len(w), 0)
 
     def test_inheritance(self):
         with original_warnings.catch_warnings(module=self.module) as w:
@@ -157,7 +157,7 @@
                 self.module.warn("FilterTests.test_ordering", UserWarning)
             except UserWarning:
                 self.fail("order handling for actions failed")
-            self.assertEquals(len(w), 0)
+            self.assertEqual(len(w), 0)
 
     def test_filterwarnings(self):
         # Test filterwarnings().
@@ -217,7 +217,7 @@
                 self.module.warn(ob)
                 # Don't directly compare objects since
                 # ``Warning() != Warning()``.
-                self.assertEquals(str(w[-1].message), str(UserWarning(ob)))
+                self.assertEqual(str(w[-1].message), str(UserWarning(ob)))
 
     def test_filename(self):
         with warnings_state(self.module):
@@ -448,7 +448,7 @@
                 self.assertEqual(w[-1].message, message)
                 del w[:]
                 self.module.warn_explicit(message, UserWarning, "file", 42)
-                self.assertEquals(len(w), 0)
+                self.assertEqual(len(w), 0)
                 # Test the resetting of onceregistry.
                 self.module.onceregistry = {}
                 __warningregistry__ = {}
@@ -459,7 +459,7 @@
                 del self.module.onceregistry
                 __warningregistry__ = {}
                 self.module.warn_explicit(message, UserWarning, "file", 42)
-                self.assertEquals(len(w), 0)
+                self.assertEqual(len(w), 0)
         finally:
             self.module.onceregistry = original_registry
 

Modified: python/branches/pep-3151/Lib/test/test_weakset.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_weakset.py	(original)
+++ python/branches/pep-3151/Lib/test/test_weakset.py	Sat Feb 26 08:16:32 2011
@@ -50,7 +50,8 @@
     def test_contains(self):
         for c in self.letters:
             self.assertEqual(c in self.s, c in self.d)
-        self.assertRaises(TypeError, self.s.__contains__, [[]])
+        # 1 is not weakref'able, but that TypeError is caught by __contains__
+        self.assertNotIn(1, self.s)
         self.assertIn(self.obj, self.fs)
         del self.obj
         self.assertNotIn(ustr('F'), self.fs)

Modified: python/branches/pep-3151/Lib/test/test_winreg.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_winreg.py	(original)
+++ python/branches/pep-3151/Lib/test/test_winreg.py	Sat Feb 26 08:16:32 2011
@@ -82,12 +82,12 @@
 
         # Check we wrote as many items as we thought.
         nkeys, nvalues, since_mod = QueryInfoKey(key)
-        self.assertEquals(nkeys, 1, "Not the correct number of sub keys")
-        self.assertEquals(nvalues, 1, "Not the correct number of values")
+        self.assertEqual(nkeys, 1, "Not the correct number of sub keys")
+        self.assertEqual(nvalues, 1, "Not the correct number of values")
         nkeys, nvalues, since_mod = QueryInfoKey(sub_key)
-        self.assertEquals(nkeys, 0, "Not the correct number of sub keys")
-        self.assertEquals(nvalues, len(test_data),
-                          "Not the correct number of values")
+        self.assertEqual(nkeys, 0, "Not the correct number of sub keys")
+        self.assertEqual(nvalues, len(test_data),
+                         "Not the correct number of values")
         # Close this key this way...
         # (but before we do, copy the key as an integer - this allows
         # us to test that the key really gets closed).
@@ -112,8 +112,8 @@
     def _read_test_data(self, root_key, subkeystr="sub_key", OpenKey=OpenKey):
         # Check we can get default value for this key.
         val = QueryValue(root_key, test_key_name)
-        self.assertEquals(val, "Default value",
-                          "Registry didn't give back the correct value")
+        self.assertEqual(val, "Default value",
+                         "Registry didn't give back the correct value")
 
         key = OpenKey(root_key, test_key_name)
         # Read the sub-keys
@@ -125,22 +125,22 @@
                     data = EnumValue(sub_key, index)
                 except EnvironmentError:
                     break
-                self.assertEquals(data in test_data, True,
-                                  "Didn't read back the correct test data")
+                self.assertEqual(data in test_data, True,
+                                 "Didn't read back the correct test data")
                 index = index + 1
-            self.assertEquals(index, len(test_data),
-                              "Didn't read the correct number of items")
+            self.assertEqual(index, len(test_data),
+                             "Didn't read the correct number of items")
             # Check I can directly access each item
             for value_name, value_data, value_type in test_data:
                 read_val, read_typ = QueryValueEx(sub_key, value_name)
-                self.assertEquals(read_val, value_data,
-                                  "Could not directly read the value")
-                self.assertEquals(read_typ, value_type,
-                                  "Could not directly read the value")
+                self.assertEqual(read_val, value_data,
+                                 "Could not directly read the value")
+                self.assertEqual(read_typ, value_type,
+                                 "Could not directly read the value")
         sub_key.Close()
         # Enumerate our main key.
         read_val = EnumKey(key, 0)
-        self.assertEquals(read_val, subkeystr, "Read subkey value wrong")
+        self.assertEqual(read_val, subkeystr, "Read subkey value wrong")
         try:
             EnumKey(key, 1)
             self.fail("Was able to get a second key when I only have one!")
@@ -159,8 +159,8 @@
             DeleteValue(sub_key, value_name)
 
         nkeys, nvalues, since_mod = QueryInfoKey(sub_key)
-        self.assertEquals(nkeys, 0, "subkey not empty before delete")
-        self.assertEquals(nvalues, 0, "subkey not empty before delete")
+        self.assertEqual(nkeys, 0, "subkey not empty before delete")
+        self.assertEqual(nvalues, 0, "subkey not empty before delete")
         sub_key.Close()
         DeleteKey(key, subkeystr)
 
@@ -341,8 +341,8 @@
         with OpenKey(HKEY_LOCAL_MACHINE, "Software") as key:
             # HKLM\Software is redirected but not reflected in all OSes
             self.assertTrue(QueryReflectionKey(key))
-            self.assertEquals(None, EnableReflectionKey(key))
-            self.assertEquals(None, DisableReflectionKey(key))
+            self.assertIsNone(EnableReflectionKey(key))
+            self.assertIsNone(DisableReflectionKey(key))
             self.assertTrue(QueryReflectionKey(key))
 
     @unittest.skipUnless(HAS_REFLECTION, "OS doesn't support reflection")

Modified: python/branches/pep-3151/Lib/test/test_winsound.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_winsound.py	(original)
+++ python/branches/pep-3151/Lib/test/test_winsound.py	Sat Feb 26 08:16:32 2011
@@ -249,6 +249,7 @@
         p = subprocess.Popen([cscript_path, check_script],
                              stdout=subprocess.PIPE)
         __have_soundcard_cache = not p.wait()
+        p.stdout.close()
     return __have_soundcard_cache
 
 

Modified: python/branches/pep-3151/Lib/test/test_with.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_with.py	(original)
+++ python/branches/pep-3151/Lib/test/test_with.py	Sat Feb 26 08:16:32 2011
@@ -9,26 +9,26 @@
 import sys
 import unittest
 from collections import deque
-from contextlib import GeneratorContextManager, contextmanager
+from contextlib import _GeneratorContextManager, contextmanager
 from test.support import run_unittest
 
 
-class MockContextManager(GeneratorContextManager):
+class MockContextManager(_GeneratorContextManager):
     def __init__(self, gen):
-        GeneratorContextManager.__init__(self, gen)
+        _GeneratorContextManager.__init__(self, gen)
         self.enter_called = False
         self.exit_called = False
         self.exit_args = None
 
     def __enter__(self):
         self.enter_called = True
-        return GeneratorContextManager.__enter__(self)
+        return _GeneratorContextManager.__enter__(self)
 
     def __exit__(self, type, value, traceback):
         self.exit_called = True
         self.exit_args = (type, value, traceback)
-        return GeneratorContextManager.__exit__(self, type,
-                                                value, traceback)
+        return _GeneratorContextManager.__exit__(self, type,
+                                                 value, traceback)
 
 
 def mock_contextmanager(func):
@@ -734,10 +734,10 @@
     def testEnterReturnsTuple(self):
         with self.Dummy(value=(1,2)) as (a1, a2), \
              self.Dummy(value=(10, 20)) as (b1, b2):
-            self.assertEquals(1, a1)
-            self.assertEquals(2, a2)
-            self.assertEquals(10, b1)
-            self.assertEquals(20, b2)
+            self.assertEqual(1, a1)
+            self.assertEqual(2, a2)
+            self.assertEqual(10, b1)
+            self.assertEqual(20, b2)
 
 def test_main():
     run_unittest(FailureTestCase, NonexceptionalTestCase,

Modified: python/branches/pep-3151/Lib/test/test_wsgiref.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_wsgiref.py	(original)
+++ python/branches/pep-3151/Lib/test/test_wsgiref.py	Sat Feb 26 08:16:32 2011
@@ -342,6 +342,10 @@
         self.checkReqURI("http://127.0.0.1/sp%C3%A4m", SCRIPT_NAME="/späm")
         self.checkReqURI("http://127.0.0.1/spammity/spam",
             SCRIPT_NAME="/spammity", PATH_INFO="/spam")
+        self.checkReqURI("http://127.0.0.1/spammity/spam;ham",
+            SCRIPT_NAME="/spammity", PATH_INFO="/spam;ham")
+        self.checkReqURI("http://127.0.0.1/spammity/spam;cookie=1234,5678",
+            SCRIPT_NAME="/spammity", PATH_INFO="/spam;cookie=1234,5678")
         self.checkReqURI("http://127.0.0.1/spammity/spam?say=ni",
             SCRIPT_NAME="/spammity", PATH_INFO="/spam",QUERY_STRING="say=ni")
         self.checkReqURI("http://127.0.0.1/spammity/spam", 0,
@@ -516,6 +520,11 @@
             s('200 OK',[])
             return ['\u0442\u0435\u0441\u0442'.encode("utf-8")]
 
+        def trivial_app4(e,s):
+            # Simulate a response to a HEAD request
+            s('200 OK',[('Content-Length', '12345')])
+            return []
+
         h = TestHandler()
         h.run(trivial_app1)
         self.assertEqual(h.stdout.getvalue(),
@@ -539,10 +548,12 @@
             b'\r\n'
             b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82')
 
-
-
-
-
+        h = TestHandler()
+        h.run(trivial_app4)
+        self.assertEqual(h.stdout.getvalue(),
+            b'Status: 200 OK\r\n'
+            b'Content-Length: 12345\r\n'
+            b'\r\n')
 
     def testBasicErrorOutput(self):
 

Modified: python/branches/pep-3151/Lib/test/test_xml_etree.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_xml_etree.py	(original)
+++ python/branches/pep-3151/Lib/test/test_xml_etree.py	Sat Feb 26 08:16:32 2011
@@ -22,7 +22,7 @@
 
 SIMPLE_XMLFILE = findfile("simple.xml", subdir="xmltestdata")
 try:
-    SIMPLE_XMLFILE.encode("utf8")
+    SIMPLE_XMLFILE.encode("utf-8")
 except UnicodeEncodeError:
     raise unittest.SkipTest("filename is not encodable to utf8")
 SIMPLE_NS_XMLFILE = findfile("simple-ns.xml", subdir="xmltestdata")
@@ -1255,8 +1255,8 @@
 
     >>> ET.tostring(ET.PI('test', '<testing&>'))
     b'<?test <testing&>?>'
-    >>> ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin1')
-    b"<?xml version='1.0' encoding='latin1'?>\\n<?test <testing&>\\xe3?>"
+    >>> ET.tostring(ET.PI('test', '<testing&>\xe3'), 'latin-1')
+    b"<?xml version='1.0' encoding='latin-1'?>\\n<?test <testing&>\\xe3?>"
     """
 
 #
@@ -1841,6 +1841,15 @@
 
     """
 
+def check_issue10777():
+    """
+    Registering a namespace twice caused a "dictionary changed size during
+    iteration" bug.
+
+    >>> ET.register_namespace('test10777', 'http://myuri/')
+    >>> ET.register_namespace('test10777', 'http://myuri/')
+    """
+
 # --------------------------------------------------------------------
 
 

Modified: python/branches/pep-3151/Lib/test/test_xml_etree_c.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_xml_etree_c.py	(original)
+++ python/branches/pep-3151/Lib/test/test_xml_etree_c.py	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,8 @@
 # xml.etree test for cElementTree
 
 from test import support
+from test.support import precisionbigmemtest, _2G
+import unittest
 
 cET = support.import_module('xml.etree.cElementTree')
 
@@ -8,19 +10,51 @@
 # cElementTree specific tests
 
 def sanity():
-    """
+    r"""
     Import sanity.
 
     >>> from xml.etree import cElementTree
+
+    Issue #6697.
+
+    >>> e = cElementTree.Element('a')
+    >>> getattr(e, '\uD800')           # doctest: +ELLIPSIS
+    Traceback (most recent call last):
+      ...
+    UnicodeEncodeError: ...
+
+    >>> p = cElementTree.XMLParser()
+    >>> p.version.split()[0]
+    'Expat'
+    >>> getattr(p, '\uD800')
+    Traceback (most recent call last):
+     ...
+    AttributeError: 'XMLParser' object has no attribute '\ud800'
     """
 
 
+class MiscTests(unittest.TestCase):
+    # Issue #8651.
+    @support.precisionbigmemtest(size=support._2G + 100, memuse=1)
+    def test_length_overflow(self, size):
+        if size < support._2G + 100:
+            self.skipTest("not enough free memory, need at least 2 GB")
+        data = b'x' * size
+        parser = cET.XMLParser()
+        try:
+            self.assertRaises(OverflowError, parser.feed, data)
+        finally:
+            data = None
+
+
 def test_main():
     from test import test_xml_etree, test_xml_etree_c
 
     # Run the tests specific to the C implementation
     support.run_doctest(test_xml_etree_c, verbosity=True)
 
+    support.run_unittest(MiscTests)
+
     # Assign the C implementation before running the doctests
     # Patch the __name__, to prevent confusion with the pure Python test
     pyET = test_xml_etree.ET

Modified: python/branches/pep-3151/Lib/test/test_xmlrpc.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_xmlrpc.py	(original)
+++ python/branches/pep-3151/Lib/test/test_xmlrpc.py	Sat Feb 26 08:16:32 2011
@@ -39,7 +39,7 @@
     def test_dump_load(self):
         dump = xmlrpclib.dumps((alist,))
         load = xmlrpclib.loads(dump)
-        self.assertEquals(alist, load[0][0])
+        self.assertEqual(alist, load[0][0])
 
     def test_dump_bare_datetime(self):
         # This checks that an unwrapped datetime.date object can be handled
@@ -49,22 +49,22 @@
         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)
-        self.assertEquals(m, None)
+        self.assertEqual(newdt, dt)
+        self.assertEqual(m, None)
 
         (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
-        self.assertEquals(newdt, xmlrpclib.DateTime('20050210T11:41:23'))
+        self.assertEqual(newdt, xmlrpclib.DateTime('20050210T11:41:23'))
 
     def test_datetime_before_1900(self):
         # same as before but with a date before 1900
         dt = datetime.datetime(1,  2, 10, 11, 41, 23)
         s = xmlrpclib.dumps((dt,))
         (newdt,), m = xmlrpclib.loads(s, use_datetime=1)
-        self.assertEquals(newdt, dt)
-        self.assertEquals(m, None)
+        self.assertEqual(newdt, dt)
+        self.assertEqual(m, None)
 
         (newdt,), m = xmlrpclib.loads(s, use_datetime=0)
-        self.assertEquals(newdt, xmlrpclib.DateTime('00010210T11:41:23'))
+        self.assertEqual(newdt, xmlrpclib.DateTime('00010210T11:41:23'))
 
     def test_cmp_datetime_DateTime(self):
         now = datetime.datetime.now()
@@ -92,7 +92,7 @@
         t.x = 100
         t.y = "Hello"
         ((t2,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((t,)))
-        self.assertEquals(t2, t.__dict__)
+        self.assertEqual(t2, t.__dict__)
 
     def test_dump_big_long(self):
         self.assertRaises(OverflowError, xmlrpclib.dumps, (2**99,))
@@ -138,18 +138,30 @@
         value = alist + [None]
         arg1 = (alist + [None],)
         strg = xmlrpclib.dumps(arg1, allow_none=True)
-        self.assertEquals(value,
+        self.assertEqual(value,
                           xmlrpclib.loads(strg)[0][0])
         self.assertRaises(TypeError, xmlrpclib.dumps, (arg1,))
 
     def test_get_host_info(self):
         # see bug #3613, this raised a TypeError
         transp = xmlrpc.client.Transport()
-        self.assertEquals(transp.get_host_info("user at host.tld"),
+        self.assertEqual(transp.get_host_info("user at host.tld"),
                           ('host.tld',
                            [('Authorization', 'Basic dXNlcg==')], {}))
 
-
+    def test_ssl_presence(self):
+        try:
+            import ssl
+        except ImportError:
+            has_ssl = False
+        else:
+            has_ssl = True
+        try:
+            xmlrpc.client.ServerProxy('https://localhost:9999').bad_function()
+        except NotImplementedError:
+            self.assertFalse(has_ssl, "xmlrpc client's error with SSL support")
+        except socket.error:
+            self.assertTrue(has_ssl)
 
 class HelperTestCase(unittest.TestCase):
     def test_escape(self):
@@ -167,8 +179,8 @@
         f = xmlrpclib.Fault(42, 'Test Fault')
         s = xmlrpclib.dumps((f,))
         (newf,), m = xmlrpclib.loads(s)
-        self.assertEquals(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
-        self.assertEquals(m, None)
+        self.assertEqual(newf, {'faultCode': 42, 'faultString': 'Test Fault'})
+        self.assertEqual(m, None)
 
         s = xmlrpclib.Marshaller().dumps(f)
         self.assertRaises(xmlrpclib.Fault, xmlrpclib.loads, s)
@@ -617,6 +629,7 @@
         self.assertEqual(p.pow(6,8), 6**8)
         self.assertEqual(p.pow(6,8), 6**8)
         self.assertEqual(p.pow(6,8), 6**8)
+        p("close")()
 
         #they should have all been handled by a single request handler
         self.assertEqual(len(self.RequestHandler.myRequests), 1)
@@ -625,6 +638,7 @@
         #due to thread scheduling)
         self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
 
+
 #test special attribute access on the serverproxy, through the __call__
 #function.
 class KeepaliveServerTestCase2(BaseKeepaliveServerTestCase):
@@ -641,6 +655,7 @@
         self.assertEqual(p.pow(6,8), 6**8)
         self.assertEqual(p.pow(6,8), 6**8)
         self.assertEqual(p.pow(6,8), 6**8)
+        p("close")()
 
         #they should have all been two request handlers, each having logged at least
         #two complete requests
@@ -648,12 +663,14 @@
         self.assertGreaterEqual(len(self.RequestHandler.myRequests[-1]), 2)
         self.assertGreaterEqual(len(self.RequestHandler.myRequests[-2]), 2)
 
+
     def test_transport(self):
         p = xmlrpclib.ServerProxy(URL)
         #do some requests with close.
         self.assertEqual(p.pow(6,8), 6**8)
         p("transport").close() #same as above, really.
         self.assertEqual(p.pow(6,8), 6**8)
+        p("close")()
         self.assertEqual(len(self.RequestHandler.myRequests), 2)
 
 #A test case that verifies that gzip encoding works in both directions
@@ -697,16 +714,18 @@
         self.assertEqual(p.pow(6,8), 6**8)
         b = self.RequestHandler.content_length
         self.assertTrue(a>b)
+        p("close")()
 
     def test_bad_gzip_request(self):
         t = self.Transport()
         t.encode_threshold = None
         t.fake_gzip = True
         p = xmlrpclib.ServerProxy(URL, transport=t)
-        cm = self.assertRaisesRegexp(xmlrpclib.ProtocolError,
-                                     re.compile(r"\b400\b"))
+        cm = self.assertRaisesRegex(xmlrpclib.ProtocolError,
+                                    re.compile(r"\b400\b"))
         with cm:
             p.pow(6, 8)
+        p("close")()
 
     def test_gsip_response(self):
         t = self.Transport()
@@ -717,6 +736,7 @@
         a = t.response_length
         self.requestHandler.encode_threshold = 0 #always encode
         self.assertEqual(p.pow(6,8), 6**8)
+        p("close")()
         b = t.response_length
         self.requestHandler.encode_threshold = old
         self.assertTrue(a>b)
@@ -906,7 +926,7 @@
 
         content = handle[handle.find("<?xml"):]
 
-        self.assertEquals(
+        self.assertEqual(
             int(re.search('Content-Length: (\d+)', handle).group(1)),
             len(content))
 

Modified: python/branches/pep-3151/Lib/test/test_xmlrpc_net.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_xmlrpc_net.py	(original)
+++ python/branches/pep-3151/Lib/test/test_xmlrpc_net.py	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
 #!/usr/bin/env python3
 
-import collections
+import collections.abc
 import errno
 import socket
 import sys
@@ -48,7 +48,7 @@
 
         # Perform a minimal sanity check on the result, just to be sure
         # the request means what we think it means.
-        self.assertIsInstance(builders, collections.Sequence)
+        self.assertIsInstance(builders, collections.abc.Sequence)
         self.assertTrue([x for x in builders if "3.x" in x], builders)
 
 

Modified: python/branches/pep-3151/Lib/test/test_zipfile.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_zipfile.py	(original)
+++ python/branches/pep-3151/Lib/test/test_zipfile.py	Sat Feb 26 08:16:32 2011
@@ -6,6 +6,7 @@
 
 import io
 import os
+import sys
 import imp
 import time
 import shutil
@@ -23,6 +24,7 @@
 TESTFN2 = TESTFN + "2"
 TESTFNDIR = TESTFN + "d"
 FIXEDTEST_SIZE = 1000
+DATAFILES_DIR = 'zipfile_datafiles'
 
 SMALL_TEST_DATA = [('_ziptest1', '1q2w3e4r5t'),
                    ('ziptest2dir/_ziptest2', 'qawsedrftg'),
@@ -112,20 +114,20 @@
         # Read the ZIP archive
         with zipfile.ZipFile(f, "r", compression) as zipfp:
             zipdata1 = []
-            zipopen1 = zipfp.open(TESTFN)
-            while True:
-                read_data = zipopen1.read(256)
-                if not read_data:
-                    break
-                zipdata1.append(read_data)
+            with zipfp.open(TESTFN) as zipopen1:
+                while True:
+                    read_data = zipopen1.read(256)
+                    if not read_data:
+                        break
+                    zipdata1.append(read_data)
 
             zipdata2 = []
-            zipopen2 = zipfp.open("another.name")
-            while True:
-                read_data = zipopen2.read(256)
-                if not read_data:
-                    break
-                zipdata2.append(read_data)
+            with zipfp.open("another.name") as zipopen2:
+                while True:
+                    read_data = zipopen2.read(256)
+                    if not read_data:
+                        break
+                    zipdata2.append(read_data)
 
             self.assertEqual(b''.join(zipdata1), self.data)
             self.assertEqual(b''.join(zipdata2), self.data)
@@ -146,7 +148,8 @@
             infos = zipfp.infolist()
             data = b""
             for info in infos:
-                data += zipfp.open(info).read()
+                with zipfp.open(info) as zipopen:
+                    data += zipopen.read()
             self.assertTrue(data == b"foobar" or data == b"barfoo")
             data = b""
             for info in infos:
@@ -159,12 +162,12 @@
         # Read the ZIP archive
         with zipfile.ZipFile(f, "r", compression) as zipfp:
             zipdata1 = []
-            zipopen1 = zipfp.open(TESTFN)
-            while True:
-                read_data = zipopen1.read(randint(1, 1024))
-                if not read_data:
-                    break
-                zipdata1.append(read_data)
+            with zipfp.open(TESTFN) as zipopen1:
+                while True:
+                    read_data = zipopen1.read(randint(1, 1024))
+                    if not read_data:
+                        break
+                    zipdata1.append(read_data)
 
             self.assertEqual(b''.join(zipdata1), self.data)
         if not isinstance(f, str):
@@ -184,9 +187,9 @@
 
         data2 = b''
         zipfp = zipfile.ZipFile(f, 'r')
-        zipopen = zipfp.open(TESTFN, 'rU')
-        for line in zipopen:
-            data2 += line
+        with zipfp.open(TESTFN, 'rU') as zipopen:
+            for line in zipopen:
+                data2 += line
         zipfp.close()
 
         self.assertEqual(data, data2.replace(b'\n', b'\r\n'))
@@ -196,19 +199,18 @@
 
         # Read the ZIP archive
         zipfp = zipfile.ZipFile(f, "r")
-        zipopen = zipfp.open(TESTFN)
+        with zipfp.open(TESTFN) as zipopen:
+            data = b''
+            while True:
+                read = zipopen.readline()
+                if not read:
+                    break
+                data += read
 
-        data = b''
-        while True:
-            read = zipopen.readline()
-            if not read:
-                break
-            data += read
-
-            read = zipopen.read(100)
-            if not read:
-                break
-            data += read
+                read = zipopen.read(100)
+                if not read:
+                    break
+                data += read
 
         self.assertEqual(data, self.data)
         zipfp.close()
@@ -220,10 +222,10 @@
 
         # Read the ZIP archive
         with zipfile.ZipFile(f, "r") as zipfp:
-            zipopen = zipfp.open(TESTFN)
-            for line in self.line_gen:
-                linedata = zipopen.readline()
-                self.assertEqual(linedata, line + '\n')
+            with zipfp.open(TESTFN) as zipopen:
+                for line in self.line_gen:
+                    linedata = zipopen.readline()
+                    self.assertEqual(linedata, line + '\n')
         if not isinstance(f, str):
             f.close()
 
@@ -232,7 +234,8 @@
 
         # Read the ZIP archive
         with zipfile.ZipFile(f, "r") as zipfp:
-            ziplines = zipfp.open(TESTFN).readlines()
+            with zipfp.open(TESTFN) as zipopen:
+                ziplines = zipopen.readlines()
             for line, zipline in zip(self.line_gen, ziplines):
                 self.assertEqual(zipline, line + '\n')
         if not isinstance(f, str):
@@ -243,8 +246,9 @@
 
         # Read the ZIP archive
         with zipfile.ZipFile(f, "r") as zipfp:
-            for line, zipline in zip(self.line_gen, zipfp.open(TESTFN)):
-                self.assertEqual(zipline, line + '\n')
+            with zipfp.open(TESTFN) as zipopen:
+                for line, zipline in zip(self.line_gen, zipopen):
+                    self.assertEqual(zipline, line + '\n')
         if not isinstance(f, str):
             f.close()
 
@@ -311,9 +315,9 @@
 
         # Get an open object for strfile
         with zipfile.ZipFile(TESTFN2, "r", zipfile.ZIP_DEFLATED) as zipfp:
-            openobj = zipfp.open("strfile")
-            self.assertEqual(openobj.read(1), b'1')
-            self.assertEqual(openobj.read(1), b'2')
+            with zipfp.open("strfile") as openobj:
+                self.assertEqual(openobj.read(1), b'1')
+                self.assertEqual(openobj.read(1), b'2')
 
     def test_absolute_arcnames(self):
         with zipfile.ZipFile(TESTFN2, "w", zipfile.ZIP_STORED) as zipfp:
@@ -352,7 +356,8 @@
         produces the expected result."""
         with zipfile.ZipFile(TESTFN2, "w") as zipfp:
             zipfp.write(TESTFN)
-            self.assertEqual(zipfp.read(TESTFN), open(TESTFN, "rb").read())
+            with open(TESTFN, "rb") as f:
+                self.assertEqual(zipfp.read(TESTFN), f.read())
 
     @skipUnless(zlib, "requires zlib")
     def test_per_file_compression(self):
@@ -394,7 +399,8 @@
                 self.assertEqual(writtenfile, correctfile)
 
                 # make sure correct data is in correct file
-                self.assertEqual(fdata.encode(), open(writtenfile, "rb").read())
+                with open(writtenfile, "rb") as f:
+                    self.assertEqual(fdata.encode(), f.read())
 
                 os.remove(writtenfile)
 
@@ -414,7 +420,8 @@
                 else:
                     outfile = os.path.join(os.getcwd(), fpath)
 
-                self.assertEqual(fdata.encode(), open(outfile, "rb").read())
+                with open(outfile, "rb") as f:
+                    self.assertEqual(fdata.encode(), f.read())
 
                 os.remove(outfile)
 
@@ -482,6 +489,13 @@
         except zipfile.BadZipFile:
             self.assertTrue(zipfp2.fp is None, 'zipfp is not closed')
 
+    def test_unicode_filenames(self):
+        # bug #10801
+        fname = findfile('zip_cp437_header.zip')
+        with zipfile.ZipFile(fname) as zipfp:
+            for name in zipfp.namelist():
+                zipfp.open(name).close()
+
     def tearDown(self):
         unlink(TESTFN)
         unlink(TESTFN2)
@@ -604,7 +618,7 @@
 
 class PyZipFileTests(unittest.TestCase):
     def test_write_pyfile(self):
-        with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
+        with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
             fn = __file__
             if fn.endswith('.pyc') or fn.endswith('.pyo'):
                 path_split = fn.split(os.sep)
@@ -622,7 +636,7 @@
             self.assertTrue(bn + 'o' in zipfp.namelist() or
                             bn + 'c' in zipfp.namelist())
 
-        with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
+        with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
             fn = __file__
             if fn.endswith(('.pyc', '.pyo')):
                 fn = fn[:-1]
@@ -638,7 +652,7 @@
         import email
         packagedir = os.path.dirname(email.__file__)
 
-        with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
+        with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
             zipfp.writepy(packagedir)
 
             # Check for a couple of modules at different levels of the
@@ -649,6 +663,22 @@
             self.assertTrue('email/mime/text.pyo' in names or
                             'email/mime/text.pyc' in names)
 
+    def test_write_with_optimization(self):
+        import email
+        packagedir = os.path.dirname(email.__file__)
+        # use .pyc if running test in optimization mode,
+        # use .pyo if running test in debug mode
+        optlevel = 1 if __debug__ else 0
+        ext = '.pyo' if optlevel == 1 else '.pyc'
+
+        with TemporaryFile() as t, \
+                 zipfile.PyZipFile(t, "w", optimize=optlevel) as zipfp:
+            zipfp.writepy(packagedir)
+
+            names = zipfp.namelist()
+            self.assertIn('email/__init__' + ext, names)
+            self.assertIn('email/mime/text' + ext, names)
+
     def test_write_python_directory(self):
         os.mkdir(TESTFN2)
         try:
@@ -661,25 +691,25 @@
             with open(os.path.join(TESTFN2, "mod2.txt"), "w") as fp:
                 fp.write("bla bla bla\n")
 
-            zipfp  = zipfile.PyZipFile(TemporaryFile(), "w")
-            zipfp.writepy(TESTFN2)
+            with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
+                zipfp.writepy(TESTFN2)
 
-            names = zipfp.namelist()
-            self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
-            self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
-            self.assertNotIn('mod2.txt', names)
+                names = zipfp.namelist()
+                self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
+                self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
+                self.assertNotIn('mod2.txt', names)
 
         finally:
             shutil.rmtree(TESTFN2)
 
     def test_write_non_pyfile(self):
-        with zipfile.PyZipFile(TemporaryFile(), "w") as zipfp:
-            open(TESTFN, 'w').write('most definitely not a python file')
+        with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp:
+            with open(TESTFN, 'w') as f:
+                f.write('most definitely not a python file')
             self.assertRaises(RuntimeError, zipfp.writepy, TESTFN)
             os.remove(TESTFN)
 
 
-
 class OtherTests(unittest.TestCase):
     zips_with_bad_crc = {
         zipfile.ZIP_STORED: (
@@ -825,7 +855,8 @@
         self.assertRaises(RuntimeError, zipf.open, "foo.txt")
         self.assertRaises(RuntimeError, zipf.testzip)
         self.assertRaises(RuntimeError, zipf.writestr, "bogus.txt", "bogus")
-        open(TESTFN, 'w').write('zipfile test data')
+        with open(TESTFN, 'w') as f:
+            f.write('zipfile test data')
         self.assertRaises(RuntimeError, zipf.write, TESTFN)
 
     def test_bad_constructor_mode(self):
@@ -848,11 +879,11 @@
         with zipfile.ZipFile(TESTFN, mode="w") as zipf:
             zipf.writestr("foo.txt", "O, for a Muse of Fire!")
             # read the data to make sure the file is there
-            f = zipf.open("foo.txt")
-            for i in range(FIXEDTEST_SIZE):
-                self.assertEqual(f.read(0), b'')
+            with zipf.open("foo.txt") as f:
+                for i in range(FIXEDTEST_SIZE):
+                    self.assertEqual(f.read(0), b'')
 
-            self.assertEqual(f.read(), b"O, for a Muse of Fire!")
+                self.assertEqual(f.read(), b"O, for a Muse of Fire!")
 
     def test_open_non_existent_item(self):
         """Check that attempting to call open() for an item that doesn't
@@ -1067,6 +1098,12 @@
         self.zip2.setpassword(b"12345")
         self.assertEqual(self.zip2.read("zero"), self.plain2)
 
+    def test_unicode_password(self):
+        self.assertRaises(TypeError, self.zip.setpassword, "unicode")
+        self.assertRaises(TypeError, self.zip.read, "test.txt", "python")
+        self.assertRaises(TypeError, self.zip.open, "test.txt", pwd="python")
+        self.assertRaises(TypeError, self.zip.extract, "test.txt", pwd="python")
+
 
 class TestsWithRandomBinaryFiles(unittest.TestCase):
     def setUp(self):
@@ -1115,20 +1152,20 @@
         # Read the ZIP archive
         with zipfile.ZipFile(f, "r", compression) as zipfp:
             zipdata1 = []
-            zipopen1 = zipfp.open(TESTFN)
-            while True:
-                read_data = zipopen1.read(256)
-                if not read_data:
-                    break
-                zipdata1.append(read_data)
+            with zipfp.open(TESTFN) as zipopen1:
+                while True:
+                    read_data = zipopen1.read(256)
+                    if not read_data:
+                        break
+                    zipdata1.append(read_data)
 
             zipdata2 = []
-            zipopen2 = zipfp.open("another.name")
-            while True:
-                read_data = zipopen2.read(256)
-                if not read_data:
-                    break
-                zipdata2.append(read_data)
+            with zipfp.open("another.name") as zipopen2:
+                while True:
+                    read_data = zipopen2.read(256)
+                    if not read_data:
+                        break
+                    zipdata2.append(read_data)
 
             testdata1 = b''.join(zipdata1)
             self.assertEqual(len(testdata1), len(self.data))
@@ -1155,12 +1192,12 @@
         # Read the ZIP archive
         with zipfile.ZipFile(f, "r", compression) as zipfp:
             zipdata1 = []
-            zipopen1 = zipfp.open(TESTFN)
-            while True:
-                read_data = zipopen1.read(randint(1, 1024))
-                if not read_data:
-                    break
-                zipdata1.append(read_data)
+            with zipfp.open(TESTFN) as zipopen1:
+                while True:
+                    read_data = zipopen1.read(randint(1, 1024))
+                    if not read_data:
+                        break
+                    zipdata1.append(read_data)
 
             testdata = b''.join(zipdata1)
             self.assertEqual(len(testdata), len(self.data))
@@ -1190,24 +1227,22 @@
         # Verify that (when the ZipFile is in control of creating file objects)
         # multiple open() calls can be made without interfering with each other.
         with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
-            zopen1 = zipf.open('ones')
-            zopen2 = zipf.open('ones')
-            data1 = zopen1.read(500)
-            data2 = zopen2.read(500)
-            data1 += zopen1.read(500)
-            data2 += zopen2.read(500)
+            with zipf.open('ones') as zopen1, zipf.open('ones') as zopen2:
+                data1 = zopen1.read(500)
+                data2 = zopen2.read(500)
+                data1 += zopen1.read(500)
+                data2 += zopen2.read(500)
             self.assertEqual(data1, data2)
 
     def test_different_file(self):
         # Verify that (when the ZipFile is in control of creating file objects)
         # multiple open() calls can be made without interfering with each other.
         with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
-            zopen1 = zipf.open('ones')
-            zopen2 = zipf.open('twos')
-            data1 = zopen1.read(500)
-            data2 = zopen2.read(500)
-            data1 += zopen1.read(500)
-            data2 += zopen2.read(500)
+            with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
+                data1 = zopen1.read(500)
+                data2 = zopen2.read(500)
+                data1 += zopen1.read(500)
+                data2 += zopen2.read(500)
             self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
             self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
 
@@ -1215,12 +1250,11 @@
         # Verify that (when the ZipFile is in control of creating file objects)
         # multiple open() calls can be made without interfering with each other.
         with zipfile.ZipFile(TESTFN2, mode="r") as zipf:
-            zopen1 = zipf.open('ones')
-            data1 = zopen1.read(500)
-            zopen2 = zipf.open('twos')
-            data2 = zopen2.read(500)
-            data1 += zopen1.read(500)
-            data2 += zopen2.read(500)
+            with zipf.open('ones') as zopen1, zipf.open('twos') as zopen2:
+                data1 = zopen1.read(500)
+                data2 = zopen2.read(500)
+                data1 += zopen1.read(500)
+                data2 += zopen2.read(500)
             self.assertEqual(data1, b'1'*FIXEDTEST_SIZE)
             self.assertEqual(data2, b'2'*FIXEDTEST_SIZE)
 
@@ -1294,25 +1328,23 @@
         self.make_test_archive(f, compression)
 
         # Read the ZIP archive
-        zipfp = zipfile.ZipFile(f, "r")
-        for sep, fn in self.arcfiles.items():
-            zipopen = zipfp.open(fn, "rU")
-            data = b''
-            while True:
-                read = zipopen.readline()
-                if not read:
-                    break
-                data += read
-
-                read = zipopen.read(5)
-                if not read:
-                    break
-                data += read
+        with zipfile.ZipFile(f, "r") as zipfp:
+            for sep, fn in self.arcfiles.items():
+                with zipfp.open(fn, "rU") as zipopen:
+                    data = b''
+                    while True:
+                        read = zipopen.readline()
+                        if not read:
+                            break
+                        data += read
+
+                        read = zipopen.read(5)
+                        if not read:
+                            break
+                        data += read
 
-            zipopen.close()
             self.assertEqual(data, self.arcdata['\n'])
 
-        zipfp.close()
         if not isinstance(f, str):
             f.close()
 

Modified: python/branches/pep-3151/Lib/test/test_zipimport.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_zipimport.py	(original)
+++ python/branches/pep-3151/Lib/test/test_zipimport.py	Sat Feb 26 08:16:32 2011
@@ -97,8 +97,8 @@
 
             if expected_ext:
                 file = mod.get_file()
-                self.assertEquals(file, os.path.join(TEMP_ZIP,
-                                  *modules) + expected_ext)
+                self.assertEqual(file, os.path.join(TEMP_ZIP,
+                                 *modules) + expected_ext)
         finally:
             z.close()
             os.remove(TEMP_ZIP)
@@ -211,32 +211,32 @@
             z.close()
 
             zi = zipimport.zipimporter(TEMP_ZIP)
-            self.assertEquals(zi.archive, TEMP_ZIP)
-            self.assertEquals(zi.is_package(TESTPACK), True)
+            self.assertEqual(zi.archive, TEMP_ZIP)
+            self.assertEqual(zi.is_package(TESTPACK), True)
             mod = zi.load_module(TESTPACK)
-            self.assertEquals(zi.get_filename(TESTPACK), mod.__file__)
+            self.assertEqual(zi.get_filename(TESTPACK), mod.__file__)
 
-            self.assertEquals(zi.is_package(packdir + '__init__'), False)
-            self.assertEquals(zi.is_package(packdir + TESTPACK2), True)
-            self.assertEquals(zi.is_package(packdir2 + TESTMOD), False)
+            self.assertEqual(zi.is_package(packdir + '__init__'), False)
+            self.assertEqual(zi.is_package(packdir + TESTPACK2), True)
+            self.assertEqual(zi.is_package(packdir2 + TESTMOD), False)
 
             mod_path = packdir2 + TESTMOD
             mod_name = module_path_to_dotted_name(mod_path)
             __import__(mod_name)
             mod = sys.modules[mod_name]
-            self.assertEquals(zi.get_source(TESTPACK), None)
-            self.assertEquals(zi.get_source(mod_path), None)
-            self.assertEquals(zi.get_filename(mod_path), mod.__file__)
+            self.assertEqual(zi.get_source(TESTPACK), None)
+            self.assertEqual(zi.get_source(mod_path), None)
+            self.assertEqual(zi.get_filename(mod_path), mod.__file__)
             # To pass in the module name instead of the path, we must use the
             # right importer
             loader = mod.__loader__
-            self.assertEquals(loader.get_source(mod_name), None)
-            self.assertEquals(loader.get_filename(mod_name), mod.__file__)
+            self.assertEqual(loader.get_source(mod_name), None)
+            self.assertEqual(loader.get_filename(mod_name), mod.__file__)
 
             # test prefix and archivepath members
             zi2 = zipimport.zipimporter(TEMP_ZIP + os.sep + TESTPACK)
-            self.assertEquals(zi2.archive, TEMP_ZIP)
-            self.assertEquals(zi2.prefix, TESTPACK + os.sep)
+            self.assertEqual(zi2.archive, TEMP_ZIP)
+            self.assertEqual(zi2.prefix, TESTPACK + os.sep)
         finally:
             z.close()
             os.remove(TEMP_ZIP)
@@ -256,29 +256,29 @@
             z.close()
 
             zi = zipimport.zipimporter(TEMP_ZIP + os.sep + packdir)
-            self.assertEquals(zi.archive, TEMP_ZIP)
-            self.assertEquals(zi.prefix, packdir)
-            self.assertEquals(zi.is_package(TESTPACK2), True)
+            self.assertEqual(zi.archive, TEMP_ZIP)
+            self.assertEqual(zi.prefix, packdir)
+            self.assertEqual(zi.is_package(TESTPACK2), True)
             mod = zi.load_module(TESTPACK2)
-            self.assertEquals(zi.get_filename(TESTPACK2), mod.__file__)
+            self.assertEqual(zi.get_filename(TESTPACK2), mod.__file__)
 
-            self.assertEquals(
+            self.assertEqual(
                 zi.is_package(TESTPACK2 + os.sep + '__init__'), False)
-            self.assertEquals(
+            self.assertEqual(
                 zi.is_package(TESTPACK2 + os.sep + TESTMOD), False)
 
             mod_path = TESTPACK2 + os.sep + TESTMOD
             mod_name = module_path_to_dotted_name(mod_path)
             __import__(mod_name)
             mod = sys.modules[mod_name]
-            self.assertEquals(zi.get_source(TESTPACK2), None)
-            self.assertEquals(zi.get_source(mod_path), None)
-            self.assertEquals(zi.get_filename(mod_path), mod.__file__)
+            self.assertEqual(zi.get_source(TESTPACK2), None)
+            self.assertEqual(zi.get_source(mod_path), None)
+            self.assertEqual(zi.get_filename(mod_path), mod.__file__)
             # To pass in the module name instead of the path, we must use the
             # right importer
             loader = mod.__loader__
-            self.assertEquals(loader.get_source(mod_name), None)
-            self.assertEquals(loader.get_filename(mod_name), mod.__file__)
+            self.assertEqual(loader.get_source(mod_name), None)
+            self.assertEqual(loader.get_filename(mod_name), mod.__file__)
         finally:
             z.close()
             os.remove(TEMP_ZIP)
@@ -292,7 +292,7 @@
             z.writestr(name, data)
             z.close()
             zi = zipimport.zipimporter(TEMP_ZIP)
-            self.assertEquals(data, zi.get_data(name))
+            self.assertEqual(data, zi.get_data(name))
             self.assertIn('zipimporter object', repr(zi))
         finally:
             z.close()

Modified: python/branches/pep-3151/Lib/test/test_zipimport_support.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_zipimport_support.py	(original)
+++ python/branches/pep-3151/Lib/test/test_zipimport_support.py	Sat Feb 26 08:16:32 2011
@@ -13,6 +13,7 @@
 import inspect
 import linecache
 import pdb
+import unittest
 from test.script_helper import (spawn_python, kill_python, assert_python_ok,
                                 temp_dir, make_script, make_zip_script)
 
@@ -29,7 +30,6 @@
 
 # Retrieve some helpers from other test cases
 from test import test_doctest, sample_doctest
-from test.test_importhooks import ImportHooksBaseTestCase
 
 
 def _run_object_doctest(obj, module):
@@ -59,17 +59,28 @@
 
 
 
-class ZipSupportTests(ImportHooksBaseTestCase):
-    # We use the ImportHooksBaseTestCase to restore
+class ZipSupportTests(unittest.TestCase):
+    # This used to use the ImportHooksBaseTestCase to restore
     # the state of the import related information
-    # in the sys module after each test
+    # in the sys module after each test. However, that restores
+    # *too much* information and breaks for the invocation of
+    # of test_doctest. So we do our own thing and leave
+    # sys.modules alone.
     # We also clear the linecache and zipimport cache
     # just to avoid any bogus errors due to name reuse in the tests
     def setUp(self):
         linecache.clearcache()
         zipimport._zip_directory_cache.clear()
-        ImportHooksBaseTestCase.setUp(self)
-
+        self.path = sys.path[:]
+        self.meta_path = sys.meta_path[:]
+        self.path_hooks = sys.path_hooks[:]
+        sys.path_importer_cache.clear()
+
+    def tearDown(self):
+        sys.path[:] = self.path
+        sys.meta_path[:] = self.meta_path
+        sys.path_hooks[:] = self.path_hooks
+        sys.path_importer_cache.clear()
 
     def test_inspect_getsource_issue4223(self):
         test_src = "def foo(): pass\n"
@@ -82,7 +93,10 @@
             os.remove(init_name)
             sys.path.insert(0, zip_name)
             import zip_pkg
-            self.assertEqual(inspect.getsource(zip_pkg.foo), test_src)
+            try:
+                self.assertEqual(inspect.getsource(zip_pkg.foo), test_src)
+            finally:
+                del sys.modules["zip_pkg"]
 
     def test_doctest_issue4197(self):
         # To avoid having to keep two copies of the doctest module's
@@ -117,53 +131,60 @@
             os.remove(script_name)
             sys.path.insert(0, zip_name)
             import test_zipped_doctest
-            # Some of the doc tests depend on the colocated text files
-            # which aren't available to the zipped version (the doctest
-            # module currently requires real filenames for non-embedded
-            # tests). So we're forced to be selective about which tests
-            # to run.
-            # doctest could really use some APIs which take a text
-            # string or a file object instead of a filename...
-            known_good_tests = [
-                test_zipped_doctest.SampleClass,
-                test_zipped_doctest.SampleClass.NestedClass,
-                test_zipped_doctest.SampleClass.NestedClass.__init__,
-                test_zipped_doctest.SampleClass.__init__,
-                test_zipped_doctest.SampleClass.a_classmethod,
-                test_zipped_doctest.SampleClass.a_property,
-                test_zipped_doctest.SampleClass.a_staticmethod,
-                test_zipped_doctest.SampleClass.double,
-                test_zipped_doctest.SampleClass.get,
-                test_zipped_doctest.SampleNewStyleClass,
-                test_zipped_doctest.SampleNewStyleClass.__init__,
-                test_zipped_doctest.SampleNewStyleClass.double,
-                test_zipped_doctest.SampleNewStyleClass.get,
-                test_zipped_doctest.sample_func,
-                test_zipped_doctest.test_DocTest,
-                test_zipped_doctest.test_DocTestParser,
-                test_zipped_doctest.test_DocTestRunner.basics,
-                test_zipped_doctest.test_DocTestRunner.exceptions,
-                test_zipped_doctest.test_DocTestRunner.option_directives,
-                test_zipped_doctest.test_DocTestRunner.optionflags,
-                test_zipped_doctest.test_DocTestRunner.verbose_flag,
-                test_zipped_doctest.test_Example,
-                test_zipped_doctest.test_debug,
-                test_zipped_doctest.test_pdb_set_trace,
-                test_zipped_doctest.test_pdb_set_trace_nested,
-                test_zipped_doctest.test_testsource,
-                test_zipped_doctest.test_trailing_space_in_test,
-                test_zipped_doctest.test_DocTestSuite,
-                test_zipped_doctest.test_DocTestFinder,
-            ]
-            # These remaining tests are the ones which need access
-            # to the data files, so we don't run them
-            fail_due_to_missing_data_files = [
-                test_zipped_doctest.test_DocFileSuite,
-                test_zipped_doctest.test_testfile,
-                test_zipped_doctest.test_unittest_reportflags,
-            ]
-            for obj in known_good_tests:
-                _run_object_doctest(obj, test_zipped_doctest)
+            try:
+                # Some of the doc tests depend on the colocated text files
+                # which aren't available to the zipped version (the doctest
+                # module currently requires real filenames for non-embedded
+                # tests). So we're forced to be selective about which tests
+                # to run.
+                # doctest could really use some APIs which take a text
+                # string or a file object instead of a filename...
+                known_good_tests = [
+                    test_zipped_doctest.SampleClass,
+                    test_zipped_doctest.SampleClass.NestedClass,
+                    test_zipped_doctest.SampleClass.NestedClass.__init__,
+                    test_zipped_doctest.SampleClass.__init__,
+                    test_zipped_doctest.SampleClass.a_classmethod,
+                    test_zipped_doctest.SampleClass.a_property,
+                    test_zipped_doctest.SampleClass.a_staticmethod,
+                    test_zipped_doctest.SampleClass.double,
+                    test_zipped_doctest.SampleClass.get,
+                    test_zipped_doctest.SampleNewStyleClass,
+                    test_zipped_doctest.SampleNewStyleClass.__init__,
+                    test_zipped_doctest.SampleNewStyleClass.double,
+                    test_zipped_doctest.SampleNewStyleClass.get,
+                    test_zipped_doctest.sample_func,
+                    test_zipped_doctest.test_DocTest,
+                    test_zipped_doctest.test_DocTestParser,
+                    test_zipped_doctest.test_DocTestRunner.basics,
+                    test_zipped_doctest.test_DocTestRunner.exceptions,
+                    test_zipped_doctest.test_DocTestRunner.option_directives,
+                    test_zipped_doctest.test_DocTestRunner.optionflags,
+                    test_zipped_doctest.test_DocTestRunner.verbose_flag,
+                    test_zipped_doctest.test_Example,
+                    test_zipped_doctest.test_debug,
+                    test_zipped_doctest.test_testsource,
+                    test_zipped_doctest.test_trailing_space_in_test,
+                    test_zipped_doctest.test_DocTestSuite,
+                    test_zipped_doctest.test_DocTestFinder,
+                ]
+                # These tests are the ones which need access
+                # to the data files, so we don't run them
+                fail_due_to_missing_data_files = [
+                    test_zipped_doctest.test_DocFileSuite,
+                    test_zipped_doctest.test_testfile,
+                    test_zipped_doctest.test_unittest_reportflags,
+                ]
+                # These tests are skipped when a trace funciton is set
+                can_fail_due_to_tracing = [
+                    test_zipped_doctest.test_pdb_set_trace,
+                    test_zipped_doctest.test_pdb_set_trace_nested,
+                ]
+
+                for obj in known_good_tests:
+                    _run_object_doctest(obj, test_zipped_doctest)
+            finally:
+                del sys.modules["test_zipped_doctest"]
 
     def test_doctest_main_issue4197(self):
         test_src = textwrap.dedent("""\
@@ -200,7 +221,7 @@
                         pass
 
                     import pdb
-                    pdb.runcall(f)
+                    pdb.Pdb(nosigint=True).runcall(f)
                     """)
         with temp_dir() as d:
             script_name = make_script(d, 'script', test_src)

Modified: python/branches/pep-3151/Lib/test/test_zlib.py
==============================================================================
--- python/branches/pep-3151/Lib/test/test_zlib.py	(original)
+++ python/branches/pep-3151/Lib/test/test_zlib.py	Sat Feb 26 08:16:32 2011
@@ -2,10 +2,16 @@
 from test import support
 import binascii
 import random
-from test.support import precisionbigmemtest, _1G
+import sys
+from test.support import precisionbigmemtest, _1G, _4G
 
 zlib = support.import_module('zlib')
 
+try:
+    import mmap
+except ImportError:
+    mmap = None
+
 
 class ChecksumTestCase(unittest.TestCase):
     # checksum test cases
@@ -57,6 +63,28 @@
         self.assertEqual(binascii.crc32(b'spam'), zlib.crc32(b'spam'))
 
 
+# Issue #10276 - check that inputs >=4GB are handled correctly.
+class ChecksumBigBufferTestCase(unittest.TestCase):
+
+    def setUp(self):
+        with open(support.TESTFN, "wb+") as f:
+            f.seek(_4G)
+            f.write(b"asdf")
+        with open(support.TESTFN, "rb") as f:
+            self.mapping = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
+
+    def tearDown(self):
+        self.mapping.close()
+        support.unlink(support.TESTFN)
+
+    @unittest.skipUnless(mmap, "mmap() is not available.")
+    @unittest.skipUnless(sys.maxsize > _4G, "Can't run on a 32-bit system.")
+    @unittest.skipUnless(support.is_resource_enabled("largefile"),
+                         "May use lots of disk space.")
+    def test_big_buffer(self):
+        self.assertEqual(zlib.crc32(self.mapping), 3058686908)
+        self.assertEqual(zlib.adler32(self.mapping), 82837919)
+
 
 class ExceptionTestCase(unittest.TestCase):
     # make sure we generate some expected errors
@@ -143,7 +171,7 @@
     def test_incomplete_stream(self):
         # An useful error message is given
         x = zlib.compress(HAMLET_SCENE)
-        self.assertRaisesRegexp(zlib.error,
+        self.assertRaisesRegex(zlib.error,
             "Error -5 while decompressing data: incomplete or truncated stream",
             zlib.decompress, x[:-1])
 
@@ -158,6 +186,16 @@
     def test_big_decompress_buffer(self, size):
         self.check_big_decompress_buffer(size, zlib.decompress)
 
+    @precisionbigmemtest(size=_4G + 100, memuse=1)
+    def test_length_overflow(self, size):
+        if size < _4G + 100:
+            self.skipTest("not enough free memory, need at least 4 GB")
+        data = b'x' * size
+        try:
+            self.assertRaises(OverflowError, zlib.compress, data, 1)
+        finally:
+            data = None
+
 
 class CompressObjectTestCase(BaseCompressTestCase, unittest.TestCase):
     # Test compression object
@@ -567,6 +605,7 @@
 def test_main():
     support.run_unittest(
         ChecksumTestCase,
+        ChecksumBigBufferTestCase,
         ExceptionTestCase,
         CompressTestCase,
         CompressObjectTestCase

Modified: python/branches/pep-3151/Lib/test/win_console_handler.py
==============================================================================
--- python/branches/pep-3151/Lib/test/win_console_handler.py	(original)
+++ python/branches/pep-3151/Lib/test/win_console_handler.py	Sat Feb 26 08:16:32 2011
@@ -40,7 +40,7 @@
         print("Unable to add SetConsoleCtrlHandler")
         exit(-1)
 
-    # Awaken mail process
+    # Awake main process
     m = mmap.mmap(-1, 1, sys.argv[1])
     m[0] = 1
 

Modified: python/branches/pep-3151/Lib/threading.py
==============================================================================
--- python/branches/pep-3151/Lib/threading.py	(original)
+++ python/branches/pep-3151/Lib/threading.py	Sat Feb 26 08:16:32 2011
@@ -17,12 +17,11 @@
 # with the multiprocessing module, which doesn't provide the old
 # Java inspired names.
 
-
-# Rename some stuff so "from threading import *" is safe
 __all__ = ['active_count', 'Condition', 'current_thread', 'enumerate', 'Event',
-           'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
+           'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread', 'Barrier',
            'Timer', 'setprofile', 'settrace', 'local', 'stack_size']
 
+# Rename some stuff so "from threading import *" is safe
 _start_new_thread = _thread.start_new_thread
 _allocate_lock = _thread.allocate_lock
 _get_ident = _thread.get_ident
@@ -36,10 +35,6 @@
 
 
 # Debug support (adapted from ihooks.py).
-# All the major classes here derive from _Verbose.  We force that to
-# be a new-style class so that all the major classes here are new-style.
-# This helps debugging (type(instance) is more revealing for instances
-# of new-style classes).
 
 _VERBOSE = False
 
@@ -55,8 +50,14 @@
         def _note(self, format, *args):
             if self._verbose:
                 format = format % args
-                format = "%s: %s\n" % (
-                    current_thread().name, format)
+                # Issue #4188: calling current_thread() can incur an infinite
+                # recursion if it has to create a DummyThread on the fly.
+                ident = _get_ident()
+                try:
+                    name = _active[ident].name
+                except KeyError:
+                    name = "<OS thread %d>" % ident
+                format = "%s: %s\n" % (name, format)
                 _sys.stderr.write(format)
 
 else:
@@ -254,6 +255,32 @@
         finally:
             self._acquire_restore(saved_state)
 
+    def wait_for(self, predicate, timeout=None):
+        endtime = None
+        waittime = timeout
+        result = predicate()
+        while not result:
+            if waittime is not None:
+                if endtime is None:
+                    endtime = _time() + waittime
+                else:
+                    waittime = endtime - _time()
+                    if waittime <= 0:
+                        if __debug__:
+                            self._note("%s.wait_for(%r, %r): Timed out.",
+                                       self, predicate, timeout)
+                        break
+            if __debug__:
+                self._note("%s.wait_for(%r, %r): Waiting with timeout=%s.",
+                           self, predicate, timeout, waittime)
+            self.wait(waittime)
+            result = predicate()
+        else:
+            if __debug__:
+                self._note("%s.wait_for(%r, %r): Success.",
+                           self, predicate, timeout)
+        return result
+
     def notify(self, n=1):
         if not self._is_owned():
             raise RuntimeError("cannot notify on un-acquired lock")
@@ -363,6 +390,10 @@
         self._cond = Condition(Lock())
         self._flag = False
 
+    def _reset_internal_locks(self):
+        # private!  called by Thread._reset_internal_locks by _after_fork()
+        self._cond.__init__()
+
     def is_set(self):
         return self._flag
 
@@ -482,13 +513,12 @@
     # Wait in the barrier until we are relased.  Raise an exception
     # if the barrier is reset or broken.
     def _wait(self, timeout):
-        while self._state == 0:
-            if self._cond.wait(timeout) is False:
-                #timed out.  Break the barrier
-                self._break()
-                raise BrokenBarrierError
-            if self._state < 0:
-                raise BrokenBarrierError
+        if not self._cond.wait_for(lambda : self._state != 0, timeout):
+            #timed out.  Break the barrier
+            self._break()
+            raise BrokenBarrierError
+        if self._state < 0:
+            raise BrokenBarrierError
         assert self._state == 1
 
     # If we are the last thread to exit the barrier, signal any threads
@@ -592,7 +622,7 @@
     #XXX __exc_clear = _sys.exc_clear
 
     def __init__(self, group=None, target=None, name=None,
-                 args=(), kwargs=None, verbose=None):
+                 args=(), kwargs=None, verbose=None, *, daemon=None):
         assert group is None, "group argument must be None for now"
         _Verbose.__init__(self, verbose)
         if kwargs is None:
@@ -601,7 +631,10 @@
         self._name = str(name or _newname())
         self._args = args
         self._kwargs = kwargs
-        self._daemonic = self._set_daemon()
+        if daemon is not None:
+            self._daemonic = daemon
+        else:
+            self._daemonic = current_thread().daemon
         self._ident = None
         self._started = Event()
         self._stopped = False
@@ -611,9 +644,12 @@
         # sys.exc_info since it can be changed between instances
         self._stderr = _sys.stderr
 
-    def _set_daemon(self):
-        # Overridden in _MainThread and _DummyThread
-        return current_thread().daemon
+    def _reset_internal_locks(self):
+        # private!  Called by _after_fork() to reset our internal locks as
+        # they may be in an invalid state leading to a deadlock or crash.
+        if hasattr(self, '_block'):  # DummyThread deletes _block
+            self._block.__init__()
+        self._started._reset_internal_locks()
 
     def __repr__(self):
         assert self._initialized, "Thread.__init__() was not called"
@@ -911,15 +947,12 @@
 class _MainThread(Thread):
 
     def __init__(self):
-        Thread.__init__(self, name="MainThread")
+        Thread.__init__(self, name="MainThread", daemon=False)
         self._started.set()
         self._set_ident()
         with _active_limbo_lock:
             _active[self._ident] = self
 
-    def _set_daemon(self):
-        return False
-
     def _exitfunc(self):
         self._stop()
         t = _pickSomeNonDaemonThread()
@@ -951,22 +984,18 @@
 class _DummyThread(Thread):
 
     def __init__(self):
-        Thread.__init__(self, name=_newname("Dummy-%d"))
+        Thread.__init__(self, name=_newname("Dummy-%d"), daemon=True)
 
-        # Thread.__block consumes an OS-level locking primitive, which
+        # Thread._block consumes an OS-level locking primitive, which
         # can never be used by a _DummyThread.  Since a _DummyThread
         # instance is immortal, that's bad, so release this resource.
         del self._block
 
-
         self._started.set()
         self._set_ident()
         with _active_limbo_lock:
             _active[self._ident] = self
 
-    def _set_daemon(self):
-        return True
-
     def join(self, timeout=None):
         assert False, "cannot join a dummy thread"
 
@@ -1033,6 +1062,9 @@
                 # its new value since it can have changed.
                 ident = _get_ident()
                 thread._ident = ident
+                # Any condition variables hanging off of the active thread may
+                # be in an invalid state, so we reinitialize them.
+                thread._reset_internal_locks()
                 new_active[ident] = thread
             else:
                 # All the others are already stopped.

Modified: python/branches/pep-3151/Lib/tkinter/__init__.py
==============================================================================
--- python/branches/pep-3151/Lib/tkinter/__init__.py	(original)
+++ python/branches/pep-3151/Lib/tkinter/__init__.py	Sat Feb 26 08:16:32 2011
@@ -216,8 +216,8 @@
         self._master.deletecommand(cbname)
     def trace_vinfo(self):
         """Return all trace callback information."""
-        return map(self._tk.split, self._tk.splitlist(
-            self._tk.call("trace", "vinfo", self._name)))
+        return [self._tk.split(x) for x in self._tk.splitlist(
+            self._tk.call("trace", "vinfo", self._name))]
     def __eq__(self, other):
         """Comparison for equality (==).
 
@@ -855,7 +855,7 @@
                      includeids and 'includeids' or None))
         if isinstance(data, str):
             data = [self.tk.split(data)]
-        return map(self.__winfo_parseitem, data)
+        return [self.__winfo_parseitem(x) for x in  data]
     def __winfo_parseitem(self, t):
         """Internal function."""
         return t[:1] + tuple(map(self.__winfo_getint, t[1:]))
@@ -1200,8 +1200,8 @@
         self.configure({key: value})
     def keys(self):
         """Return a list of all resource names of this widget."""
-        return map(lambda x: x[0][1:],
-               self.tk.split(self.tk.call(self._w, 'configure')))
+        return [x[0][1:] for x in
+                self.tk.split(self.tk.call(self._w, 'configure'))]
     def __str__(self):
         """Return the window path name of this widget."""
         return self._w
@@ -1223,18 +1223,18 @@
     def pack_slaves(self):
         """Return a list of all slaves of this widget
         in its packing order."""
-        return map(self._nametowidget,
-               self.tk.splitlist(
-                   self.tk.call('pack', 'slaves', self._w)))
+        return [self._nametowidget(x) for x in
+                self.tk.splitlist(
+                   self.tk.call('pack', 'slaves', self._w))]
     slaves = pack_slaves
     # Place method that applies to the master
     def place_slaves(self):
         """Return a list of all slaves of this widget
         in its packing order."""
-        return map(self._nametowidget,
-               self.tk.splitlist(
+        return [self._nametowidget(x) for x in
+                self.tk.splitlist(
                    self.tk.call(
-                       'place', 'slaves', self._w)))
+                       'place', 'slaves', self._w))]
     # Grid methods that apply to the master
     def grid_bbox(self, column=None, row=None, col2=None, row2=None):
         """Return a tuple of integer coordinates for the bounding
@@ -1338,9 +1338,9 @@
             args = args + ('-row', row)
         if column is not None:
             args = args + ('-column', column)
-        return map(self._nametowidget,
-               self.tk.splitlist(self.tk.call(
-                   ('grid', 'slaves', self._w) + args)))
+        return [self._nametowidget(x) for x in
+                self.tk.splitlist(self.tk.call(
+                   ('grid', 'slaves', self._w) + args))]
 
     # Support for the "event" command, new in Tk 4.2.
     # By Case Roole.
@@ -1494,7 +1494,7 @@
         if len(wlist) > 1:
             wlist = (wlist,) # Tk needs a list of windows here
         args = ('wm', 'colormapwindows', self._w) + wlist
-        return map(self._nametowidget, self.tk.call(args))
+        return [self._nametowidget(x) for x in  self.tk.call(args)]
     colormapwindows = wm_colormapwindows
     def wm_command(self, value=None):
         """Store VALUE in WM_COMMAND property. It is the command
@@ -2157,9 +2157,9 @@
     def coords(self, *args):
         """Return a list of coordinates for the item given in ARGS."""
         # XXX Should use _flatten on args
-        return map(getdouble,
+        return [getdouble(x) for x in
                            self.tk.splitlist(
-                   self.tk.call((self._w, 'coords') + args)))
+                   self.tk.call((self._w, 'coords') + args))]
     def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
         """Internal function."""
         args = _flatten(args)

Modified: python/branches/pep-3151/Lib/tkinter/scrolledtext.py
==============================================================================
--- python/branches/pep-3151/Lib/tkinter/scrolledtext.py	(original)
+++ python/branches/pep-3151/Lib/tkinter/scrolledtext.py	Sat Feb 26 08:16:32 2011
@@ -30,8 +30,8 @@
         # Copy geometry methods of self.frame without overriding Text
         # methods -- hack!
         text_meths = vars(Text).keys()
-        methods = vars(Pack).keys() + vars(Grid).keys() + vars(Place).keys()
-        methods = set(methods).difference(text_meths)
+        methods = vars(Pack).keys() | vars(Grid).keys() | vars(Place).keys()
+        methods = methods.difference(text_meths)
 
         for m in methods:
             if m[0] != '_' and m != 'config' and m != 'configure':
@@ -42,11 +42,10 @@
 
 
 def example():
-    import __main__
     from tkinter.constants import END
 
     stext = ScrolledText(bg='white', height=10)
-    stext.insert(END, __main__.__doc__)
+    stext.insert(END, __doc__)
     stext.pack(fill=BOTH, side=LEFT, expand=True)
     stext.focus_set()
     stext.mainloop()

Modified: python/branches/pep-3151/Lib/tkinter/test/test_tkinter/test_loadtk.py
==============================================================================
--- python/branches/pep-3151/Lib/tkinter/test/test_tkinter/test_loadtk.py	(original)
+++ python/branches/pep-3151/Lib/tkinter/test/test_tkinter/test_loadtk.py	Sat Feb 26 08:16:32 2011
@@ -31,7 +31,8 @@
                 # doesn't actually carry through to the process level
                 # because they don't support unsetenv
                 # If that's the case, abort.
-                display = os.popen('echo $DISPLAY').read().strip()
+                with os.popen('echo $DISPLAY') as pipe:
+                    display = pipe.read().strip()
                 if display:
                     return
 

Modified: python/branches/pep-3151/Lib/tkinter/test/test_ttk/test_widgets.py
==============================================================================
--- python/branches/pep-3151/Lib/tkinter/test/test_ttk/test_widgets.py	(original)
+++ python/branches/pep-3151/Lib/tkinter/test/test_ttk/test_widgets.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,6 @@
 import unittest
 import tkinter
+import os
 from tkinter import ttk
 from test.support import requires, run_unittest
 
@@ -925,7 +926,8 @@
         self.assertRaises(tkinter.TclError, self.tv.heading, '#0',
             anchor=1)
 
-
+    # XXX skipping for now; should be fixed to work with newer ttk
+    @unittest.skip
     def test_heading_callback(self):
         def simulate_heading_click(x, y):
             support.simulate_mouse_click(self.tv, x, y)

Modified: python/branches/pep-3151/Lib/tkinter/tix.py
==============================================================================
--- python/branches/pep-3151/Lib/tkinter/tix.py	(original)
+++ python/branches/pep-3151/Lib/tkinter/tix.py	Sat Feb 26 08:16:32 2011
@@ -268,10 +268,10 @@
         return self.tk.call('tixForm', 'info', self._w, option)
 
     def slaves(self):
-        return map(self._nametowidget,
-                   self.tk.splitlist(
+        return [self._nametowidget(x) for x in
+                self.tk.splitlist(
                        self.tk.call(
-                       'tixForm', 'slaves', self._w)))
+                       'tixForm', 'slaves', self._w))]
 
 
 

Modified: python/branches/pep-3151/Lib/token.py
==============================================================================
--- python/branches/pep-3151/Lib/token.py	(original)
+++ python/branches/pep-3151/Lib/token.py	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,7 @@
-#! /usr/bin/env python3
-
 """Token constants (from "token.h")."""
 
+__all__ = ['tok_name', 'ISTERMINAL', 'ISNONTERMINAL', 'ISEOF']
+
 #  This file is automatically generated; please don't muck it up!
 #
 #  To update the symbols in this file, 'cd' to the top directory of
@@ -68,12 +68,10 @@
 NT_OFFSET = 256
 #--end constants--
 
-tok_name = {}
-for _name, _value in list(globals().items()):
-    if type(_value) is type(0):
-        tok_name[_value] = _name
-del _name, _value
-
+tok_name = {value: name
+            for name, value in globals().items()
+            if isinstance(value, int)}
+__all__.extend(tok_name.values())
 
 def ISTERMINAL(x):
     return x < NT_OFFSET
@@ -85,7 +83,7 @@
     return x == ENDMARKER
 
 
-def main():
+def _main():
     import re
     import sys
     args = sys.argv[1:]
@@ -139,4 +137,4 @@
 
 
 if __name__ == "__main__":
-    main()
+    _main()

Modified: python/branches/pep-3151/Lib/tokenize.py
==============================================================================
--- python/branches/pep-3151/Lib/tokenize.py	(original)
+++ python/branches/pep-3151/Lib/tokenize.py	Sat Feb 26 08:16:32 2011
@@ -24,6 +24,7 @@
 __credits__ = ('GvR, ESR, Tim Peters, Thomas Wouters, Fred Drake, '
                'Skip Montanaro, Raymond Hettinger, Trent Nelson, '
                'Michael Foord')
+import builtins
 import re
 import sys
 from token import *
@@ -33,9 +34,8 @@
 cookie_re = re.compile("coding[:=]\s*([-\w.]+)")
 
 import token
-__all__ = [x for x in dir(token) if not x.startswith("_")]
-__all__.extend(["COMMENT", "tokenize", "detect_encoding", "NL", "untokenize",
-                "ENCODING", "TokenInfo"])
+__all__ = token.__all__ + ["COMMENT", "tokenize", "detect_encoding",
+                           "NL", "untokenize", "ENCODING", "TokenInfo"]
 del token
 
 COMMENT = N_TOKENS
@@ -336,13 +336,11 @@
     return default, [first, second]
 
 
-_builtin_open = open
-
 def open(filename):
     """Open a file in read only mode using the encoding detected by
     detect_encoding().
     """
-    buffer = _builtin_open(filename, 'rb')
+    buffer = builtins.open(filename, 'rb')
     encoding, lines = detect_encoding(buffer.readline)
     buffer.seek(0)
     text = TextIOWrapper(buffer, encoding, line_buffering=True)

Modified: python/branches/pep-3151/Lib/trace.py
==============================================================================
--- python/branches/pep-3151/Lib/trace.py	(original)
+++ python/branches/pep-3151/Lib/trace.py	Sat Feb 26 08:16:32 2011
@@ -47,7 +47,7 @@
   r = tracer.results()
   r.write_results(show_missing=True, coverdir="/tmp")
 """
-
+__all__ = ['Trace', 'CoverageResults']
 import io
 import linecache
 import os
@@ -60,6 +60,7 @@
 import gc
 import dis
 import pickle
+from warnings import warn as _warn
 
 try:
     import threading
@@ -77,7 +78,7 @@
         sys.settrace(None)
         threading.settrace(None)
 
-def usage(outfile):
+def _usage(outfile):
     outfile.write("""Usage: %s [OPTIONS] <file> [ARGS]
 
 Meta-options:
@@ -127,7 +128,7 @@
 # Simple rx to find lines with no code.
 rx_blank = re.compile(r'^\s*(#.*)?$')
 
-class Ignore:
+class _Ignore:
     def __init__(self, modules=None, dirs=None):
         self._mods = set() if not modules else set(modules)
         self._dirs = [] if not dirs else [os.path.normpath(d)
@@ -177,14 +178,14 @@
         self._ignore[modulename] = 0
         return 0
 
-def modname(path):
+def _modname(path):
     """Return a plausible module name for the patch."""
 
     base = os.path.basename(path)
     filename, ext = os.path.splitext(base)
     return filename
 
-def fullmodname(path):
+def _fullmodname(path):
     """Return a plausible module name for the path."""
 
     # If the file 'path' is part of a package, then the filename isn't
@@ -311,17 +312,17 @@
 
             if coverdir is None:
                 dir = os.path.dirname(os.path.abspath(filename))
-                modulename = modname(filename)
+                modulename = _modname(filename)
             else:
                 dir = coverdir
                 if not os.path.exists(dir):
                     os.makedirs(dir)
-                modulename = fullmodname(filename)
+                modulename = _fullmodname(filename)
 
             # If desired, get a list of the line numbers which represent
             # executable content (returned as a dict for better lookup speed)
             if show_missing:
-                lnotab = find_executable_linenos(filename)
+                lnotab = _find_executable_linenos(filename)
             else:
                 lnotab = {}
 
@@ -384,7 +385,7 @@
 
         return n_hits, n_lines
 
-def find_lines_from_code(code, strs):
+def _find_lines_from_code(code, strs):
     """Return dict where keys are lines in the line number table."""
     linenos = {}
 
@@ -394,19 +395,19 @@
 
     return linenos
 
-def find_lines(code, strs):
+def _find_lines(code, strs):
     """Return lineno dict for all code objects reachable from code."""
     # get all of the lineno information from the code of this scope level
-    linenos = find_lines_from_code(code, strs)
+    linenos = _find_lines_from_code(code, strs)
 
     # and check the constants for references to other code objects
     for c in code.co_consts:
         if inspect.iscode(c):
             # find another code object, so recurse into it
-            linenos.update(find_lines(c, strs))
+            linenos.update(_find_lines(c, strs))
     return linenos
 
-def find_strings(filename, encoding=None):
+def _find_strings(filename, encoding=None):
     """Return a dict of possible docstring positions.
 
     The dict maps line numbers to strings.  There is an entry for
@@ -429,7 +430,7 @@
             prev_ttype = ttype
     return d
 
-def find_executable_linenos(filename):
+def _find_executable_linenos(filename):
     """Return dict where keys are line numbers in the line number table."""
     try:
         with tokenize.open(filename) as f:
@@ -440,8 +441,8 @@
                               % (filename, err)), file=sys.stderr)
         return {}
     code = compile(prog, filename, "exec")
-    strs = find_strings(filename, encoding)
-    return find_lines(code, strs)
+    strs = _find_strings(filename, encoding)
+    return _find_lines(code, strs)
 
 class Trace:
     def __init__(self, count=1, trace=1, countfuncs=0, countcallers=0,
@@ -466,7 +467,7 @@
         """
         self.infile = infile
         self.outfile = outfile
-        self.ignore = Ignore(ignoremods, ignoredirs)
+        self.ignore = _Ignore(ignoremods, ignoredirs)
         self.counts = {}   # keys are (filename, linenumber)
         self.pathtobasename = {} # for memoizing os.path.basename
         self.donothing = 0
@@ -525,7 +526,7 @@
         code = frame.f_code
         filename = code.co_filename
         if filename:
-            modulename = modname(filename)
+            modulename = _modname(filename)
         else:
             modulename = None
 
@@ -592,9 +593,9 @@
             code = frame.f_code
             filename = frame.f_globals.get('__file__', None)
             if filename:
-                # XXX modname() doesn't work right for packages, so
+                # XXX _modname() doesn't work right for packages, so
                 # the ignore support won't work right for packages
-                modulename = modname(filename)
+                modulename = _modname(filename)
                 if modulename is not None:
                     ignore_it = self.ignore.names(filename, modulename)
                     if not ignore_it:
@@ -810,5 +811,47 @@
         if not no_report:
             results.write_results(missing, summary=summary, coverdir=coverdir)
 
+#  Deprecated API
+def usage(outfile):
+    _warn("The trace.usage() function is deprecated",
+         DeprecationWarning, 2)
+    _usage(outfile)
+
+class Ignore(_Ignore):
+    def __init__(self, modules=None, dirs=None):
+        _warn("The class trace.Ignore is deprecated",
+             DeprecationWarning, 2)
+        _Ignore.__init__(self, modules, dirs)
+
+def modname(path):
+    _warn("The trace.modname() function is deprecated",
+         DeprecationWarning, 2)
+    return _modname(path)
+
+def fullmodname(path):
+    _warn("The trace.fullmodname() function is deprecated",
+         DeprecationWarning, 2)
+    return _fullmodname(path)
+
+def find_lines_from_code(code, strs):
+    _warn("The trace.find_lines_from_code() function is deprecated",
+         DeprecationWarning, 2)
+    return _find_lines_from_code(code, strs)
+
+def find_lines(code, strs):
+    _warn("The trace.find_lines() function is deprecated",
+         DeprecationWarning, 2)
+    return _find_lines(code, strs)
+
+def find_strings(filename, encoding=None):
+    _warn("The trace.find_strings() function is deprecated",
+         DeprecationWarning, 2)
+    return _find_strings(filename, encoding=None)
+
+def find_executable_linenos(filename):
+    _warn("The trace.find_executable_linenos() function is deprecated",
+         DeprecationWarning, 2)
+    return _find_executable_linenos(filename)
+
 if __name__=='__main__':
     main()

Modified: python/branches/pep-3151/Lib/turtle.py
==============================================================================
--- python/branches/pep-3151/Lib/turtle.py	(original)
+++ python/branches/pep-3151/Lib/turtle.py	Sat Feb 26 08:16:32 2011
@@ -752,7 +752,7 @@
         [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982),
         (9.9999999999999982, 0.0)]
         >>> """
-        cl = list(self.cv.coords(item))
+        cl = self.cv.coords(item)
         pl = [(cl[i], -cl[i+1]) for i in range(0, len(cl), 2)]
         return  pl
 

Modified: python/branches/pep-3151/Lib/turtledemo/about_turtledemo.txt
==============================================================================
--- python/branches/pep-3151/Lib/turtledemo/about_turtledemo.txt	(original)
+++ python/branches/pep-3151/Lib/turtledemo/about_turtledemo.txt	Sat Feb 26 08:16:32 2011
@@ -1,9 +1,9 @@
 
     --------------------------------------
-        About turtleDemo.py
+        About this viewer
     --------------------------------------
 
-    Tiny demo Viewer to view turtle graphics example scripts.
+    Tiny demo viewer to view turtle graphics example scripts.
 
     Quickly and dirtyly assembled by Gregor Lingl.
     June, 2006

Modified: python/branches/pep-3151/Lib/turtledemo/demohelp.txt
==============================================================================
--- python/branches/pep-3151/Lib/turtledemo/demohelp.txt	(original)
+++ python/branches/pep-3151/Lib/turtledemo/demohelp.txt	Sat Feb 26 08:16:32 2011
@@ -53,12 +53,7 @@
 
    (2) How to add your own demos to the demo repository
 
-   - scriptname: must begin with tdemo_ ,
-     so it must have the form tdemo_<your-script-name>.py
-
-   - place: same directory as turtleDemo.py or some
-     subdirectory, the name of which must also begin with
-     tdemo_.....
+   - place: same directory as turtledemo/__main__.py
 
    - requirements on source code:
        code must contain a main() function which will

Modified: python/branches/pep-3151/Lib/unittest/case.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/case.py	(original)
+++ python/branches/pep-3151/Lib/unittest/case.py	Sat Feb 26 08:16:32 2011
@@ -6,10 +6,12 @@
 import pprint
 import re
 import warnings
+import collections
 
 from . import result
 from .util import (strclass, safe_repr, sorted_list_difference,
-                   unorderable_list_difference)
+                   unorderable_list_difference, _count_diff_all_purpose,
+                   _count_diff_hashable)
 
 __unittest = True
 
@@ -24,7 +26,6 @@
     Usually you can use TestResult.skip() or one of the skipping decorators
     instead of raising this directly.
     """
-    pass
 
 class _ExpectedFailure(Exception):
     """
@@ -41,7 +42,17 @@
     """
     The test was supposed to fail, but it didn't!
     """
-    pass
+
+
+class _Outcome(object):
+    def __init__(self):
+        self.success = True
+        self.skipped = None
+        self.unexpectedSuccess = None
+        self.expectedFailure = None
+        self.errors = []
+        self.failures = []
+
 
 def _id(obj):
     return obj
@@ -93,7 +104,7 @@
 class _AssertRaisesBaseContext(object):
 
     def __init__(self, expected, test_case, callable_obj=None,
-                  expected_regexp=None):
+                  expected_regex=None):
         self.expected = expected
         self.failureException = test_case.failureException
         if callable_obj is not None:
@@ -103,9 +114,9 @@
                 self.obj_name = str(callable_obj)
         else:
             self.obj_name = None
-        if isinstance(expected_regexp, (bytes, str)):
-            expected_regexp = re.compile(expected_regexp)
-        self.expected_regexp = expected_regexp
+        if isinstance(expected_regex, (bytes, str)):
+            expected_regex = re.compile(expected_regex)
+        self.expected_regex = expected_regex
 
 
 class _AssertRaisesContext(_AssertRaisesBaseContext):
@@ -131,13 +142,13 @@
             return False
         # store exception, without traceback, for later retrieval
         self.exception = exc_value.with_traceback(None)
-        if self.expected_regexp is None:
+        if self.expected_regex is None:
             return True
 
-        expected_regexp = self.expected_regexp
-        if not expected_regexp.search(str(exc_value)):
+        expected_regex = self.expected_regex
+        if not expected_regex.search(str(exc_value)):
             raise self.failureException('"%s" does not match "%s"' %
-                     (expected_regexp.pattern, str(exc_value)))
+                     (expected_regex.pattern, str(exc_value)))
         return True
 
 
@@ -171,8 +182,8 @@
                 continue
             if first_matching is None:
                 first_matching = w
-            if (self.expected_regexp is not None and
-                not self.expected_regexp.search(str(w))):
+            if (self.expected_regex is not None and
+                not self.expected_regex.search(str(w))):
                 continue
             # store warning for later retrieval
             self.warning = w
@@ -182,7 +193,7 @@
         # Now we simply try to choose a helpful failure message
         if first_matching is not None:
             raise self.failureException('"%s" does not match "%s"' %
-                     (self.expected_regexp.pattern, str(first_matching)))
+                     (self.expected_regex.pattern, str(first_matching)))
         if self.obj_name:
             raise self.failureException("{0} not triggered by {1}"
                 .format(exc_name, self.obj_name))
@@ -191,6 +202,27 @@
                 .format(exc_name))
 
 
+class _TypeEqualityDict(object):
+
+    def __init__(self, testcase):
+        self.testcase = testcase
+        self._store = {}
+
+    def __setitem__(self, key, value):
+        self._store[key] = value
+
+    def __getitem__(self, key):
+        value = self._store[key]
+        if isinstance(value, str):
+            return getattr(self.testcase, value)
+        return value
+
+    def get(self, key, default=None):
+        if key in self._store:
+            return self[key]
+        return default
+
+
 class TestCase(object):
     """A class whose instances are single test cases.
 
@@ -223,7 +255,7 @@
     # objects used in assert methods) will be printed on failure in *addition*
     # to any explicit message passed.
 
-    longMessage = False
+    longMessage = True
 
     # This attribute sets the maximum length of a diff in failure messages
     # by assert methods using difflib. It is looked up as an instance attribute
@@ -241,25 +273,30 @@
            not have a method with the specified name.
         """
         self._testMethodName = methodName
-        self._resultForDoCleanups = None
+        self._outcomeForDoCleanups = None
+        self._testMethodDoc = 'No test'
         try:
             testMethod = getattr(self, methodName)
         except AttributeError:
-            raise ValueError("no such test method in %s: %s" %
-                  (self.__class__, methodName))
-        self._testMethodDoc = testMethod.__doc__
+            if methodName != 'runTest':
+                # we allow instantiation with no explicit method name
+                # but not an *incorrect* or missing method name
+                raise ValueError("no such test method in %s: %s" %
+                      (self.__class__, methodName))
+        else:
+            self._testMethodDoc = testMethod.__doc__
         self._cleanups = []
 
         # Map types to custom assertEqual functions that will compare
         # instances of said type in more detail to generate a more useful
         # error message.
-        self._type_equality_funcs = {}
-        self.addTypeEqualityFunc(dict, self.assertDictEqual)
-        self.addTypeEqualityFunc(list, self.assertListEqual)
-        self.addTypeEqualityFunc(tuple, self.assertTupleEqual)
-        self.addTypeEqualityFunc(set, self.assertSetEqual)
-        self.addTypeEqualityFunc(frozenset, self.assertSetEqual)
-        self.addTypeEqualityFunc(str, self.assertMultiLineEqual)
+        self._type_equality_funcs = _TypeEqualityDict(self)
+        self.addTypeEqualityFunc(dict, 'assertDictEqual')
+        self.addTypeEqualityFunc(list, 'assertListEqual')
+        self.addTypeEqualityFunc(tuple, 'assertTupleEqual')
+        self.addTypeEqualityFunc(set, 'assertSetEqual')
+        self.addTypeEqualityFunc(frozenset, 'assertSetEqual')
+        self.addTypeEqualityFunc(str, 'assertMultiLineEqual')
 
     def addTypeEqualityFunc(self, typeobj, function):
         """Add a type specific assertEqual style function to compare a type.
@@ -345,6 +382,36 @@
                           RuntimeWarning, 2)
             result.addSuccess(self)
 
+    def _executeTestPart(self, function, outcome, isTest=False):
+        try:
+            function()
+        except KeyboardInterrupt:
+            raise
+        except SkipTest as e:
+            outcome.success = False
+            outcome.skipped = str(e)
+        except _UnexpectedSuccess:
+            exc_info = sys.exc_info()
+            outcome.success = False
+            if isTest:
+                outcome.unexpectedSuccess = exc_info
+            else:
+                outcome.errors.append(exc_info)
+        except _ExpectedFailure:
+            outcome.success = False
+            exc_info = sys.exc_info()
+            if isTest:
+                outcome.expectedFailure = exc_info
+            else:
+                outcome.errors.append(exc_info)
+        except self.failureException:
+            outcome.success = False
+            outcome.failures.append(sys.exc_info())
+            exc_info = sys.exc_info()
+        except:
+            outcome.success = False
+            outcome.errors.append(sys.exc_info())
+
     def run(self, result=None):
         orig_result = result
         if result is None:
@@ -353,7 +420,6 @@
             if startTestRun is not None:
                 startTestRun()
 
-        self._resultForDoCleanups = result
         result.startTest(self)
 
         testMethod = getattr(self, self._testMethodName)
@@ -368,51 +434,42 @@
                 result.stopTest(self)
             return
         try:
-            success = False
-            try:
-                self.setUp()
-            except SkipTest as e:
-                self._addSkip(result, str(e))
-            except Exception:
-                result.addError(self, sys.exc_info())
+            outcome = _Outcome()
+            self._outcomeForDoCleanups = outcome
+
+            self._executeTestPart(self.setUp, outcome)
+            if outcome.success:
+                self._executeTestPart(testMethod, outcome, isTest=True)
+                self._executeTestPart(self.tearDown, outcome)
+
+            self.doCleanups()
+            if outcome.success:
+                result.addSuccess(self)
             else:
-                try:
-                    testMethod()
-                except self.failureException:
-                    result.addFailure(self, sys.exc_info())
-                except _ExpectedFailure as e:
-                    addExpectedFailure = getattr(result, 'addExpectedFailure', None)
-                    if addExpectedFailure is not None:
-                        addExpectedFailure(self, e.exc_info)
-                    else:
-                        warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
-                                      RuntimeWarning)
-                        result.addSuccess(self)
-                except _UnexpectedSuccess:
+                if outcome.skipped is not None:
+                    self._addSkip(result, outcome.skipped)
+                for exc_info in outcome.errors:
+                    result.addError(self, exc_info)
+                for exc_info in outcome.failures:
+                    result.addFailure(self, exc_info)
+                if outcome.unexpectedSuccess is not None:
                     addUnexpectedSuccess = getattr(result, 'addUnexpectedSuccess', None)
                     if addUnexpectedSuccess is not None:
                         addUnexpectedSuccess(self)
                     else:
                         warnings.warn("TestResult has no addUnexpectedSuccess method, reporting as failures",
                                       RuntimeWarning)
-                        result.addFailure(self, sys.exc_info())
-                except SkipTest as e:
-                    self._addSkip(result, str(e))
-                except Exception:
-                    result.addError(self, sys.exc_info())
-                else:
-                    success = True
+                        result.addFailure(self, outcome.unexpectedSuccess)
+
+                if outcome.expectedFailure is not None:
+                    addExpectedFailure = getattr(result, 'addExpectedFailure', None)
+                    if addExpectedFailure is not None:
+                        addExpectedFailure(self, outcome.expectedFailure)
+                    else:
+                        warnings.warn("TestResult has no addExpectedFailure method, reporting as passes",
+                                      RuntimeWarning)
+                        result.addSuccess(self)
 
-                try:
-                    self.tearDown()
-                except Exception:
-                    result.addError(self, sys.exc_info())
-                    success = False
-
-            cleanUpSuccess = self.doCleanups()
-            success = success and cleanUpSuccess
-            if success:
-                result.addSuccess(self)
         finally:
             result.stopTest(self)
             if orig_result is None:
@@ -423,16 +480,15 @@
     def doCleanups(self):
         """Execute all cleanup functions. Normally called for you after
         tearDown."""
-        result = self._resultForDoCleanups
-        ok = True
+        outcome = self._outcomeForDoCleanups or _Outcome()
         while self._cleanups:
-            function, args, kwargs = self._cleanups.pop(-1)
-            try:
-                function(*args, **kwargs)
-            except Exception:
-                ok = False
-                result.addError(self, sys.exc_info())
-        return ok
+            function, args, kwargs = self._cleanups.pop()
+            part = lambda: function(*args, **kwargs)
+            self._executeTestPart(part, outcome)
+
+        # return this for backwards compatibility
+        # even though we no longer us it internally
+        return outcome.success
 
     def __call__(self, *args, **kwds):
         return self.run(*args, **kwds)
@@ -455,15 +511,15 @@
         raise self.failureException(msg)
 
     def assertFalse(self, expr, msg=None):
-        "Fail the test if the expression is true."
+        """Check that the expression is false."""
         if expr:
-            msg = self._formatMessage(msg, "%s is not False" % safe_repr(expr))
+            msg = self._formatMessage(msg, "%s is not false" % safe_repr(expr))
             raise self.failureException(msg)
 
     def assertTrue(self, expr, msg=None):
-        """Fail the test unless the expression is true."""
+        """Check that the expression is true."""
         if not expr:
-            msg = self._formatMessage(msg, "%s is not True" % safe_repr(expr))
+            msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
             raise self.failureException(msg)
 
     def _formatMessage(self, msg, standardMsg):
@@ -666,34 +722,6 @@
         msg = self._formatMessage(msg, standardMsg)
         raise self.failureException(msg)
 
-    # Synonyms for assertion methods
-
-    # The plurals are undocumented.  Keep them that way to discourage use.
-    # Do not add more.  Do not remove.
-    # Going through a deprecation cycle on these would annoy many people.
-    assertEquals = assertEqual
-    assertNotEquals = assertNotEqual
-    assertAlmostEquals = assertAlmostEqual
-    assertNotAlmostEquals = assertNotAlmostEqual
-    assert_ = assertTrue
-
-    # These fail* assertion method names are pending deprecation and will
-    # be a DeprecationWarning in 3.2; http://bugs.python.org/issue2578
-    def _deprecate(original_func):
-        def deprecated_func(*args, **kwargs):
-            warnings.warn(
-                'Please use {0} instead.'.format(original_func.__name__),
-                DeprecationWarning, 2)
-            return original_func(*args, **kwargs)
-        return deprecated_func
-
-    failUnlessEqual = _deprecate(assertEqual)
-    failIfEqual = _deprecate(assertNotEqual)
-    failUnlessAlmostEqual = _deprecate(assertAlmostEqual)
-    failIfAlmostEqual = _deprecate(assertNotAlmostEqual)
-    failUnless = _deprecate(assertTrue)
-    failUnlessRaises = _deprecate(assertRaises)
-    failIf = _deprecate(assertFalse)
 
     def assertSequenceEqual(self, seq1, seq2, msg=None, seq_type=None):
         """An equality assertion for ordered sequences (like lists and tuples).
@@ -899,8 +927,8 @@
             self.fail(self._formatMessage(msg, standardMsg))
 
     def assertDictEqual(self, d1, d2, msg=None):
-        self.assert_(isinstance(d1, dict), 'First argument is not a dictionary')
-        self.assert_(isinstance(d2, dict), 'Second argument is not a dictionary')
+        self.assertIsInstance(d1, dict, 'First argument is not a dictionary')
+        self.assertIsInstance(d2, dict, 'Second argument is not a dictionary')
 
         if d1 != d2:
             standardMsg = '%s != %s' % (safe_repr(d1, True), safe_repr(d2, True))
@@ -910,118 +938,43 @@
             standardMsg = self._truncateMessage(standardMsg, diff)
             self.fail(self._formatMessage(msg, standardMsg))
 
-    def assertDictContainsSubset(self, expected, actual, msg=None):
-        """Checks whether actual is a superset of expected."""
-        missing = []
-        mismatched = []
-        for key, value in expected.items():
-            if key not in actual:
-                missing.append(key)
-            elif value != actual[key]:
-                mismatched.append('%s, expected: %s, actual: %s' %
-                                  (safe_repr(key), safe_repr(value),
-                                   safe_repr(actual[key])))
-
-        if not (missing or mismatched):
-            return
-
-        standardMsg = ''
-        if missing:
-            standardMsg = 'Missing: %s' % ','.join(safe_repr(m) for m in
-                                                    missing)
-        if mismatched:
-            if standardMsg:
-                standardMsg += '; '
-            standardMsg += 'Mismatched values: %s' % ','.join(mismatched)
-
-        self.fail(self._formatMessage(msg, standardMsg))
-
-    def assertSameElements(self, expected_seq, actual_seq, msg=None):
-        """An unordered sequence specific comparison.
-
-        Raises with an error message listing which elements of expected_seq
-        are missing from actual_seq and vice versa if any.
-
-        Duplicate elements are ignored when comparing *expected_seq* and
-        *actual_seq*. It is the equivalent of ``assertEqual(set(expected),
-        set(actual))`` but it works with sequences of unhashable objects as
-        well.
-        """
-        warnings.warn('assertSameElements is deprecated',
-                      DeprecationWarning)
-        try:
-            expected = set(expected_seq)
-            actual = set(actual_seq)
-            missing = sorted(expected.difference(actual))
-            unexpected = sorted(actual.difference(expected))
-        except TypeError:
-            # Fall back to slower list-compare if any of the objects are
-            # not hashable.
-            expected = list(expected_seq)
-            actual = list(actual_seq)
-            try:
-                expected.sort()
-                actual.sort()
-            except TypeError:
-                missing, unexpected = unorderable_list_difference(expected,
-                                                                  actual)
-            else:
-                missing, unexpected = sorted_list_difference(expected, actual)
-        errors = []
-        if missing:
-            errors.append('Expected, but missing:\n    %s' %
-                          safe_repr(missing))
-        if unexpected:
-            errors.append('Unexpected, but present:\n    %s' %
-                          safe_repr(unexpected))
-        if errors:
-            standardMsg = '\n'.join(errors)
-            self.fail(self._formatMessage(msg, standardMsg))
-
+    def assertCountEqual(self, first, second, msg=None):
+        """An unordered sequence comparison asserting that the same elements,
+        regardless of order.  If the same element occurs more than once,
+        it verifies that the elements occur the same number of times.
 
-    def assertItemsEqual(self, expected_seq, actual_seq, msg=None):
-        """An unordered sequence / set specific comparison. It asserts that
-        expected_seq and actual_seq contain the same elements. It is
-        the equivalent of::
+            self.assertEqual(Counter(list(first)),
+                             Counter(list(second)))
 
-            self.assertEqual(sorted(expected_seq), sorted(actual_seq))
-
-        Raises with an error message listing which elements of expected_seq
-        are missing from actual_seq and vice versa if any.
-
-        Asserts that each element has the same count in both sequences.
-        Example:
+         Example:
             - [0, 1, 1] and [1, 0, 1] compare equal.
             - [0, 0, 1] and [0, 1] compare unequal.
+
         """
+        first_seq, second_seq = list(first), list(second)
         try:
-            expected = sorted(expected_seq)
-            actual = sorted(actual_seq)
+            first = collections.Counter(first_seq)
+            second = collections.Counter(second_seq)
         except TypeError:
-            # Unsortable items (example: set(), complex(), ...)
-            expected = list(expected_seq)
-            actual = list(actual_seq)
-            missing, unexpected = unorderable_list_difference(expected, actual)
+            # Handle case with unhashable elements
+            differences = _count_diff_all_purpose(first_seq, second_seq)
         else:
-            return self.assertSequenceEqual(expected, actual, msg=msg)
+            if first == second:
+                return
+            differences = _count_diff_hashable(first_seq, second_seq)
 
-        errors = []
-        if missing:
-            errors.append('Expected, but missing:\n    %s' %
-                           safe_repr(missing))
-        if unexpected:
-            errors.append('Unexpected, but present:\n    %s' %
-                           safe_repr(unexpected))
-        if errors:
-            standardMsg = '\n'.join(errors)
-            self.fail(self._formatMessage(msg, standardMsg))
+        if differences:
+            standardMsg = 'Element counts were not equal:\n'
+            lines = ['First has %d, Second has %d:  %r' % diff for diff in differences]
+            diffMsg = '\n'.join(lines)
+            standardMsg = self._truncateMessage(standardMsg, diffMsg)
+            msg = self._formatMessage(msg, standardMsg)
+            self.fail(msg)
 
     def assertMultiLineEqual(self, first, second, msg=None):
         """Assert that two multi-line strings are equal."""
-        self.assert_(isinstance(first, str), (
-                'First argument is not a string'))
-        self.assert_(isinstance(second, str), (
-                'Second argument is not a string'))
+        self.assertIsInstance(first, str, 'First argument is not a string')
+        self.assertIsInstance(second, str, 'Second argument is not a string')
 
         if first != second:
             firstlines = first.splitlines(True)
@@ -1084,27 +1037,27 @@
             standardMsg = '%s is an instance of %r' % (safe_repr(obj), cls)
             self.fail(self._formatMessage(msg, standardMsg))
 
-    def assertRaisesRegexp(self, expected_exception, expected_regexp,
-                           callable_obj=None, *args, **kwargs):
-        """Asserts that the message in a raised exception matches a regexp.
+    def assertRaisesRegex(self, expected_exception, expected_regex,
+                          callable_obj=None, *args, **kwargs):
+        """Asserts that the message in a raised exception matches a regex.
 
         Args:
             expected_exception: Exception class expected to be raised.
-            expected_regexp: Regexp (re pattern object or string) expected
+            expected_regex: Regex (re pattern object or string) expected
                     to be found in error message.
             callable_obj: Function to be called.
             args: Extra args.
             kwargs: Extra kwargs.
         """
         context = _AssertRaisesContext(expected_exception, self, callable_obj,
-                                       expected_regexp)
+                                       expected_regex)
         if callable_obj is None:
             return context
         with context:
             callable_obj(*args, **kwargs)
 
-    def assertWarnsRegexp(self, expected_warning, expected_regexp,
-                          callable_obj=None, *args, **kwargs):
+    def assertWarnsRegex(self, expected_warning, expected_regex,
+                         callable_obj=None, *args, **kwargs):
         """Asserts that the message in a triggered warning matches a regexp.
         Basic functioning is similar to assertWarns() with the addition
         that only warnings whose messages also match the regular expression
@@ -1112,42 +1065,63 @@
 
         Args:
             expected_warning: Warning class expected to be triggered.
-            expected_regexp: Regexp (re pattern object or string) expected
+            expected_regex: Regex (re pattern object or string) expected
                     to be found in error message.
             callable_obj: Function to be called.
             args: Extra args.
             kwargs: Extra kwargs.
         """
         context = _AssertWarnsContext(expected_warning, self, callable_obj,
-                                      expected_regexp)
+                                      expected_regex)
         if callable_obj is None:
             return context
         with context:
             callable_obj(*args, **kwargs)
 
-    def assertRegexpMatches(self, text, expected_regexp, msg=None):
+    def assertRegex(self, text, expected_regex, msg=None):
         """Fail the test unless the text matches the regular expression."""
-        if isinstance(expected_regexp, (str, bytes)):
-            expected_regexp = re.compile(expected_regexp)
-        if not expected_regexp.search(text):
-            msg = msg or "Regexp didn't match"
-            msg = '%s: %r not found in %r' % (msg, expected_regexp.pattern, text)
+        if isinstance(expected_regex, (str, bytes)):
+            assert expected_regex, "expected_regex must not be empty."
+            expected_regex = re.compile(expected_regex)
+        if not expected_regex.search(text):
+            msg = msg or "Regex didn't match"
+            msg = '%s: %r not found in %r' % (msg, expected_regex.pattern, text)
             raise self.failureException(msg)
 
-    def assertNotRegexpMatches(self, text, unexpected_regexp, msg=None):
+    def assertNotRegex(self, text, unexpected_regex, msg=None):
         """Fail the test if the text matches the regular expression."""
-        if isinstance(unexpected_regexp, (str, bytes)):
-            unexpected_regexp = re.compile(unexpected_regexp)
-        match = unexpected_regexp.search(text)
+        if isinstance(unexpected_regex, (str, bytes)):
+            unexpected_regex = re.compile(unexpected_regex)
+        match = unexpected_regex.search(text)
         if match:
-            msg = msg or "Regexp matched"
+            msg = msg or "Regex matched"
             msg = '%s: %r matches %r in %r' % (msg,
                                                text[match.start():match.end()],
-                                               unexpected_regexp.pattern,
+                                               unexpected_regex.pattern,
                                                text)
             raise self.failureException(msg)
 
 
+    def _deprecate(original_func):
+        def deprecated_func(*args, **kwargs):
+            warnings.warn(
+                'Please use {0} instead.'.format(original_func.__name__),
+                DeprecationWarning, 2)
+            return original_func(*args, **kwargs)
+        return deprecated_func
+
+    # The fail* methods can be removed in 3.3, the 5 assert* methods will
+    # have to stay around for a few more versions.  See #9424.
+    assertEquals = _deprecate(assertEqual)
+    assertNotEquals = _deprecate(assertNotEqual)
+    assertAlmostEquals = _deprecate(assertAlmostEqual)
+    assertNotAlmostEquals = _deprecate(assertNotAlmostEqual)
+    assert_ = _deprecate(assertTrue)
+    assertRaisesRegexp = _deprecate(assertRaisesRegex)
+    assertRegexpMatches = _deprecate(assertRegex)
+
+
+
 class FunctionTestCase(TestCase):
     """A test case that wraps a test function.
 

Modified: python/branches/pep-3151/Lib/unittest/loader.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/loader.py	(original)
+++ python/branches/pep-3151/Lib/unittest/loader.py	Sat Feb 26 08:16:32 2011
@@ -147,9 +147,9 @@
 
     def discover(self, start_dir, pattern='test*.py', top_level_dir=None):
         """Find and return all test modules from the specified start
-        directory, recursing into subdirectories to find them. Only test files
-        that match the pattern will be loaded. (Using shell style pattern
-        matching.)
+        directory, recursing into subdirectories to find them and return all
+        tests found within them. Only test files that match the pattern will
+        be loaded. (Using shell style pattern matching.)
 
         All test modules must be importable from the top level of the project.
         If the start directory is not the top level directory then the top

Modified: python/branches/pep-3151/Lib/unittest/main.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/main.py	(original)
+++ python/branches/pep-3151/Lib/unittest/main.py	Sat Feb 26 08:16:32 2011
@@ -58,7 +58,24 @@
                                                in MyTestCase
 """
 
+def _convert_name(name):
+    # on Linux / Mac OS X 'foo.PY' is not importable, but on
+    # Windows it is. Simpler to do a case insensitive match
+    # a better check would be to check that the name is a
+    # valid Python module name.
+    if os.path.isfile(name) and name.lower().endswith('.py'):
+        if os.path.isabs(name):
+            rel_path = os.path.relpath(name, os.getcwd())
+            if os.path.isabs(rel_path) or rel_path.startswith(os.pardir):
+                return name
+            name = rel_path
+        # on Windows both '\' and '/' are used as path
+        # separators. Better to replace both than rely on os.path.sep
+        return name[:-3].replace('\\', '.').replace('/', '.')
+    return name
 
+def _convert_names(names):
+    return [_convert_name(name) for name in names]
 
 class TestProgram(object):
     """A command-line program that runs a set of tests; this is primarily
@@ -67,12 +84,12 @@
     USAGE = USAGE_FROM_MODULE
 
     # defaults for testing
-    failfast = catchbreak = buffer = progName = None
+    failfast = catchbreak = buffer = progName = warnings = None
 
     def __init__(self, module='__main__', defaultTest=None, argv=None,
                     testRunner=None, testLoader=loader.defaultTestLoader,
                     exit=True, verbosity=1, failfast=None, catchbreak=None,
-                    buffer=None):
+                    buffer=None, warnings=None):
         if isinstance(module, str):
             self.module = __import__(module)
             for part in module.split('.')[1:]:
@@ -87,6 +104,18 @@
         self.catchbreak = catchbreak
         self.verbosity = verbosity
         self.buffer = buffer
+        if warnings is None and not sys.warnoptions:
+            # even if DreprecationWarnings are ignored by default
+            # print them anyway unless other warnings settings are
+            # specified by the warnings arg or the -W python flag
+            self.warnings = 'default'
+        else:
+            # here self.warnings is set either to the value passed
+            # to the warnings args or to None.
+            # If the user didn't pass a value self.warnings will
+            # be None. This means that the behavior is unchanged
+            # and depends on the values passed to -W.
+            self.warnings = warnings
         self.defaultTest = defaultTest
         self.testRunner = testRunner
         self.testLoader = testLoader
@@ -109,7 +138,8 @@
         sys.exit(2)
 
     def parseArgs(self, argv):
-        if len(argv) > 1 and argv[1].lower() == 'discover':
+        if ((len(argv) > 1 and argv[1].lower() == 'discover') or
+            (len(argv) == 1 and self.module is None)):
             self._do_discovery(argv[2:])
             return
 
@@ -117,38 +147,48 @@
         long_opts = ['help', 'verbose', 'quiet', 'failfast', 'catch', 'buffer']
         try:
             options, args = getopt.getopt(argv[1:], 'hHvqfcb', long_opts)
-            for opt, value in options:
-                if opt in ('-h','-H','--help'):
-                    self.usageExit()
-                if opt in ('-q','--quiet'):
-                    self.verbosity = 0
-                if opt in ('-v','--verbose'):
-                    self.verbosity = 2
-                if opt in ('-f','--failfast'):
-                    if self.failfast is None:
-                        self.failfast = True
-                    # Should this raise an exception if -f is not valid?
-                if opt in ('-c','--catch'):
-                    if self.catchbreak is None:
-                        self.catchbreak = True
-                    # Should this raise an exception if -c is not valid?
-                if opt in ('-b','--buffer'):
-                    if self.buffer is None:
-                        self.buffer = True
-                    # Should this raise an exception if -b is not valid?
-            if len(args) == 0 and self.defaultTest is None:
-                # createTests will load tests from self.module
-                self.testNames = None
-            elif len(args) > 0:
-                self.testNames = args
-                if __name__ == '__main__':
-                    # to support python -m unittest ...
-                    self.module = None
-            else:
-                self.testNames = (self.defaultTest,)
-            self.createTests()
         except getopt.error as msg:
             self.usageExit(msg)
+            return
+
+        for opt, value in options:
+            if opt in ('-h','-H','--help'):
+                self.usageExit()
+            if opt in ('-q','--quiet'):
+                self.verbosity = 0
+            if opt in ('-v','--verbose'):
+                self.verbosity = 2
+            if opt in ('-f','--failfast'):
+                if self.failfast is None:
+                    self.failfast = True
+                # Should this raise an exception if -f is not valid?
+            if opt in ('-c','--catch'):
+                if self.catchbreak is None:
+                    self.catchbreak = True
+                # Should this raise an exception if -c is not valid?
+            if opt in ('-b','--buffer'):
+                if self.buffer is None:
+                    self.buffer = True
+                # Should this raise an exception if -b is not valid?
+
+        if len(args) == 0 and self.module is None:
+            # this allows "python -m unittest -v" to still work for
+            # test discovery. This means -c / -b / -v / -f options will
+            # be handled twice, which is harmless but not ideal.
+            self._do_discovery(argv[1:])
+            return
+
+        if len(args) == 0 and self.defaultTest is None:
+            # createTests will load tests from self.module
+            self.testNames = None
+        elif len(args) > 0:
+            self.testNames = _convert_names(args)
+            if __name__ == '__main__':
+                # to support python -m unittest ...
+                self.module = None
+        else:
+            self.testNames = (self.defaultTest,)
+        self.createTests()
 
     def createTests(self):
         if self.testNames is None:
@@ -219,7 +259,8 @@
             try:
                 testRunner = self.testRunner(verbosity=self.verbosity,
                                              failfast=self.failfast,
-                                             buffer=self.buffer)
+                                             buffer=self.buffer,
+                                             warnings=self.warnings)
             except TypeError:
                 # didn't accept the verbosity, buffer or failfast arguments
                 testRunner = self.testRunner()

Modified: python/branches/pep-3151/Lib/unittest/runner.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/runner.py	(original)
+++ python/branches/pep-3151/Lib/unittest/runner.py	Sat Feb 26 08:16:32 2011
@@ -2,6 +2,7 @@
 
 import sys
 import time
+import warnings
 
 from . import result
 from .signals import registerResult
@@ -124,13 +125,16 @@
     """
     resultclass = TextTestResult
 
-    def __init__(self, stream=sys.stderr, descriptions=True, verbosity=1,
-                 failfast=False, buffer=False, resultclass=None):
+    def __init__(self, stream=None, descriptions=True, verbosity=1,
+                 failfast=False, buffer=False, resultclass=None, warnings=None):
+        if stream is None:
+            stream = sys.stderr
         self.stream = _WritelnDecorator(stream)
         self.descriptions = descriptions
         self.verbosity = verbosity
         self.failfast = failfast
         self.buffer = buffer
+        self.warnings = warnings
         if resultclass is not None:
             self.resultclass = resultclass
 
@@ -143,17 +147,30 @@
         registerResult(result)
         result.failfast = self.failfast
         result.buffer = self.buffer
-        startTime = time.time()
-        startTestRun = getattr(result, 'startTestRun', None)
-        if startTestRun is not None:
-            startTestRun()
-        try:
-            test(result)
-        finally:
-            stopTestRun = getattr(result, 'stopTestRun', None)
-            if stopTestRun is not None:
-                stopTestRun()
-        stopTime = time.time()
+        with warnings.catch_warnings():
+            if self.warnings:
+                # if self.warnings is set, use it to filter all the warnings
+                warnings.simplefilter(self.warnings)
+                # if the filter is 'default' or 'always', special-case the
+                # warnings from the deprecated unittest methods to show them
+                # no more than once per module, because they can be fairly
+                # noisy.  The -Wd and -Wa flags can be used to bypass this
+                # only when self.warnings is None.
+                if self.warnings in ['default', 'always']:
+                    warnings.filterwarnings('module',
+                            category=DeprecationWarning,
+                            message='Please use assert\w+ instead.')
+            startTime = time.time()
+            startTestRun = getattr(result, 'startTestRun', None)
+            if startTestRun is not None:
+                startTestRun()
+            try:
+                test(result)
+            finally:
+                stopTestRun = getattr(result, 'stopTestRun', None)
+                if stopTestRun is not None:
+                    stopTestRun()
+            stopTime = time.time()
         timeTaken = stopTime - startTime
         result.printErrors()
         if hasattr(result, 'separator2'):
@@ -168,9 +185,10 @@
             results = map(len, (result.expectedFailures,
                                 result.unexpectedSuccesses,
                                 result.skipped))
-            expectedFails, unexpectedSuccesses, skipped = results
         except AttributeError:
             pass
+        else:
+            expectedFails, unexpectedSuccesses, skipped = results
 
         infos = []
         if not result.wasSuccessful():

Modified: python/branches/pep-3151/Lib/unittest/suite.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/suite.py	(original)
+++ python/branches/pep-3151/Lib/unittest/suite.py	Sat Feb 26 08:16:32 2011
@@ -104,6 +104,7 @@
         if topLevel:
             self._tearDownPreviousClass(None, result)
             self._handleModuleTearDown(result)
+            result._testRunEntered = False
         return result
 
     def debug(self):

Modified: python/branches/pep-3151/Lib/unittest/test/test_assertions.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_assertions.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_assertions.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,5 @@
 import datetime
-
+import warnings
 import unittest
 
 
@@ -92,15 +92,15 @@
         else:
             self.fail("assertRaises() didn't let exception pass through")
 
-    def testAssertNotRegexpMatches(self):
-        self.assertNotRegexpMatches('Ala ma kota', r'r+')
+    def testAssertNotRegex(self):
+        self.assertNotRegex('Ala ma kota', r'r+')
         try:
-            self.assertNotRegexpMatches('Ala ma kota', r'k.t', 'Message')
+            self.assertNotRegex('Ala ma kota', r'k.t', 'Message')
         except self.failureException as e:
             self.assertIn("'kot'", e.args[0])
             self.assertIn('Message', e.args[0])
         else:
-            self.fail('assertNotRegexpMatches should have failed.')
+            self.fail('assertNotRegex should have failed.')
 
 
 class TestLongMessage(unittest.TestCase):
@@ -127,14 +127,14 @@
         self.testableFalse = TestableTestFalse('testTest')
 
     def testDefault(self):
-        self.assertFalse(unittest.TestCase.longMessage)
+        self.assertTrue(unittest.TestCase.longMessage)
 
     def test_formatMsg(self):
-        self.assertEquals(self.testableFalse._formatMessage(None, "foo"), "foo")
-        self.assertEquals(self.testableFalse._formatMessage("foo", "bar"), "foo")
+        self.assertEqual(self.testableFalse._formatMessage(None, "foo"), "foo")
+        self.assertEqual(self.testableFalse._formatMessage("foo", "bar"), "foo")
 
-        self.assertEquals(self.testableTrue._formatMessage(None, "foo"), "foo")
-        self.assertEquals(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
+        self.assertEqual(self.testableTrue._formatMessage(None, "foo"), "foo")
+        self.assertEqual(self.testableTrue._formatMessage("foo", "bar"), "bar : foo")
 
         # This blows up if _formatMessage uses string concatenation
         self.testableTrue._formatMessage(object(), 'foo')
@@ -153,26 +153,26 @@
                 test = self.testableTrue
             return getattr(test, methodName)
 
-        for i, expected_regexp in enumerate(errors):
+        for i, expected_regex in enumerate(errors):
             testMethod = getMethod(i)
             kwargs = {}
             withMsg = i % 2
             if withMsg:
                 kwargs = {"msg": "oops"}
 
-            with self.assertRaisesRegexp(self.failureException,
-                                         expected_regexp=expected_regexp):
+            with self.assertRaisesRegex(self.failureException,
+                                        expected_regex=expected_regex):
                 testMethod(*args, **kwargs)
 
     def testAssertTrue(self):
         self.assertMessages('assertTrue', (False,),
-                            ["^False is not True$", "^oops$", "^False is not True$",
-                             "^False is not True : oops$"])
+                            ["^False is not true$", "^oops$", "^False is not true$",
+                             "^False is not true : oops$"])
 
     def testAssertFalse(self):
         self.assertMessages('assertFalse', (True,),
-                            ["^True is not False$", "^oops$", "^True is not False$",
-                             "^True is not False : oops$"])
+                            ["^True is not false$", "^oops$", "^True is not false$",
+                             "^True is not false : oops$"])
 
     def testNotEqual(self):
         self.assertMessages('assertNotEqual', (1, 1),
@@ -223,18 +223,6 @@
                              "\+ \{'key': 'value'\}$",
                              "\+ \{'key': 'value'\} : oops$"])
 
-    def testAssertDictContainsSubset(self):
-        self.assertMessages('assertDictContainsSubset', ({'key': 'value'}, {}),
-                            ["^Missing: 'key'$", "^oops$",
-                             "^Missing: 'key'$",
-                             "^Missing: 'key' : oops$"])
-
-    def testAssertItemsEqual(self):
-        self.assertMessages('assertItemsEqual', ([], [None]),
-                            [r"\[None\]$", "^oops$",
-                             r"\[None\]$",
-                             r"\[None\] : oops$"])
-
     def testAssertMultiLineEqual(self):
         self.assertMessages('assertMultiLineEqual', ("", "foo"),
                             [r"\+ foo$", "^oops$",

Modified: python/branches/pep-3151/Lib/unittest/test/test_break.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_break.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_break.py	Sat Feb 26 08:16:32 2011
@@ -209,7 +209,8 @@
 
         self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None,
                                                      'verbosity': verbosity,
-                                                     'failfast': failfast})])
+                                                     'failfast': failfast,
+                                                     'warnings': None})])
         self.assertEqual(FakeRunner.runArgs, [test])
         self.assertEqual(p.result, result)
 
@@ -222,7 +223,8 @@
 
         self.assertEqual(FakeRunner.initArgs, [((), {'buffer': None,
                                                      'verbosity': verbosity,
-                                                     'failfast': failfast})])
+                                                     'failfast': failfast,
+                                                     'warnings': None})])
         self.assertEqual(FakeRunner.runArgs, [test])
         self.assertEqual(p.result, result)
 

Modified: python/branches/pep-3151/Lib/unittest/test/test_case.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_case.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_case.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,6 @@
 import difflib
 import pprint
+import pickle
 import re
 import sys
 import warnings
@@ -76,6 +77,16 @@
 
         self.assertEqual(Test().id()[-13:], '.Test.runTest')
 
+        # test that TestCase can be instantiated with no args
+        # primarily for use at the interactive interpreter
+        test = unittest.TestCase()
+        test.assertEqual(3, 3)
+        with test.assertRaises(test.failureException):
+            test.assertEqual(3, 2)
+
+        with self.assertRaises(AttributeError):
+            test.run()
+
     # "class TestCase([methodName])"
     # ...
     # "Each instance of TestCase will run a single test method: the
@@ -176,8 +187,8 @@
                 super(Foo, self).test()
                 raise RuntimeError('raised by Foo.test')
 
-        expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
-                    'stopTest']
+        expected = ['startTest', 'setUp', 'test', 'tearDown',
+                    'addError', 'stopTest']
         Foo(events).run(result)
         self.assertEqual(events, expected)
 
@@ -194,8 +205,8 @@
                 super(Foo, self).test()
                 raise RuntimeError('raised by Foo.test')
 
-        expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addError',
-                    'tearDown', 'stopTest', 'stopTestRun']
+        expected = ['startTestRun', 'startTest', 'setUp', 'test',
+                    'tearDown', 'addError', 'stopTest', 'stopTestRun']
         Foo(events).run()
         self.assertEqual(events, expected)
 
@@ -215,8 +226,8 @@
                 super(Foo, self).test()
                 self.fail('raised by Foo.test')
 
-        expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
-                    'stopTest']
+        expected = ['startTest', 'setUp', 'test', 'tearDown',
+                    'addFailure', 'stopTest']
         Foo(events).run(result)
         self.assertEqual(events, expected)
 
@@ -230,8 +241,8 @@
                 super(Foo, self).test()
                 self.fail('raised by Foo.test')
 
-        expected = ['startTestRun', 'startTest', 'setUp', 'test', 'addFailure',
-                    'tearDown', 'stopTest', 'stopTestRun']
+        expected = ['startTestRun', 'startTest', 'setUp', 'test',
+                    'tearDown', 'addFailure', 'stopTest', 'stopTestRun']
         events = []
         Foo(events).run()
         self.assertEqual(events, expected)
@@ -477,33 +488,6 @@
         self.assertRaises(self.failureException, self.assertNotIn, 'cow',
                           animals)
 
-    def testAssertDictContainsSubset(self):
-        self.assertDictContainsSubset({}, {})
-        self.assertDictContainsSubset({}, {'a': 1})
-        self.assertDictContainsSubset({'a': 1}, {'a': 1})
-        self.assertDictContainsSubset({'a': 1}, {'a': 1, 'b': 2})
-        self.assertDictContainsSubset({'a': 1, 'b': 2}, {'a': 1, 'b': 2})
-
-        with self.assertRaises(self.failureException):
-            self.assertDictContainsSubset({1: "one"}, {})
-
-        with self.assertRaises(self.failureException):
-            self.assertDictContainsSubset({'a': 2}, {'a': 1})
-
-        with self.assertRaises(self.failureException):
-            self.assertDictContainsSubset({'c': 1}, {'a': 1})
-
-        with self.assertRaises(self.failureException):
-            self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
-
-        with self.assertRaises(self.failureException):
-            self.assertDictContainsSubset({'a': 1, 'c': 1}, {'a': 1})
-
-        one = ''.join(chr(i) for i in range(255))
-        # this used to cause a UnicodeDecodeError constructing the failure msg
-        with self.assertRaises(self.failureException):
-            self.assertDictContainsSubset({'foo': one}, {'foo': '\uFFFD'})
-
     def testAssertEqual(self):
         equal_pairs = [
                 ((), ()),
@@ -671,46 +655,68 @@
         else:
             self.fail('assertMultiLineEqual did not fail')
 
-    def testAssertItemsEqual(self):
+    def testAssertCountEqual(self):
         a = object()
-        self.assertItemsEqual([1, 2, 3], [3, 2, 1])
-        self.assertItemsEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
-        self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
-        self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertCountEqual([1, 2, 3], [3, 2, 1])
+        self.assertCountEqual(['foo', 'bar', 'baz'], ['bar', 'baz', 'foo'])
+        self.assertCountEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
+        self.assertCountEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [1, 2] + [3] * 100, [1] * 100 + [2, 3])
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [1, "2", "a", "a"], ["a", "2", True, 1])
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [10], [10, 11])
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [10, 11], [10])
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [10, 11, 10], [10, 11])
 
         # Test that sequences of unhashable objects can be tested for sameness:
-        self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
+        self.assertCountEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
+        # Test that iterator of unhashable objects can be tested for sameness:
+        self.assertCountEqual(iter([1, 2, [], 3, 4]),
+                              iter([1, 2, [], 3, 4]))
 
         # hashable types, but not orderable
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [], [divmod, 'x', 1, 5j, 2j, frozenset()])
         # comparing dicts
-        self.assertItemsEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
+        self.assertCountEqual([{'a': 1}, {'b': 2}], [{'b': 2}, {'a': 1}])
         # comparing heterogenous non-hashable sequences
-        self.assertItemsEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertCountEqual([1, 'x', divmod, []], [divmod, [], 'x', 1])
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [], [divmod, [], 'x', 1, 5j, 2j, set()])
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [[1]], [[2]])
 
         # Same elements, but not same sequence length
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [1, 1, 2], [2, 1])
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
-        self.assertRaises(self.failureException, self.assertItemsEqual,
+        self.assertRaises(self.failureException, self.assertCountEqual,
                           [1, {'b': 2}, None, True], [{'b': 2}, True, None])
 
+        # Same elements which don't reliably compare, in
+        # different order, see issue 10242
+        a = [{2,4}, {1,2}]
+        b = a[::-1]
+        self.assertCountEqual(a, b)
+
+        # test utility functions supporting assertCountEqual()
+
+        diffs = set(unittest.util._count_diff_all_purpose('aaabccd', 'abbbcce'))
+        expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')}
+        self.assertEqual(diffs, expected)
+
+        diffs = unittest.util._count_diff_all_purpose([[]], [])
+        self.assertEqual(diffs, [(1, 0, [])])
+
+        diffs = set(unittest.util._count_diff_hashable('aaabccd', 'abbbcce'))
+        expected = {(3,1,'a'), (1,3,'b'), (1,0,'d'), (0,1,'e')}
+        self.assertEqual(diffs, expected)
+
     def testAssertSetEqual(self):
         set1 = set()
         set2 = set()
@@ -864,44 +870,44 @@
         self.assertIsNotNone('DjZoPloGears on Rails')
         self.assertRaises(self.failureException, self.assertIsNotNone, None)
 
-    def testAssertRegexpMatches(self):
-        self.assertRegexpMatches('asdfabasdf', r'ab+')
-        self.assertRaises(self.failureException, self.assertRegexpMatches,
+    def testAssertRegex(self):
+        self.assertRegex('asdfabasdf', r'ab+')
+        self.assertRaises(self.failureException, self.assertRegex,
                           'saaas', r'aaaa')
 
-    def testAssertRaisesRegexp(self):
+    def testAssertRaisesRegex(self):
         class ExceptionMock(Exception):
             pass
 
         def Stub():
             raise ExceptionMock('We expect')
 
-        self.assertRaisesRegexp(ExceptionMock, re.compile('expect$'), Stub)
-        self.assertRaisesRegexp(ExceptionMock, 'expect$', Stub)
+        self.assertRaisesRegex(ExceptionMock, re.compile('expect$'), Stub)
+        self.assertRaisesRegex(ExceptionMock, 'expect$', Stub)
 
-    def testAssertNotRaisesRegexp(self):
-        self.assertRaisesRegexp(
+    def testAssertNotRaisesRegex(self):
+        self.assertRaisesRegex(
                 self.failureException, '^Exception not raised by <lambda>$',
-                self.assertRaisesRegexp, Exception, re.compile('x'),
+                self.assertRaisesRegex, Exception, re.compile('x'),
                 lambda: None)
-        self.assertRaisesRegexp(
+        self.assertRaisesRegex(
                 self.failureException, '^Exception not raised by <lambda>$',
-                self.assertRaisesRegexp, Exception, 'x',
+                self.assertRaisesRegex, Exception, 'x',
                 lambda: None)
 
-    def testAssertRaisesRegexpMismatch(self):
+    def testAssertRaisesRegexMismatch(self):
         def Stub():
             raise Exception('Unexpected')
 
-        self.assertRaisesRegexp(
+        self.assertRaisesRegex(
                 self.failureException,
                 r'"\^Expected\$" does not match "Unexpected"',
-                self.assertRaisesRegexp, Exception, '^Expected$',
+                self.assertRaisesRegex, Exception, '^Expected$',
                 Stub)
-        self.assertRaisesRegexp(
+        self.assertRaisesRegex(
                 self.failureException,
                 r'"\^Expected\$" does not match "Unexpected"',
-                self.assertRaisesRegexp, Exception,
+                self.assertRaisesRegex, Exception,
                 re.compile('^Expected$'), Stub)
 
     def testAssertRaisesExcValue(self):
@@ -985,26 +991,26 @@
                 with self.assertWarns(DeprecationWarning):
                     _runtime_warn()
 
-    def testAssertWarnsRegexpCallable(self):
+    def testAssertWarnsRegexCallable(self):
         def _runtime_warn(msg):
             warnings.warn(msg, RuntimeWarning)
-        self.assertWarnsRegexp(RuntimeWarning, "o+",
-                               _runtime_warn, "foox")
+        self.assertWarnsRegex(RuntimeWarning, "o+",
+                              _runtime_warn, "foox")
         # Failure when no warning is triggered
         with self.assertRaises(self.failureException):
-            self.assertWarnsRegexp(RuntimeWarning, "o+",
-                                   lambda: 0)
+            self.assertWarnsRegex(RuntimeWarning, "o+",
+                                  lambda: 0)
         # Failure when another warning is triggered
         with warnings.catch_warnings():
             # Force default filter (in case tests are run with -We)
             warnings.simplefilter("default", RuntimeWarning)
             with self.assertRaises(self.failureException):
-                self.assertWarnsRegexp(DeprecationWarning, "o+",
-                                       _runtime_warn, "foox")
+                self.assertWarnsRegex(DeprecationWarning, "o+",
+                                      _runtime_warn, "foox")
         # Failure when message doesn't match
         with self.assertRaises(self.failureException):
-            self.assertWarnsRegexp(RuntimeWarning, "o+",
-                                   _runtime_warn, "barz")
+            self.assertWarnsRegex(RuntimeWarning, "o+",
+                                  _runtime_warn, "barz")
         # A little trickier: we ask RuntimeWarnings to be raised, and then
         # check for some of them.  It is implementation-defined whether
         # non-matching RuntimeWarnings are simply re-raised, or produce a
@@ -1012,15 +1018,15 @@
         with warnings.catch_warnings():
             warnings.simplefilter("error", RuntimeWarning)
             with self.assertRaises((RuntimeWarning, self.failureException)):
-                self.assertWarnsRegexp(RuntimeWarning, "o+",
-                                       _runtime_warn, "barz")
+                self.assertWarnsRegex(RuntimeWarning, "o+",
+                                      _runtime_warn, "barz")
 
-    def testAssertWarnsRegexpContext(self):
-        # Same as above, but with assertWarnsRegexp as a context manager
+    def testAssertWarnsRegexContext(self):
+        # Same as above, but with assertWarnsRegex as a context manager
         def _runtime_warn(msg):
             warnings.warn(msg, RuntimeWarning)
         _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1]
-        with self.assertWarnsRegexp(RuntimeWarning, "o+") as cm:
+        with self.assertWarnsRegex(RuntimeWarning, "o+") as cm:
             _runtime_warn("foox")
         self.assertIsInstance(cm.warning, RuntimeWarning)
         self.assertEqual(cm.warning.args[0], "foox")
@@ -1028,18 +1034,18 @@
         self.assertEqual(cm.lineno, _runtime_warn_lineno + 1)
         # Failure when no warning is triggered
         with self.assertRaises(self.failureException):
-            with self.assertWarnsRegexp(RuntimeWarning, "o+"):
+            with self.assertWarnsRegex(RuntimeWarning, "o+"):
                 pass
         # Failure when another warning is triggered
         with warnings.catch_warnings():
             # Force default filter (in case tests are run with -We)
             warnings.simplefilter("default", RuntimeWarning)
             with self.assertRaises(self.failureException):
-                with self.assertWarnsRegexp(DeprecationWarning, "o+"):
+                with self.assertWarnsRegex(DeprecationWarning, "o+"):
                     _runtime_warn("foox")
         # Failure when message doesn't match
         with self.assertRaises(self.failureException):
-            with self.assertWarnsRegexp(RuntimeWarning, "o+"):
+            with self.assertWarnsRegex(RuntimeWarning, "o+"):
                 _runtime_warn("barz")
         # A little trickier: we ask RuntimeWarnings to be raised, and then
         # check for some of them.  It is implementation-defined whether
@@ -1048,42 +1054,27 @@
         with warnings.catch_warnings():
             warnings.simplefilter("error", RuntimeWarning)
             with self.assertRaises((RuntimeWarning, self.failureException)):
-                with self.assertWarnsRegexp(RuntimeWarning, "o+"):
+                with self.assertWarnsRegex(RuntimeWarning, "o+"):
                     _runtime_warn("barz")
 
-    def testSynonymAssertMethodNames(self):
-        """Test undocumented method name synonyms.
-
-        Please do not use these methods names in your own code.
-
-        This test confirms their continued existence and functionality
-        in order to avoid breaking existing code.
-        """
-        self.assertNotEquals(3, 5)
-        self.assertEquals(3, 3)
-        self.assertAlmostEquals(2.0, 2.0)
-        self.assertNotAlmostEquals(3.0, 5.0)
-        self.assert_(True)
-
-    def testPendingDeprecationMethodNames(self):
-        """Test fail* methods pending deprecation, they will warn in 3.2.
+    def testDeprecatedMethodNames(self):
+        """Test that the deprecated methods raise a DeprecationWarning.
 
-        Do not use these methods.  They will go away in 3.3.
+        The fail* methods will be removed in 3.3. The assert* methods will
+        have to stay around for a few more versions.  See #9424.
         """
         old = (
-            (self.failIfEqual, (3, 5)),
-            (self.failUnlessEqual, (3, 3)),
-            (self.failUnlessAlmostEqual, (2.0, 2.0)),
-            (self.failIfAlmostEqual, (3.0, 5.0)),
-            (self.failUnless, (True,)),
-            (self.failUnlessRaises, (TypeError, lambda _: 3.14 + 'spam')),
-            (self.failIf, (False,)),
-            (self.assertSameElements, ([1, 1, 2, 3], [1, 2, 3]))
+            (self.assertNotEquals, (3, 5)),
+            (self.assertEquals, (3, 3)),
+            (self.assertAlmostEquals, (2.0, 2.0)),
+            (self.assertNotAlmostEquals, (3.0, 5.0)),
+            (self.assert_, (True,)),
+            (self.assertRaisesRegexp, (KeyError, 'foo', lambda: {}['foo'])),
+            (self.assertRegexpMatches, ('bar', 'bar')),
         )
         for meth, args in old:
-            with support.check_warnings(('', DeprecationWarning)) as w:
+            with self.assertWarns(DeprecationWarning):
                 meth(*args)
-            self.assertEqual(len(w.warnings), 1)
 
     def testDeepcopy(self):
         # Issue: 5660
@@ -1095,3 +1086,99 @@
 
         # This shouldn't blow up
         deepcopy(test)
+
+    def testPickle(self):
+        # Issue 10326
+
+        # Can't use TestCase classes defined in Test class as
+        # pickle does not work with inner classes
+        test = unittest.TestCase('run')
+        for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
+
+            # blew up prior to fix
+            pickled_test = pickle.dumps(test, protocol=protocol)
+            unpickled_test = pickle.loads(pickled_test)
+            self.assertEqual(test, unpickled_test)
+
+            # exercise the TestCase instance in a way that will invoke
+            # the type equality lookup mechanism
+            unpickled_test.assertEqual(set(), set())
+
+    def testKeyboardInterrupt(self):
+        def _raise(self=None):
+            raise KeyboardInterrupt
+        def nothing(self):
+            pass
+
+        class Test1(unittest.TestCase):
+            test_something = _raise
+
+        class Test2(unittest.TestCase):
+            setUp = _raise
+            test_something = nothing
+
+        class Test3(unittest.TestCase):
+            test_something = nothing
+            tearDown = _raise
+
+        class Test4(unittest.TestCase):
+            def test_something(self):
+                self.addCleanup(_raise)
+
+        for klass in (Test1, Test2, Test3, Test4):
+            with self.assertRaises(KeyboardInterrupt):
+                klass('test_something').run()
+
+    def testSkippingEverywhere(self):
+        def _skip(self=None):
+            raise unittest.SkipTest('some reason')
+        def nothing(self):
+            pass
+
+        class Test1(unittest.TestCase):
+            test_something = _skip
+
+        class Test2(unittest.TestCase):
+            setUp = _skip
+            test_something = nothing
+
+        class Test3(unittest.TestCase):
+            test_something = nothing
+            tearDown = _skip
+
+        class Test4(unittest.TestCase):
+            def test_something(self):
+                self.addCleanup(_skip)
+
+        for klass in (Test1, Test2, Test3, Test4):
+            result = unittest.TestResult()
+            klass('test_something').run(result)
+            self.assertEqual(len(result.skipped), 1)
+            self.assertEqual(result.testsRun, 1)
+
+    def testSystemExit(self):
+        def _raise(self=None):
+            raise SystemExit
+        def nothing(self):
+            pass
+
+        class Test1(unittest.TestCase):
+            test_something = _raise
+
+        class Test2(unittest.TestCase):
+            setUp = _raise
+            test_something = nothing
+
+        class Test3(unittest.TestCase):
+            test_something = nothing
+            tearDown = _raise
+
+        class Test4(unittest.TestCase):
+            def test_something(self):
+                self.addCleanup(_raise)
+
+        for klass in (Test1, Test2, Test3, Test4):
+            result = unittest.TestResult()
+            klass('test_something').run(result)
+            self.assertEqual(len(result.errors), 1)
+            self.assertEqual(result.testsRun, 1)

Modified: python/branches/pep-3151/Lib/unittest/test/test_discovery.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_discovery.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_discovery.py	Sat Feb 26 08:16:32 2011
@@ -5,6 +5,18 @@
 import unittest
 
 
+class TestableTestProgram(unittest.TestProgram):
+    module = '__main__'
+    exit = True
+    defaultTest = failfast = catchbreak = buffer = None
+    verbosity = 1
+    progName = ''
+    testRunner = testLoader = None
+
+    def __init__(self):
+        pass
+
+
 class TestDiscovery(unittest.TestCase):
 
     # Heavily mocked tests so I can avoid hitting the filesystem
@@ -195,8 +207,7 @@
             test.test_this_does_not_exist()
 
     def test_command_line_handling_parseArgs(self):
-        # Haha - take that uninstantiable class
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
 
         args = []
         def do_discovery(argv):
@@ -208,13 +219,39 @@
         program.parseArgs(['something', 'discover', 'foo', 'bar'])
         self.assertEqual(args, ['foo', 'bar'])
 
+    def test_command_line_handling_discover_by_default(self):
+        program = TestableTestProgram()
+        program.module = None
+
+        self.called = False
+        def do_discovery(argv):
+            self.called = True
+            self.assertEqual(argv, [])
+        program._do_discovery = do_discovery
+        program.parseArgs(['something'])
+        self.assertTrue(self.called)
+
+    def test_command_line_handling_discover_by_default_with_options(self):
+        program = TestableTestProgram()
+        program.module = None
+
+        args = ['something', '-v', '-b', '-v', '-c', '-f']
+        self.called = False
+        def do_discovery(argv):
+            self.called = True
+            self.assertEqual(argv, args[1:])
+        program._do_discovery = do_discovery
+        program.parseArgs(args)
+        self.assertTrue(self.called)
+
+
     def test_command_line_handling_do_discovery_too_many_arguments(self):
         class Stop(Exception):
             pass
         def usageExit():
             raise Stop
 
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program.usageExit = usageExit
 
         with self.assertRaises(Stop):
@@ -223,7 +260,7 @@
 
 
     def test_command_line_handling_do_discovery_calls_loader(self):
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
 
         class Loader(object):
             args = []
@@ -237,49 +274,49 @@
         self.assertEqual(Loader.args, [('.', 'test*.py', None)])
 
         Loader.args = []
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program._do_discovery(['--verbose'], Loader=Loader)
         self.assertEqual(program.test, 'tests')
         self.assertEqual(Loader.args, [('.', 'test*.py', None)])
 
         Loader.args = []
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program._do_discovery([], Loader=Loader)
         self.assertEqual(program.test, 'tests')
         self.assertEqual(Loader.args, [('.', 'test*.py', None)])
 
         Loader.args = []
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program._do_discovery(['fish'], Loader=Loader)
         self.assertEqual(program.test, 'tests')
         self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
 
         Loader.args = []
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program._do_discovery(['fish', 'eggs'], Loader=Loader)
         self.assertEqual(program.test, 'tests')
         self.assertEqual(Loader.args, [('fish', 'eggs', None)])
 
         Loader.args = []
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program._do_discovery(['fish', 'eggs', 'ham'], Loader=Loader)
         self.assertEqual(program.test, 'tests')
         self.assertEqual(Loader.args, [('fish', 'eggs', 'ham')])
 
         Loader.args = []
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program._do_discovery(['-s', 'fish'], Loader=Loader)
         self.assertEqual(program.test, 'tests')
         self.assertEqual(Loader.args, [('fish', 'test*.py', None)])
 
         Loader.args = []
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program._do_discovery(['-t', 'fish'], Loader=Loader)
         self.assertEqual(program.test, 'tests')
         self.assertEqual(Loader.args, [('.', 'test*.py', 'fish')])
 
         Loader.args = []
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program._do_discovery(['-p', 'fish'], Loader=Loader)
         self.assertEqual(program.test, 'tests')
         self.assertEqual(Loader.args, [('.', 'fish', None)])
@@ -287,7 +324,7 @@
         self.assertFalse(program.catchbreak)
 
         Loader.args = []
-        program = object.__new__(unittest.TestProgram)
+        program = TestableTestProgram()
         program._do_discovery(['-p', 'eggs', '-s', 'fish', '-v', '-f', '-c'],
                               Loader=Loader)
         self.assertEqual(program.test, 'tests')
@@ -330,7 +367,7 @@
         expected_dir = os.path.abspath('foo')
         msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. "
                 "Is this module globally installed?" % (mod_dir, expected_dir))
-        self.assertRaisesRegexp(
+        self.assertRaisesRegex(
             ImportError, '^%s$' % msg, loader.discover,
             start_dir='foo', pattern='foo.py'
         )

Modified: python/branches/pep-3151/Lib/unittest/test/test_functiontestcase.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_functiontestcase.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_functiontestcase.py	Sat Feb 26 08:16:32 2011
@@ -58,8 +58,8 @@
         def tearDown():
             events.append('tearDown')
 
-        expected = ['startTest', 'setUp', 'test', 'addError', 'tearDown',
-                    'stopTest']
+        expected = ['startTest', 'setUp', 'test', 'tearDown',
+                    'addError', 'stopTest']
         unittest.FunctionTestCase(test, setUp, tearDown).run(result)
         self.assertEqual(events, expected)
 
@@ -84,8 +84,8 @@
         def tearDown():
             events.append('tearDown')
 
-        expected = ['startTest', 'setUp', 'test', 'addFailure', 'tearDown',
-                    'stopTest']
+        expected = ['startTest', 'setUp', 'test', 'tearDown',
+                    'addFailure', 'stopTest']
         unittest.FunctionTestCase(test, setUp, tearDown).run(result)
         self.assertEqual(events, expected)
 

Modified: python/branches/pep-3151/Lib/unittest/test/test_loader.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_loader.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_loader.py	Sat Feb 26 08:16:32 2011
@@ -167,11 +167,11 @@
         loader = unittest.TestLoader()
         suite = loader.loadTestsFromModule(m)
         self.assertIsInstance(suite, unittest.TestSuite)
-        self.assertEquals(load_tests_args, [loader, suite, None])
+        self.assertEqual(load_tests_args, [loader, suite, None])
 
         load_tests_args = []
         suite = loader.loadTestsFromModule(m, use_load_tests=False)
-        self.assertEquals(load_tests_args, [])
+        self.assertEqual(load_tests_args, [])
 
     def test_loadTestsFromModule__faulty_load_tests(self):
         m = types.ModuleType('m')
@@ -186,7 +186,7 @@
         self.assertEqual(suite.countTestCases(), 1)
         test = list(suite)[0]
 
-        self.assertRaisesRegexp(TypeError, "some failure", test.m)
+        self.assertRaisesRegex(TypeError, "some failure", test.m)
 
     ################################################################
     ### /Tests for TestLoader.loadTestsFromModule()

Modified: python/branches/pep-3151/Lib/unittest/test/test_program.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_program.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_program.py	Sat Feb 26 08:16:32 2011
@@ -99,6 +99,7 @@
     defaultTest = None
     testRunner = None
     testLoader = unittest.defaultTestLoader
+    module = '__main__'
     progName = 'test'
     test = 'test'
     def __init__(self, *args):
@@ -182,6 +183,27 @@
                 program.parseArgs([None, opt])
                 self.assertEqual(getattr(program, attr), not_none)
 
+    def testWarning(self):
+        """Test the warnings argument"""
+        # see #10535
+        class FakeTP(unittest.TestProgram):
+            def parseArgs(self, *args, **kw): pass
+            def runTests(self, *args, **kw): pass
+        warnoptions = sys.warnoptions
+        try:
+            sys.warnoptions[:] = []
+            # no warn options, no arg -> default
+            self.assertEqual(FakeTP().warnings, 'default')
+            # no warn options, w/ arg -> arg value
+            self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')
+            sys.warnoptions[:] = ['somevalue']
+            # warn options, no arg -> None
+            # warn options, w/ arg -> arg value
+            self.assertEqual(FakeTP().warnings, None)
+            self.assertEqual(FakeTP(warnings='ignore').warnings, 'ignore')
+        finally:
+            sys.warnoptions[:] = warnoptions
+
     def testRunTestsRunnerClass(self):
         program = self.program
 
@@ -189,12 +211,14 @@
         program.verbosity = 'verbosity'
         program.failfast = 'failfast'
         program.buffer = 'buffer'
+        program.warnings = 'warnings'
 
         program.runTests()
 
         self.assertEqual(FakeRunner.initArgs, {'verbosity': 'verbosity',
                                                 'failfast': 'failfast',
-                                                'buffer': 'buffer'})
+                                                'buffer': 'buffer',
+                                                'warnings': 'warnings'})
         self.assertEqual(FakeRunner.test, 'test')
         self.assertIs(program.result, RESULT)
 
@@ -250,6 +274,85 @@
         program.runTests()
         self.assertTrue(self.installed)
 
+    def _patch_isfile(self, names, exists=True):
+        def isfile(path):
+            return path in names
+        original = os.path.isfile
+        os.path.isfile = isfile
+        def restore():
+            os.path.isfile = original
+        self.addCleanup(restore)
+
+
+    def testParseArgsFileNames(self):
+        # running tests with filenames instead of module names
+        program = self.program
+        argv = ['progname', 'foo.py', 'bar.Py', 'baz.PY', 'wing.txt']
+        self._patch_isfile(argv)
+
+        program.createTests = lambda: None
+        program.parseArgs(argv)
+
+        # note that 'wing.txt' is not a Python file so the name should
+        # *not* be converted to a module name
+        expected = ['foo', 'bar', 'baz', 'wing.txt']
+        self.assertEqual(program.testNames, expected)
+
+
+    def testParseArgsFilePaths(self):
+        program = self.program
+        argv = ['progname', 'foo/bar/baz.py', 'green\\red.py']
+        self._patch_isfile(argv)
+
+        program.createTests = lambda: None
+        program.parseArgs(argv)
+
+        expected = ['foo.bar.baz', 'green.red']
+        self.assertEqual(program.testNames, expected)
+
+
+    def testParseArgsNonExistentFiles(self):
+        program = self.program
+        argv = ['progname', 'foo/bar/baz.py', 'green\\red.py']
+        self._patch_isfile([])
+
+        program.createTests = lambda: None
+        program.parseArgs(argv)
+
+        self.assertEqual(program.testNames, argv[1:])
+
+    def testParseArgsAbsolutePathsThatCanBeConverted(self):
+        cur_dir = os.getcwd()
+        program = self.program
+        def _join(name):
+            return os.path.join(cur_dir, name)
+        argv = ['progname', _join('foo/bar/baz.py'), _join('green\\red.py')]
+        self._patch_isfile(argv)
+
+        program.createTests = lambda: None
+        program.parseArgs(argv)
+
+        expected = ['foo.bar.baz', 'green.red']
+        self.assertEqual(program.testNames, expected)
+
+    def testParseArgsAbsolutePathsThatCannotBeConverted(self):
+        program = self.program
+        # even on Windows '/...' is considered absolute by os.path.abspath
+        argv = ['progname', '/foo/bar/baz.py', '/green/red.py']
+        self._patch_isfile(argv)
+
+        program.createTests = lambda: None
+        program.parseArgs(argv)
+
+        self.assertEqual(program.testNames, argv[1:])
+
+        # it may be better to use platform specific functions to normalise paths
+        # rather than accepting '.PY' and '\' as file seprator on Linux / Mac
+        # it would also be better to check that a filename is a valid module
+        # identifier (we have a regex for this in loader.py)
+        # for invalid filenames should we raise a useful error rather than
+        # leaving the current error message (import of filename fails) in place?
+
 
 if __name__ == '__main__':
     unittest.main()

Modified: python/branches/pep-3151/Lib/unittest/test/test_runner.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_runner.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_runner.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,8 @@
 import io
+import os
+import sys
 import pickle
+import subprocess
 
 import unittest
 
@@ -31,9 +34,7 @@
                          [(cleanup1, (1, 2, 3), dict(four='hello', five='goodbye')),
                           (cleanup2, (), {})])
 
-        result = test.doCleanups()
-        self.assertTrue(result)
-
+        self.assertTrue(test.doCleanups())
         self.assertEqual(cleanups, [(2, (), {}), (1, (1, 2, 3), dict(four='hello', five='goodbye'))])
 
     def testCleanUpWithErrors(self):
@@ -41,14 +42,12 @@
             def testNothing(self):
                 pass
 
-        class MockResult(object):
+        class MockOutcome(object):
+            success = True
             errors = []
-            def addError(self, test, exc_info):
-                self.errors.append((test, exc_info))
 
-        result = MockResult()
         test = TestableTest('testNothing')
-        test._resultForDoCleanups = result
+        test._outcomeForDoCleanups = MockOutcome
 
         exc1 = Exception('foo')
         exc2 = Exception('bar')
@@ -62,10 +61,11 @@
         test.addCleanup(cleanup2)
 
         self.assertFalse(test.doCleanups())
+        self.assertFalse(MockOutcome.success)
 
-        (test1, (Type1, instance1, _)), (test2, (Type2, instance2, _)) = reversed(MockResult.errors)
-        self.assertEqual((test1, Type1, instance1), (test, Exception, exc1))
-        self.assertEqual((test2, Type2, instance2), (test, Exception, exc2))
+        (Type1, instance1, _), (Type2, instance2, _) = reversed(MockOutcome.errors)
+        self.assertEqual((Type1, instance1), (Exception, exc1))
+        self.assertEqual((Type2, instance2), (Exception, exc2))
 
     def testCleanupInRun(self):
         blowUp = False
@@ -144,6 +144,7 @@
         self.assertFalse(runner.failfast)
         self.assertFalse(runner.buffer)
         self.assertEqual(runner.verbosity, 1)
+        self.assertEqual(runner.warnings, None)
         self.assertTrue(runner.descriptions)
         self.assertEqual(runner.resultclass, unittest.TextTestResult)
 
@@ -244,3 +245,70 @@
 
         expectedresult = (runner.stream, DESCRIPTIONS, VERBOSITY)
         self.assertEqual(runner._makeResult(), expectedresult)
+
+    def test_warnings(self):
+        """
+        Check that warnings argument of TextTestRunner correctly affects the
+        behavior of the warnings.
+        """
+        # see #10535 and the _test_warnings file for more information
+
+        def get_parse_out_err(p):
+            return [b.splitlines() for b in p.communicate()]
+        opts = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE,
+                    cwd=os.path.dirname(__file__))
+
+        # no args -> all the warnings are printed, unittest warnings only once
+        p = subprocess.Popen([sys.executable, '_test_warnings.py'], **opts)
+        out, err = get_parse_out_err(p)
+        self.assertIn(b'OK', err)
+        # check that the total number of warnings in the output is correct
+        self.assertEqual(len(out), 11)
+        # check that the numbers of the different kind of warnings is correct
+        for msg in [b'dw', b'iw', b'uw']:
+            self.assertEqual(out.count(msg), 3)
+        for msg in [b'rw']:
+            self.assertEqual(out.count(msg), 1)
+
+        args_list = (
+            # passing 'ignore' as warnings arg -> no warnings
+            [sys.executable, '_test_warnings.py', 'ignore'],
+            # -W doesn't affect the result if the arg is passed
+            [sys.executable, '-Wa', '_test_warnings.py', 'ignore'],
+            # -W affects the result if the arg is not passed
+            [sys.executable, '-Wi', '_test_warnings.py']
+        )
+        # in all these cases no warnings are printed
+        for args in args_list:
+            p = subprocess.Popen(args, **opts)
+            out, err = get_parse_out_err(p)
+            self.assertIn(b'OK', err)
+            self.assertEqual(len(out), 0)
+
+
+        # passing 'always' as warnings arg -> all the warnings printed,
+        #                                     unittest warnings only once
+        p = subprocess.Popen([sys.executable, '_test_warnings.py', 'always'],
+                             **opts)
+        out, err = get_parse_out_err(p)
+        self.assertIn(b'OK', err)
+        self.assertEqual(len(out), 13)
+        for msg in [b'dw', b'iw', b'uw', b'rw']:
+            self.assertEqual(out.count(msg), 3)
+
+    def testStdErrLookedUpAtInstantiationTime(self):
+        # see issue 10786
+        old_stderr = sys.stderr
+        f = io.StringIO()
+        sys.stderr = f
+        try:
+            runner = unittest.TextTestRunner()
+            self.assertTrue(runner.stream.stream is f)
+        finally:
+            sys.stderr = old_stderr
+
+    def testSpecifiedStreamUsed(self):
+        # see issue 10786
+        f = io.StringIO()
+        runner = unittest.TextTestRunner(f)
+        self.assertTrue(runner.stream.stream is f)

Modified: python/branches/pep-3151/Lib/unittest/test/test_setups.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_setups.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_setups.py	Sat Feb 26 08:16:32 2011
@@ -500,7 +500,7 @@
 
         messages = ('setUpModule', 'tearDownModule', 'setUpClass', 'tearDownClass', 'test_something')
         for phase, msg in enumerate(messages):
-            with self.assertRaisesRegexp(Exception, msg):
+            with self.assertRaisesRegex(Exception, msg):
                 suite.debug()
 
 if __name__ == '__main__':

Modified: python/branches/pep-3151/Lib/unittest/test/test_suite.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/test/test_suite.py	(original)
+++ python/branches/pep-3151/Lib/unittest/test/test_suite.py	Sat Feb 26 08:16:32 2011
@@ -353,11 +353,16 @@
                 unittest.TestSuite.__call__(self, *args, **kw)
 
         suite = MySuite()
+        result = unittest.TestResult()
         wrapper = unittest.TestSuite()
         wrapper.addTest(suite)
-        wrapper(unittest.TestResult())
+        wrapper(result)
         self.assertTrue(suite.called)
 
+        # reusing results should be permitted even if abominable
+        self.assertFalse(result._testRunEntered)
+
+
 
 if __name__ == '__main__':
     unittest.main()

Modified: python/branches/pep-3151/Lib/unittest/util.py
==============================================================================
--- python/branches/pep-3151/Lib/unittest/util.py	(original)
+++ python/branches/pep-3151/Lib/unittest/util.py	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,7 @@
 """Various utility functions."""
 
+from collections import namedtuple, OrderedDict
+
 __unittest = True
 
 _MAX_LENGTH = 80
@@ -12,7 +14,6 @@
         return result
     return result[:_MAX_LENGTH] + ' [truncated]...'
 
-
 def strclass(cls):
     return "%s.%s" % (cls.__module__, cls.__name__)
 
@@ -77,3 +78,63 @@
 def three_way_cmp(x, y):
     """Return -1 if x < y, 0 if x == y and 1 if x > y"""
     return (x > y) - (x < y)
+
+_Mismatch = namedtuple('Mismatch', 'actual expected value')
+
+def _count_diff_all_purpose(actual, expected):
+    'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ'
+    # elements need not be hashable
+    s, t = list(actual), list(expected)
+    m, n = len(s), len(t)
+    NULL = object()
+    result = []
+    for i, elem in enumerate(s):
+        if elem is NULL:
+            continue
+        cnt_s = cnt_t = 0
+        for j in range(i, m):
+            if s[j] == elem:
+                cnt_s += 1
+                s[j] = NULL
+        for j, other_elem in enumerate(t):
+            if other_elem == elem:
+                cnt_t += 1
+                t[j] = NULL
+        if cnt_s != cnt_t:
+            diff = _Mismatch(cnt_s, cnt_t, elem)
+            result.append(diff)
+
+    for i, elem in enumerate(t):
+        if elem is NULL:
+            continue
+        cnt_t = 0
+        for j in range(i, n):
+            if t[j] == elem:
+                cnt_t += 1
+                t[j] = NULL
+        diff = _Mismatch(0, cnt_t, elem)
+        result.append(diff)
+    return result
+
+def _ordered_count(iterable):
+    'Return dict of element counts, in the order they were first seen'
+    c = OrderedDict()
+    for elem in iterable:
+        c[elem] = c.get(elem, 0) + 1
+    return c
+
+def _count_diff_hashable(actual, expected):
+    'Returns list of (cnt_act, cnt_exp, elem) triples where the counts differ'
+    # elements must be hashable
+    s, t = _ordered_count(actual), _ordered_count(expected)
+    result = []
+    for elem, cnt_s in s.items():
+        cnt_t = t.get(elem, 0)
+        if cnt_s != cnt_t:
+            diff = _Mismatch(cnt_s, cnt_t, elem)
+            result.append(diff)
+    for elem, cnt_t in t.items():
+        if elem not in s:
+            diff = _Mismatch(0, cnt_t, elem)
+            result.append(diff)
+    return result

Modified: python/branches/pep-3151/Lib/urllib/parse.py
==============================================================================
--- python/branches/pep-3151/Lib/urllib/parse.py	(original)
+++ python/branches/pep-3151/Lib/urllib/parse.py	Sat Feb 26 08:16:32 2011
@@ -11,7 +11,7 @@
 RFC 2396:  "Uniform Resource Identifiers (URI)": Generic Syntax by T.
 Berners-Lee, R. Fielding, and L. Masinter, August 1998.
 
-RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zwinski, July 1998.
+RFC 2368: "The mailto URL scheme", by P.Hoffman , L Masinter, J. Zawinski, July 1998.
 
 RFC 1808: "Relative Uniform Resource Locators", by R. Fielding, UC Irvine, June
 1995.
@@ -60,6 +60,7 @@
                 '0123456789'
                 '+-.')
 
+# XXX: Consider replacing with functools.lru_cache
 MAX_CACHE_SIZE = 20
 _parse_cache = {}
 
@@ -69,66 +70,210 @@
     _safe_quoters.clear()
 
 
-class ResultMixin(object):
-    """Shared methods for the parsed result objects."""
+# Helpers for bytes handling
+# For 3.2, we deliberately require applications that
+# handle improperly quoted URLs to do their own
+# decoding and encoding. If valid use cases are
+# presented, we may relax this by using latin-1
+# decoding internally for 3.3
+_implicit_encoding = 'ascii'
+_implicit_errors = 'strict'
+
+def _noop(obj):
+    return obj
+
+def _encode_result(obj, encoding=_implicit_encoding,
+                        errors=_implicit_errors):
+    return obj.encode(encoding, errors)
+
+def _decode_args(args, encoding=_implicit_encoding,
+                       errors=_implicit_errors):
+    return tuple(x.decode(encoding, errors) if x else '' for x in args)
+
+def _coerce_args(*args):
+    # Invokes decode if necessary to create str args
+    # and returns the coerced inputs along with
+    # an appropriate result coercion function
+    #   - noop for str inputs
+    #   - encoding function otherwise
+    str_input = isinstance(args[0], str)
+    for arg in args[1:]:
+        # We special-case the empty string to support the
+        # "scheme=''" default argument to some functions
+        if arg and isinstance(arg, str) != str_input:
+            raise TypeError("Cannot mix str and non-str arguments")
+    if str_input:
+        return args + (_noop,)
+    return _decode_args(args) + (_encode_result,)
+
+# Result objects are more helpful than simple tuples
+class _ResultMixinStr(object):
+    """Standard approach to encoding parsed results from str to bytes"""
+    __slots__ = ()
+
+    def encode(self, encoding='ascii', errors='strict'):
+        return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self))
+
+
+class _ResultMixinBytes(object):
+    """Standard approach to decoding parsed results from bytes to str"""
+    __slots__ = ()
+
+    def decode(self, encoding='ascii', errors='strict'):
+        return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self))
+
+
+class _NetlocResultMixinBase(object):
+    """Shared methods for the parsed result objects containing a netloc element"""
+    __slots__ = ()
 
     @property
     def username(self):
-        netloc = self.netloc
-        if "@" in netloc:
-            userinfo = netloc.rsplit("@", 1)[0]
-            if ":" in userinfo:
-                userinfo = userinfo.split(":", 1)[0]
-            return userinfo
-        return None
+        return self._userinfo[0]
 
     @property
     def password(self):
-        netloc = self.netloc
-        if "@" in netloc:
-            userinfo = netloc.rsplit("@", 1)[0]
-            if ":" in userinfo:
-                return userinfo.split(":", 1)[1]
-        return None
+        return self._userinfo[1]
 
     @property
     def hostname(self):
-        netloc = self.netloc.split('@')[-1]
-        if '[' in netloc and ']' in netloc:
-            return netloc.split(']')[0][1:].lower()
-        elif ':' in netloc:
-            return netloc.split(':')[0].lower()
-        elif netloc == '':
-            return None
-        else:
-            return netloc.lower()
+        hostname = self._hostinfo[0]
+        if not hostname:
+            hostname = None
+        elif hostname is not None:
+            hostname = hostname.lower()
+        return hostname
 
     @property
     def port(self):
-        netloc = self.netloc.split('@')[-1].split(']')[-1]
-        if ':' in netloc:
-            port = netloc.split(':')[1]
-            return int(port, 10)
+        port = self._hostinfo[1]
+        if port is not None:
+            port = int(port, 10)
+        return port
+
+
+class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr):
+    __slots__ = ()
+
+    @property
+    def _userinfo(self):
+        netloc = self.netloc
+        userinfo, have_info, hostinfo = netloc.rpartition('@')
+        if have_info:
+            username, have_password, password = userinfo.partition(':')
+            if not have_password:
+                password = None
+        else:
+            username = password = None
+        return username, password
+
+    @property
+    def _hostinfo(self):
+        netloc = self.netloc
+        _, _, hostinfo = netloc.rpartition('@')
+        _, have_open_br, bracketed = hostinfo.partition('[')
+        if have_open_br:
+            hostname, _, port = bracketed.partition(']')
+            _, have_port, port = port.partition(':')
+        else:
+            hostname, have_port, port = hostinfo.partition(':')
+        if not have_port:
+            port = None
+        return hostname, port
+
+
+class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes):
+    __slots__ = ()
+
+    @property
+    def _userinfo(self):
+        netloc = self.netloc
+        userinfo, have_info, hostinfo = netloc.rpartition(b'@')
+        if have_info:
+            username, have_password, password = userinfo.partition(b':')
+            if not have_password:
+                password = None
         else:
-            return None
+            username = password = None
+        return username, password
+
+    @property
+    def _hostinfo(self):
+        netloc = self.netloc
+        _, _, hostinfo = netloc.rpartition(b'@')
+        _, have_open_br, bracketed = hostinfo.partition(b'[')
+        if have_open_br:
+            hostname, _, port = bracketed.partition(b']')
+            _, have_port, port = port.partition(b':')
+        else:
+            hostname, have_port, port = hostinfo.partition(b':')
+        if not have_port:
+            port = None
+        return hostname, port
+
 
 from collections import namedtuple
 
-class SplitResult(namedtuple('SplitResult', 'scheme netloc path query fragment'), ResultMixin):
+_DefragResultBase = namedtuple('DefragResult', 'url fragment')
+_SplitResultBase = namedtuple('SplitResult', 'scheme netloc path query fragment')
+_ParseResultBase = namedtuple('ParseResult', 'scheme netloc path params query fragment')
+
+# For backwards compatibility, alias _NetlocResultMixinStr
+# ResultBase is no longer part of the documented API, but it is
+# retained since deprecating it isn't worth the hassle
+ResultBase = _NetlocResultMixinStr
 
+# Structured result objects for string data
+class DefragResult(_DefragResultBase, _ResultMixinStr):
     __slots__ = ()
+    def geturl(self):
+        if self.fragment:
+            return self.url + '#' + self.fragment
+        else:
+            return self.url
 
+class SplitResult(_SplitResultBase, _NetlocResultMixinStr):
+    __slots__ = ()
     def geturl(self):
         return urlunsplit(self)
 
+class ParseResult(_ParseResultBase, _NetlocResultMixinStr):
+    __slots__ = ()
+    def geturl(self):
+        return urlunparse(self)
 
-class ParseResult(namedtuple('ParseResult', 'scheme netloc path params query fragment'), ResultMixin):
+# Structured result objects for bytes data
+class DefragResultBytes(_DefragResultBase, _ResultMixinBytes):
+    __slots__ = ()
+    def geturl(self):
+        if self.fragment:
+            return self.url + b'#' + self.fragment
+        else:
+            return self.url
 
+class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes):
     __slots__ = ()
+    def geturl(self):
+        return urlunsplit(self)
 
+class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes):
+    __slots__ = ()
     def geturl(self):
         return urlunparse(self)
 
+# Set up the encode/decode result pairs
+def _fix_result_transcoding():
+    _result_pairs = (
+        (DefragResult, DefragResultBytes),
+        (SplitResult, SplitResultBytes),
+        (ParseResult, ParseResultBytes),
+    )
+    for _decoded, _encoded in _result_pairs:
+        _decoded._encoded_counterpart = _encoded
+        _encoded._decoded_counterpart = _decoded
+
+_fix_result_transcoding()
+del _fix_result_transcoding
 
 def urlparse(url, scheme='', allow_fragments=True):
     """Parse a URL into 6 components:
@@ -136,13 +281,15 @@
     Return a 6-tuple: (scheme, netloc, path, params, query, fragment).
     Note that we don't break the components up in smaller bits
     (e.g. netloc is a single string) and we don't expand % escapes."""
+    url, scheme, _coerce_result = _coerce_args(url, scheme)
     tuple = urlsplit(url, scheme, allow_fragments)
     scheme, netloc, url, query, fragment = tuple
     if scheme in uses_params and ';' in url:
         url, params = _splitparams(url)
     else:
         params = ''
-    return ParseResult(scheme, netloc, url, params, query, fragment)
+    result = ParseResult(scheme, netloc, url, params, query, fragment)
+    return _coerce_result(result)
 
 def _splitparams(url):
     if '/'  in url:
@@ -167,11 +314,12 @@
     Return a 5-tuple: (scheme, netloc, path, query, fragment).
     Note that we don't break the components up in smaller bits
     (e.g. netloc is a single string) and we don't expand % escapes."""
+    url, scheme, _coerce_result = _coerce_args(url, scheme)
     allow_fragments = bool(allow_fragments)
     key = url, scheme, allow_fragments, type(url), type(scheme)
     cached = _parse_cache.get(key, None)
     if cached:
-        return cached
+        return _coerce_result(cached)
     if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth
         clear_cache()
     netloc = query = fragment = ''
@@ -191,7 +339,7 @@
                 url, query = url.split('?', 1)
             v = SplitResult(scheme, netloc, url, query, fragment)
             _parse_cache[key] = v
-            return v
+            return _coerce_result(v)
         if url.endswith(':') or not url[i+1].isdigit():
             for c in url[:i]:
                 if c not in scheme_chars:
@@ -209,17 +357,18 @@
         url, query = url.split('?', 1)
     v = SplitResult(scheme, netloc, url, query, fragment)
     _parse_cache[key] = v
-    return v
+    return _coerce_result(v)
 
 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
+    scheme, netloc, url, params, query, fragment, _coerce_result = (
+                                                  _coerce_args(*components))
     if params:
         url = "%s;%s" % (url, params)
-    return urlunsplit((scheme, netloc, url, query, fragment))
+    return _coerce_result(urlunsplit((scheme, netloc, url, query, fragment)))
 
 def urlunsplit(components):
     """Combine the elements of a tuple as returned by urlsplit() into a
@@ -227,7 +376,8 @@
     This may result in a slightly different, but equivalent URL, if the URL that
     was parsed originally had unnecessary delimiters (for example, a ? with an
     empty query; the RFC states that these are equivalent)."""
-    scheme, netloc, url, query, fragment = components
+    scheme, netloc, url, query, fragment, _coerce_result = (
+                                          _coerce_args(*components))
     if netloc or (scheme and scheme in uses_netloc and url[:2] != '//'):
         if url and url[:1] != '/': url = '/' + url
         url = '//' + (netloc or '') + url
@@ -237,7 +387,7 @@
         url = url + '?' + query
     if fragment:
         url = url + '#' + fragment
-    return url
+    return _coerce_result(url)
 
 def urljoin(base, url, allow_fragments=True):
     """Join a base URL and a possibly relative URL to form an absolute
@@ -246,32 +396,28 @@
         return url
     if not url:
         return base
+    base, url, _coerce_result = _coerce_args(base, url)
     bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
             urlparse(base, '', allow_fragments)
     scheme, netloc, path, params, query, fragment = \
             urlparse(url, bscheme, allow_fragments)
     if scheme != bscheme or scheme not in uses_relative:
-        return url
+        return _coerce_result(url)
     if scheme in uses_netloc:
         if netloc:
-            return urlunparse((scheme, netloc, path,
-                               params, query, fragment))
+            return _coerce_result(urlunparse((scheme, netloc, path,
+                                              params, query, fragment)))
         netloc = bnetloc
     if path[:1] == '/':
-        return urlunparse((scheme, netloc, path,
-                           params, query, fragment))
-    if not path:
+        return _coerce_result(urlunparse((scheme, netloc, path,
+                                          params, query, fragment)))
+    if not path and not params:
         path = bpath
-        if not params:
-            params = bparams
-        else:
-            path = path[:-1]
-            return urlunparse((scheme, netloc, path,
-                                params, query, fragment))
+        params = bparams
         if not query:
             query = bquery
-        return urlunparse((scheme, netloc, path,
-                           params, query, fragment))
+        return _coerce_result(urlunparse((scheme, netloc, path,
+                                          params, query, fragment)))
     segments = bpath.split('/')[:-1] + path.split('/')
     # XXX The stuff below is bogus in various ways...
     if segments[-1] == '.':
@@ -293,8 +439,8 @@
         segments[-1] = ''
     elif len(segments) >= 2 and segments[-1] == '..':
         segments[-2:] = ['']
-    return urlunparse((scheme, netloc, '/'.join(segments),
-                       params, query, fragment))
+    return _coerce_result(urlunparse((scheme, netloc, '/'.join(segments),
+                                      params, query, fragment)))
 
 def urldefrag(url):
     """Removes any existing fragment from URL.
@@ -303,12 +449,14 @@
     the URL contained no fragments, the second element is the
     empty string.
     """
+    url, _coerce_result = _coerce_args(url)
     if '#' in url:
         s, n, p, a, q, frag = urlparse(url)
         defrag = urlunparse((s, n, p, a, q, ''))
-        return defrag, frag
     else:
-        return url, ''
+        frag = ''
+        defrag = url
+    return _coerce_result(DefragResult(defrag, frag))
 
 def unquote_to_bytes(string):
     """unquote_to_bytes('abc%20def') -> b'abc def'."""
@@ -375,7 +523,8 @@
         string += pct_sequence.decode(encoding, errors)
     return string
 
-def parse_qs(qs, keep_blank_values=False, strict_parsing=False):
+def parse_qs(qs, keep_blank_values=False, strict_parsing=False,
+             encoding='utf-8', errors='replace'):
     """Parse a query given as a string argument.
 
         Arguments:
@@ -392,16 +541,22 @@
         strict_parsing: flag indicating what to do with parsing errors.
             If false (the default), errors are silently ignored.
             If true, errors raise a ValueError exception.
+
+        encoding and errors: specify how to decode percent-encoded sequences
+            into Unicode characters, as accepted by the bytes.decode() method.
     """
     dict = {}
-    for name, value in parse_qsl(qs, keep_blank_values, strict_parsing):
+    pairs = parse_qsl(qs, keep_blank_values, strict_parsing,
+                      encoding=encoding, errors=errors)
+    for name, value in pairs:
         if name in dict:
             dict[name].append(value)
         else:
             dict[name] = [value]
     return dict
 
-def parse_qsl(qs, keep_blank_values=False, strict_parsing=False):
+def parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
+              encoding='utf-8', errors='replace'):
     """Parse a query given as a string argument.
 
     Arguments:
@@ -418,8 +573,12 @@
         false (the default), errors are silently ignored. If true,
         errors raise a ValueError exception.
 
+    encoding and errors: specify how to decode percent-encoded sequences
+        into Unicode characters, as accepted by the bytes.decode() method.
+
     Returns a list, as G-d intended.
     """
+    qs, _coerce_result = _coerce_args(qs)
     pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
     r = []
     for name_value in pairs:
@@ -435,10 +594,13 @@
             else:
                 continue
         if len(nv[1]) or keep_blank_values:
-            name = unquote(nv[0].replace('+', ' '))
-            value = unquote(nv[1].replace('+', ' '))
+            name = nv[0].replace('+', ' ')
+            name = unquote(name, encoding=encoding, errors=errors)
+            name = _coerce_result(name)
+            value = nv[1].replace('+', ' ')
+            value = unquote(value, encoding=encoding, errors=errors)
+            value = _coerce_result(value)
             r.append((name, value))
-
     return r
 
 def unquote_plus(string, encoding='utf-8', errors='replace'):
@@ -699,7 +861,12 @@
         _hostprog = re.compile('^//([^/?]*)(.*)$')
 
     match = _hostprog.match(url)
-    if match: return match.group(1, 2)
+    if match:
+        host_port = match.group(1)
+        path = match.group(2)
+        if path and not path.startswith('/'):
+            path = '/' + path
+        return host_port, path
     return None, url
 
 _userprog = None
@@ -711,7 +878,7 @@
         _userprog = re.compile('^(.*)@(.*)$')
 
     match = _userprog.match(host)
-    if match: return map(unquote, match.group(1, 2))
+    if match: return match.group(1, 2)
     return None, host
 
 _passwdprog = None

Modified: python/branches/pep-3151/Lib/urllib/request.py
==============================================================================
--- python/branches/pep-3151/Lib/urllib/request.py	(original)
+++ python/branches/pep-3151/Lib/urllib/request.py	Sat Feb 26 08:16:32 2011
@@ -94,6 +94,7 @@
 import socket
 import sys
 import time
+import collections
 
 from urllib.error import URLError, HTTPError, ContentTooShortError
 from urllib.parse import (
@@ -105,7 +106,7 @@
 # check for SSL
 try:
     import ssl
-except:
+except ImportError:
     _have_ssl = False
 else:
     _have_ssl = True
@@ -274,8 +275,9 @@
     def __init__(self):
         client_version = "Python-urllib/%s" % __version__
         self.addheaders = [('User-agent', client_version)]
-        # manage the individual handlers
+        # self.handlers is retained only for backward compatibility
         self.handlers = []
+        # manage the individual handlers
         self.handle_open = {}
         self.handle_error = {}
         self.process_response = {}
@@ -325,8 +327,6 @@
             added = True
 
         if added:
-            # 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)
 
@@ -1048,13 +1048,24 @@
 
         if request.data is not None:  # POST
             data = request.data
+            if isinstance(data, str):
+                raise TypeError("POST data should be bytes"
+                        " or an iterable of bytes. It cannot be str.")
             if not request.has_header('Content-type'):
                 request.add_unredirected_header(
                     'Content-type',
                     'application/x-www-form-urlencoded')
             if not request.has_header('Content-length'):
-                request.add_unredirected_header(
-                    'Content-length', '%d' % len(data))
+                try:
+                    mv = memoryview(data)
+                except TypeError:
+                    if isinstance(data, collections.Iterable):
+                        raise ValueError("Content-Length should be specified "
+                                "for iterable data of type %r %r" % (type(data),
+                                data))
+                else:
+                    request.add_unredirected_header(
+                            'Content-length', '%d' % (len(mv) * mv.itemsize))
 
         sel_host = host
         if request.has_proxy():
@@ -1300,8 +1311,8 @@
         else:
             passwd = None
         host = unquote(host)
-        user = unquote(user or '')
-        passwd = unquote(passwd or '')
+        user = user or ''
+        passwd = passwd or ''
 
         try:
             host = socket.gethostbyname(host)
@@ -1835,7 +1846,7 @@
         if encoding == 'base64':
             import base64
             # XXX is this encoding/decoding ok?
-            data = base64.decodebytes(data.encode('ascii')).decode('latin1')
+            data = base64.decodebytes(data.encode('ascii')).decode('latin-1')
         else:
             data = unquote(data)
         msg.append('Content-Length: %d' % len(data))

Modified: python/branches/pep-3151/Lib/wave.py
==============================================================================
--- python/branches/pep-3151/Lib/wave.py	(original)
+++ python/branches/pep-3151/Lib/wave.py	Sat Feb 26 08:16:32 2011
@@ -467,11 +467,11 @@
         self._datalength = self._nframes * self._nchannels * self._sampwidth
         self._form_length_pos = self._file.tell()
         self._file.write(struct.pack('<l4s4slhhllhh4s',
-            36 + self._datalength, 'WAVE', 'fmt ', 16,
+            36 + self._datalength, b'WAVE', b'fmt ', 16,
             WAVE_FORMAT_PCM, self._nchannels, self._framerate,
             self._nchannels * self._framerate * self._sampwidth,
             self._nchannels * self._sampwidth,
-            self._sampwidth * 8, 'data'))
+            self._sampwidth * 8, b'data'))
         self._data_length_pos = self._file.tell()
         self._file.write(struct.pack('<l', self._datalength))
         self._headerwritten = True

Modified: python/branches/pep-3151/Lib/weakref.py
==============================================================================
--- python/branches/pep-3151/Lib/weakref.py	(original)
+++ python/branches/pep-3151/Lib/weakref.py	Sat Feb 26 08:16:32 2011
@@ -166,7 +166,7 @@
     def popitem(self):
         if self._pending_removals:
             self._commit_removals()
-        while 1:
+        while True:
             key, wr = self.data.popitem()
             o = wr()
             if o is not None:
@@ -324,7 +324,7 @@
         try:
             wr = ref(key)
         except TypeError:
-            return 0
+            return False
         return wr in self.data
 
     def items(self):
@@ -362,7 +362,7 @@
         return list(self.data)
 
     def popitem(self):
-        while 1:
+        while True:
             key, value = self.data.popitem()
             o = key()
             if o is not None:

Modified: python/branches/pep-3151/Lib/webbrowser.py
==============================================================================
--- python/branches/pep-3151/Lib/webbrowser.py	(original)
+++ python/branches/pep-3151/Lib/webbrowser.py	Sat Feb 26 08:16:32 2011
@@ -286,12 +286,10 @@
     """Launcher class for Mozilla/Netscape browsers."""
 
     raise_opts = ["-noraise", "-raise"]
-
     remote_args = ['-remote', 'openURL(%s%action)']
     remote_action = ""
     remote_action_newwin = ",new-window"
     remote_action_newtab = ",new-tab"
-
     background = True
 
 Netscape = Mozilla
@@ -304,15 +302,13 @@
     remote_args = ['%action', '%s']
     remote_action = "-n"
     remote_action_newwin = "-w"
-
     background = True
 
 
 class Opera(UnixBrowser):
     "Launcher class for Opera browser."
 
-    raise_opts = ["", "-raise"]
-
+    raise_opts = ["-noraise", ""]
     remote_args = ['-remote', 'openURL(%s%action)']
     remote_action = ""
     remote_action_newwin = ",new-window"

Modified: python/branches/pep-3151/Lib/wsgiref/handlers.py
==============================================================================
--- python/branches/pep-3151/Lib/wsgiref/handlers.py	(original)
+++ python/branches/pep-3151/Lib/wsgiref/handlers.py	Sat Feb 26 08:16:32 2011
@@ -302,7 +302,9 @@
     def finish_content(self):
         """Ensure headers and content have both been sent"""
         if not self.headers_sent:
-            self.headers['Content-Length'] = "0"
+            # Only zero Content-Length if not set by the application (so
+            # that HEAD requests can be satisfied properly, see #3839)
+            self.headers.setdefault('Content-Length', "0")
             self.send_headers()
         else:
             pass # XXX check if content-length was too short?

Modified: python/branches/pep-3151/Lib/wsgiref/util.py
==============================================================================
--- python/branches/pep-3151/Lib/wsgiref/util.py	(original)
+++ python/branches/pep-3151/Lib/wsgiref/util.py	Sat Feb 26 08:16:32 2011
@@ -64,7 +64,7 @@
     """Return the full request URI, optionally including the query string"""
     url = application_uri(environ)
     from urllib.parse import quote
-    path_info = quote(environ.get('PATH_INFO',''))
+    path_info = quote(environ.get('PATH_INFO',''),safe='/;=,')
     if not environ.get('SCRIPT_NAME'):
         url += path_info[1:]
     else:

Modified: python/branches/pep-3151/Lib/xml/etree/ElementTree.py
==============================================================================
--- python/branches/pep-3151/Lib/xml/etree/ElementTree.py	(original)
+++ python/branches/pep-3151/Lib/xml/etree/ElementTree.py	Sat Feb 26 08:16:32 2011
@@ -584,6 +584,8 @@
         self.text = text_or_uri
     def __str__(self):
         return self.text
+    def __repr__(self):
+        return '<QName %r>' % (self.text,)
     def __hash__(self):
         return hash(self.text)
     def __le__(self, other):
@@ -1066,7 +1068,7 @@
 def register_namespace(prefix, uri):
     if re.match("ns\d+$", prefix):
         raise ValueError("Prefix format reserved for internal use")
-    for k, v in _namespace_map.items():
+    for k, v in list(_namespace_map.items()):
         if k == uri or v == prefix:
             del _namespace_map[k]
     _namespace_map[uri] = prefix

Modified: python/branches/pep-3151/Lib/xmlrpc/client.py
==============================================================================
--- python/branches/pep-3151/Lib/xmlrpc/client.py	(original)
+++ python/branches/pep-3151/Lib/xmlrpc/client.py	Sat Feb 26 08:16:32 2011
@@ -1297,8 +1297,12 @@
 
     def parse_response(self, response):
         # read response data from httpresponse, and parse it
-        if response.getheader("Content-Encoding", "") == "gzip":
-            stream = GzipDecodedResponse(response)
+        # Check for new http response object, otherwise it is a file object.
+        if hasattr(response, 'getheader'):
+            if response.getheader("Content-Encoding", "") == "gzip":
+                stream = GzipDecodedResponse(response)
+            else:
+                stream = response
         else:
             stream = response
 
@@ -1330,7 +1334,7 @@
         if self._connection and host == self._connection[0]:
             return self._connection[1]
 
-        if not hasattr(socket, "ssl"):
+        if not hasattr(http.client, "HTTPSConnection"):
             raise NotImplementedError(
             "your version of http.client doesn't support HTTPS")
         # create a HTTPS connection object from a host descriptor

Modified: python/branches/pep-3151/Lib/zipfile.py
==============================================================================
--- python/branches/pep-3151/Lib/zipfile.py	(original)
+++ python/branches/pep-3151/Lib/zipfile.py	Sat Feb 26 08:16:32 2011
@@ -473,9 +473,11 @@
     # Search for universal newlines or line chunks.
     PATTERN = re.compile(br'^(?P<chunk>[^\r\n]+)|(?P<newline>\n|\r\n?)')
 
-    def __init__(self, fileobj, mode, zipinfo, decrypter=None):
+    def __init__(self, fileobj, mode, zipinfo, decrypter=None,
+                 close_fileobj=False):
         self._fileobj = fileobj
         self._decrypter = decrypter
+        self._close_fileobj = close_fileobj
 
         self._compress_type = zipinfo.compress_type
         self._compress_size = zipinfo.compress_size
@@ -647,6 +649,12 @@
         self._offset += len(data)
         return data
 
+    def close(self):
+        try:
+            if self._close_fileobj:
+                self._fileobj.close()
+        finally:
+            super().close()
 
 
 class ZipFile:
@@ -869,8 +877,12 @@
 
     def setpassword(self, pwd):
         """Set default password for encrypted files."""
-        assert isinstance(pwd, bytes)
-        self.pwd = pwd
+        if pwd and not isinstance(pwd, bytes):
+            raise TypeError("pwd: expected bytes, got %s" % type(pwd))
+        if pwd:
+            self.pwd = pwd
+        else:
+            self.pwd = None
 
     def read(self, name, pwd=None):
         """Return file bytes (as a string) for name."""
@@ -881,6 +893,8 @@
         """Return file-like object for 'name'."""
         if mode not in ("r", "U", "rU"):
             raise RuntimeError('open() requires mode "r", "U", or "rU"')
+        if pwd and not isinstance(pwd, bytes):
+            raise TypeError("pwd: expected bytes, got %s" % type(pwd))
         if not self.fp:
             raise RuntimeError(
                   "Attempt to read ZIP archive that was already closed")
@@ -898,8 +912,12 @@
             zinfo = name
         else:
             # Get info object for name
-            zinfo = self.getinfo(name)
-
+            try:
+                zinfo = self.getinfo(name)
+            except KeyError:
+                if not self._filePassed:
+                    zef_file.close()
+                raise
         zef_file.seek(zinfo.header_offset, 0)
 
         # Skip the file header:
@@ -912,7 +930,15 @@
         if fheader[_FH_EXTRA_FIELD_LENGTH]:
             zef_file.read(fheader[_FH_EXTRA_FIELD_LENGTH])
 
-        if fname != zinfo.orig_filename.encode("utf-8"):
+        if zinfo.flag_bits & 0x800:
+            # UTF-8 filename
+            fname_str = fname.decode("utf-8")
+        else:
+            fname_str = fname.decode("cp437")
+
+        if fname_str != zinfo.orig_filename:
+            if not self._filePassed:
+                zef_file.close()
             raise BadZipFile(
                   'File name in directory %r and header %r differ.'
                   % (zinfo.orig_filename, fname))
@@ -924,6 +950,8 @@
             if not pwd:
                 pwd = self.pwd
             if not pwd:
+                if not self._filePassed:
+                    zef_file.close()
                 raise RuntimeError("File %s is encrypted, "
                                    "password required for extraction" % name)
 
@@ -933,8 +961,8 @@
             #  completely random, while the 12th contains the MSB of the CRC,
             #  or the MSB of the file time depending on the header type
             #  and is used to check the correctness of the password.
-            bytes = zef_file.read(12)
-            h = list(map(zd, bytes[0:12]))
+            header = zef_file.read(12)
+            h = list(map(zd, header[0:12]))
             if zinfo.flag_bits & 0x8:
                 # compare against the file type from extended local headers
                 check_byte = (zinfo._raw_time >> 8) & 0xff
@@ -942,9 +970,12 @@
                 # compare against the CRC otherwise
                 check_byte = (zinfo.CRC >> 24) & 0xff
             if h[11] != check_byte:
+                if not self._filePassed:
+                    zef_file.close()
                 raise RuntimeError("Bad password for file", name)
 
-        return  ZipExtFile(zef_file, mode, zinfo, zd)
+        return ZipExtFile(zef_file, mode, zinfo, zd,
+                          close_fileobj=not self._filePassed)
 
     def extract(self, member, path=None, pwd=None):
         """Extract a member from the archive to the current working directory,
@@ -1276,6 +1307,12 @@
 class PyZipFile(ZipFile):
     """Class to create ZIP archives with Python library files and packages."""
 
+    def __init__(self, file, mode="r", compression=ZIP_STORED,
+                 allowZip64=False, optimize=-1):
+        ZipFile.__init__(self, file, mode=mode, compression=compression,
+                         allowZip64=allowZip64)
+        self._optimize = optimize
+
     def writepy(self, pathname, basename=""):
         """Add all files from "pathname" to the ZIP archive.
 
@@ -1348,44 +1385,63 @@
         archive name, compiling if necessary.  For example, given
         /python/lib/string, return (/python/lib/string.pyc, string).
         """
+        def _compile(file, optimize=-1):
+            import py_compile
+            if self.debug:
+                print("Compiling", file)
+            try:
+                py_compile.compile(file, doraise=True, optimize=optimize)
+            except py_compile.PyCompileError as error:
+                print(err.msg)
+                return False
+            return True
+
         file_py  = pathname + ".py"
         file_pyc = pathname + ".pyc"
         file_pyo = pathname + ".pyo"
         pycache_pyc = imp.cache_from_source(file_py, True)
         pycache_pyo = imp.cache_from_source(file_py, False)
-        if (os.path.isfile(file_pyo) and
-            os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime):
-            # Use .pyo file.
-            arcname = fname = file_pyo
-        elif (os.path.isfile(file_pyc) and
-              os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime):
-            # Use .pyc file.
-            arcname = fname = file_pyc
-        elif (os.path.isfile(pycache_pyc) and
-              os.stat(pycache_pyc).st_mtime >= os.stat(file_py).st_mtime):
-            # Use the __pycache__/*.pyc file, but write it to the legacy pyc
-            # file name in the archive.
-            fname = pycache_pyc
-            arcname = file_pyc
-        elif (os.path.isfile(pycache_pyo) and
-              os.stat(pycache_pyo).st_mtime >= os.stat(file_py).st_mtime):
-            # Use the __pycache__/*.pyo file, but write it to the legacy pyo
-            # file name in the archive.
-            fname = pycache_pyo
-            arcname = file_pyo
+        if self._optimize == -1:
+            # legacy mode: use whatever file is present
+            if (os.path.isfile(file_pyo) and
+                os.stat(file_pyo).st_mtime >= os.stat(file_py).st_mtime):
+                # Use .pyo file.
+                arcname = fname = file_pyo
+            elif (os.path.isfile(file_pyc) and
+                  os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime):
+                # Use .pyc file.
+                arcname = fname = file_pyc
+            elif (os.path.isfile(pycache_pyc) and
+                  os.stat(pycache_pyc).st_mtime >= os.stat(file_py).st_mtime):
+                # Use the __pycache__/*.pyc file, but write it to the legacy pyc
+                # file name in the archive.
+                fname = pycache_pyc
+                arcname = file_pyc
+            elif (os.path.isfile(pycache_pyo) and
+                  os.stat(pycache_pyo).st_mtime >= os.stat(file_py).st_mtime):
+                # Use the __pycache__/*.pyo file, but write it to the legacy pyo
+                # file name in the archive.
+                fname = pycache_pyo
+                arcname = file_pyo
+            else:
+                # Compile py into PEP 3147 pyc file.
+                if _compile(file_py):
+                    fname = (pycache_pyc if __debug__ else pycache_pyo)
+                    arcname = (file_pyc if __debug__ else file_pyo)
+                else:
+                    fname = arcname = file_py
         else:
-            # Compile py into PEP 3147 pyc file.
-            import py_compile
-            if self.debug:
-                print("Compiling", file_py)
-            try:
-                py_compile.compile(file_py, doraise=True)
-            except py_compile.PyCompileError as error:
-                print(err.msg)
-                fname = file_py
+            # new mode: use given optimization level
+            if self._optimize == 0:
+                fname = pycache_pyc
+                arcname = file_pyc
             else:
-                fname = (pycache_pyc if __debug__ else pycache_pyo)
-                arcname = (file_pyc if __debug__ else file_pyo)
+                fname = pycache_pyo
+                arcname = file_pyo
+            if not (os.path.isfile(fname) and
+                    os.stat(fname).st_mtime >= os.stat(file_py).st_mtime):
+                if not _compile(file_py, optimize=self._optimize):
+                    fname = arcname = file_py
         archivename = os.path.split(arcname)[1]
         if basename:
             archivename = "%s/%s" % (basename, archivename)

Modified: python/branches/pep-3151/Mac/BuildScript/README.txt
==============================================================================
--- python/branches/pep-3151/Mac/BuildScript/README.txt	(original)
+++ python/branches/pep-3151/Mac/BuildScript/README.txt	Sat Feb 26 08:16:32 2011
@@ -1,78 +1,147 @@
-Building a MacPython distribution
-=================================
+Building a Python Mac OS X distribution
+=======================================
 
-The ``build-install.py`` script creates MacPython distributions, including
-sleepycat db4, sqlite3 and readline support.  It builds a complete 
+The ``build-install.py`` script creates Python distributions, including
+certain third-party libraries as necessary.  It builds a complete 
 framework-based Python out-of-tree, installs it in a funny place with 
 $DESTROOT, massages that installation to remove .pyc files and such, creates 
 an Installer package from the installation plus other files in ``resources`` 
 and ``scripts`` and placed that on a ``.dmg`` disk image.
 
-Prerequisites
--------------
+As of Python 2.7.x and 3.2, PSF practice is to build two installer variants
+for each release:
 
-* A MacOS X 10.4 (or later)
+1.  32-bit-only, i386 and PPC universal, capable on running on all machines
+    supported by Mac OS X 10.3.9 through (at least) 10.6::
 
-* XCode 2.2 (or later), with the universal SDK
+        python build-installer.py \
+            --sdk-path=/Developer/SDKs/MacOSX10.4u.sdk \
+            --universal-archs=32-bit \
+            --dep-target=10.3 
+            # These are the current default options
 
-* No Fink (in ``/sw``) or DarwinPorts (in ``/opt/local``), those could
+    - builds the following third-party libraries
+
+        * Bzip2
+        * Zlib 1.2.3
+        * GNU Readline (GPL)
+        * SQLite 3
+        * NCurses
+        * Oracle Sleepycat DB 4.8 (Python 2.x only)
+
+    - requires ActiveState ``Tcl/Tk 8.4`` (currently 8.4.19) to be installed for building
+
+    - current target build environment:
+        
+        * Mac OS X 10.5.8 PPC or Intel
+        * Xcode 3.1.4 (or later)
+        * ``MacOSX10.4u`` SDK (later SDKs do not support PPC G3 processors)
+        * ``MACOSX_DEPLOYMENT_TARGET=10.3``
+        * Apple ``gcc-4.0``
+        * Python 2.n (n >= 4) for documentation build with Sphinx
+
+    - alternate build environments:
+
+        * Mac OS X 10.4.11 with Xcode 2.5
+        * Mac OS X 10.6.6 with Xcode 3.2.5
+            - need to change ``/System/Library/Frameworks/{Tcl,Tk}.framework/Version/Current`` to ``8.4``
+
+2.  64-bit / 32-bit, x86_64 and i386 universal, for OS X 10.6 (and later)::
+
+        python build-installer.py \
+            --sdk-path=/Developer/SDKs/MacOSX10.6.sdk \
+            --universal-archs=intel \
+            --dep-target=10.6
+
+    - uses system-supplied versions of third-party libraries
+    
+        * readline module links with Apple BSD editline (libedit)
+        * builds Oracle Sleepycat DB 4.8 (Python 2.x only)
+
+    - requires ActiveState Tcl/Tk 8.5.9 (or later) to be installed for building
+
+    - current target build environment:
+        
+        * Mac OS X 10.6.6 (or later)
+        * Xcode 3.2.5 (or later)
+        * ``MacOSX10.6`` SDK
+        * ``MACOSX_DEPLOYMENT_TARGET=10.6``
+        * Apple ``gcc-4.2``
+        * Python 2.n (n >= 4) for documentation build with Sphinx
+
+    - alternate build environments:
+
+        * none
+
+
+General Prerequisites
+---------------------
+
+* No Fink (in ``/sw``) or MacPorts (in ``/opt/local``) or other local
+  libraries or utilities (in ``/usr/local``) as they could
   interfere with the build.
 
-* The documentation for the release must be available on python.org
+* The documentation for the release is built using Sphinx
   because it is included in the installer.
 
+* It is safest to start each variant build with an empty source directory
+  populated with a fresh copy of the untarred source.
+
 
 The Recipe
 ----------
 
-Here are the steps you need to follow to build a MacPython installer:
+Here are the steps you need to follow to build a Python installer:
 
-*  Run ``./build-installer.py``. Optionally you can pass a number of arguments
-   to specify locations of various files. Please see the top of
+* Run ``build-installer.py``. Optionally you can pass a number of arguments
+  to specify locations of various files. Please see the top of
   ``build-installer.py`` for its usage.
 
-  Running this script takes some time, I will not only build Python itself
+  Running this script takes some time, it will not only build Python itself
   but also some 3th-party libraries that are needed for extensions.
 
 * When done the script will tell you where the DMG image is (by default
   somewhere in ``/tmp/_py``).
 
-Building a 4-way universal installer
-....................................
+Building other universal installers
+...................................
 
 It is also possible to build a 4-way universal installer that runs on 
-OSX Leopard or later::
+OS X Leopard or later::
 
-  $ ./build-installer.py --dep-target=10.5 --universal-archs=all --sdk=/
+  python 2.6 /build-installer.py \
+        --dep-target=10.5
+        --universal-archs=all
+        --sdk-path=/Developer/SDKs/MacOSX10.5.sdk
+
+This requires that the deployment target is 10.5, and hence
+also that you are building on at least OS X 10.5.  4-way includes
+``i386``, ``x86_64``, ``ppc``, and ``ppc64`` (G5).  ``ppc64`` executable
+variants can only be run on G5 machines running 10.5.  Note that,
+while OS X 10.6 is only supported on Intel-based machines, it is possible
+to run ``ppc`` (32-bit) executables unmodified thanks to the Rosetta ppc
+emulation in OS X 10.5 and 10.6.
+
+Other ``--universal-archs`` options are ``64-bit`` (``x86_64``, ``ppc64``),
+and ``3-way`` (``ppc``, ``i386``, ``x86_64``).  None of these options
+are regularly exercised; use at your own risk.
 
-This requires that the deployment target is 10.5 (or later), and hence
-also that your building on at least OSX 10.5.
 
 Testing
 -------
 
-The resulting binaries should work on MacOSX 10.3.9 or later. I usually run
-the installer on a 10.3.9, a 10.4.x PPC and a 10.4.x Intel system and then
-run the testsuite to make sure.
-
-
-Announcements
--------------
-
-(This is mostly of historic interest)
-
-When all is done, announcements can be posted to at least the following
-places:
--   pythonmac-sig at python.org
--   python-dev at python.org
--   python-announce at python.org
--   archivist at info-mac.org
--   adcnews at apple.com
--   news at macnn.com
--   http://www.macupdate.com
--   http://guide.apple.com/usindex.lasso
--   http://www.apple.com/downloads/macosx/submit
--   http://www.versiontracker.com/ (userid Jack.Jansen at oratrix.com)
--   http://www.macshareware.net (userid jackjansen)
+Ideally, the resulting binaries should be installed and the test suite run
+on all supported OS X releases and architectures.  As a practical matter,
+that is generally not possible.  At a minimum, variant 1 should be run on
+at least one Intel, one PPC G4, and one PPC G3 system and one each of 
+OS X 10.6, 10.5, 10.4, and 10.3.9.  Not all tests run on 10.3.9.
+Variant 2 should be run on 10.6 in both 32-bit and 64-bit modes.::
+
+    arch -i386 /usr/local/bin/pythonn.n -m test.regrtest -w -u all 
+    arch -X86_64 /usr/local/bin/pythonn.n -m test.regrtest -w -u all
+    
+Certain tests will be skipped and some cause the interpreter to fail
+which will likely generate ``Python quit unexpectedly`` alert messages
+to be generated at several points during a test run.  These can
+be ignored.
 
-Also, check out Stephan Deibels http://pythonology.org/market contact list

Modified: python/branches/pep-3151/Mac/BuildScript/build-installer.py
==============================================================================
--- python/branches/pep-3151/Mac/BuildScript/build-installer.py	(original)
+++ python/branches/pep-3151/Mac/BuildScript/build-installer.py	Sat Feb 26 08:16:32 2011
@@ -1,12 +1,14 @@
 #!/usr/bin/python
 """
-This script is used to build the "official unofficial" universal build on
-Mac OS X. It requires Mac OS X 10.4, Xcode 2.2 and the 10.4u SDK to do its
-work.  64-bit or four-way universal builds require at least OS X 10.5 and
-the 10.5 SDK.
-
-Please ensure that this script keeps working with Python 2.3, to avoid
-bootstrap issues (/usr/bin/python is Python 2.3 on OSX 10.4)
+This script is used to build "official" universal installers on Mac OS X.
+It requires at least Mac OS X 10.4, Xcode 2.2 and the 10.4u SDK for
+32-bit builds.  64-bit or four-way universal builds require at least
+OS X 10.5 and the 10.5 SDK.
+
+Please ensure that this script keeps working with Python 2.5, to avoid
+bootstrap issues (/usr/bin/python is Python 2.5 on OSX 10.5).  Sphinx,
+which is used to build the documentation, currently requires at least
+Python 2.4.
 
 Usage: see USAGE variable in the script.
 """
@@ -144,9 +146,9 @@
     if DEPTARGET < '10.5':
         result.extend([
           dict(
-              name="Bzip2 1.0.5",
-              url="http://www.bzip.org/1.0.5/bzip2-1.0.5.tar.gz",
-              checksum='3c15a0c8d1d3ee1c46a1634d00617b1a',
+              name="Bzip2 1.0.6",
+              url="http://bzip.org/1.0.6/bzip2-1.0.6.tar.gz",
+              checksum='00b516f4704d4a7cb50a1d97e6e8e15b',
               configure=None,
               install='make install CC=%s PREFIX=%s/usr/local/ CFLAGS="-arch %s -isysroot %s"'%(
                   CC,
@@ -169,29 +171,33 @@
           ),
           dict(
               # Note that GNU readline is GPL'd software
-              name="GNU Readline 5.1.4",
-              url="http://ftp.gnu.org/pub/gnu/readline/readline-5.1.tar.gz" ,
-              checksum='7ee5a692db88b30ca48927a13fd60e46',
+              name="GNU Readline 6.1.2",
+              url="http://ftp.gnu.org/pub/gnu/readline/readline-6.1.tar.gz" ,
+              checksum='fc2f7e714fe792db1ce6ddc4c9fb4ef3',
               patchlevel='0',
               patches=[
                   # The readline maintainers don't do actual micro releases, but
                   # just ship a set of patches.
-                  'http://ftp.gnu.org/pub/gnu/readline/readline-5.1-patches/readline51-001',
-                  'http://ftp.gnu.org/pub/gnu/readline/readline-5.1-patches/readline51-002',
-                  'http://ftp.gnu.org/pub/gnu/readline/readline-5.1-patches/readline51-003',
-                  'http://ftp.gnu.org/pub/gnu/readline/readline-5.1-patches/readline51-004',
+                  'http://ftp.gnu.org/pub/gnu/readline/readline-6.1-patches/readline61-001',
+                  'http://ftp.gnu.org/pub/gnu/readline/readline-6.1-patches/readline61-002',
               ]
           ),
           dict(
-              name="SQLite 3.6.11",
-              url="http://www.sqlite.org/sqlite-3.6.11.tar.gz",
-              checksum='7ebb099696ab76cc6ff65dd496d17858',
+              name="SQLite 3.7.4",
+              url="http://www.sqlite.org/sqlite-autoconf-3070400.tar.gz",
+              checksum='8f0c690bfb33c3cbbc2471c3d9ba0158',
+              configure_env=('CFLAGS="-Os'
+                                  ' -DSQLITE_ENABLE_FTS3'
+                                  ' -DSQLITE_ENABLE_FTS3_PARENTHESIS'
+                                  ' -DSQLITE_ENABLE_RTREE'
+                                  ' -DSQLITE_TCL=0'
+                                  '"'),
               configure_pre=[
                   '--enable-threadsafe',
-                  '--enable-tempstore',
                   '--enable-shared=no',
                   '--enable-static=yes',
-                  '--disable-tcl',
+                  '--disable-readline',
+                  '--disable-dependency-tracking',
               ]
           ),
           dict(
@@ -199,6 +205,7 @@
               url="http://ftp.gnu.org/pub/gnu/ncurses/ncurses-5.5.tar.gz",
               checksum='e73c1ac10b4bfc46db43b2ddfd6244ef',
               configure_pre=[
+                  "--enable-widec",
                   "--without-cxx",
                   "--without-ada",
                   "--without-progs",
@@ -225,18 +232,19 @@
           ),
         ])
 
-    result.extend([
-      dict(
-          name="Sleepycat DB 4.7.25",
-          url="http://download.oracle.com/berkeley-db/db-4.7.25.tar.gz",
-          checksum='ec2b87e833779681a0c3a814aa71359e',
-          buildDir="build_unix",
-          configure="../dist/configure",
-          configure_pre=[
-              '--includedir=/usr/local/include/db4',
-          ]
-      ),
-    ])
+    if not PYTHON_3:
+        result.extend([
+          dict(
+              name="Sleepycat DB 4.7.25",
+              url="http://download.oracle.com/berkeley-db/db-4.7.25.tar.gz",
+              checksum='ec2b87e833779681a0c3a814aa71359e',
+              buildDir="build_unix",
+              configure="../dist/configure",
+              configure_pre=[
+                  '--includedir=/usr/local/include/db4',
+              ]
+          ),
+        ])
 
     return result
 
@@ -399,6 +407,9 @@
     Check that we're running on a supported system.
     """
 
+    if sys.version_info[0:2] < (2, 4):
+        fatal("This script must be run with Python 2.4 or later")
+
     if platform.system() != 'Darwin':
         fatal("This script should be run on a Mac OS X 10.4 (or later) system")
 
@@ -418,15 +429,16 @@
     #       to install a newer patch level.
 
     for framework in ['Tcl', 'Tk']:
-        fw = dict(lower=framework.lower(),
-                    upper=framework.upper(),
-                    cap=framework.capitalize())
-        fwpth = "Library/Frameworks/%(cap)s.framework/%(lower)sConfig.sh" % fw
-        sysfw = os.path.join('/System', fwpth)
+        #fw = dict(lower=framework.lower(),
+        #            upper=framework.upper(),
+        #            cap=framework.capitalize())
+        #fwpth = "Library/Frameworks/%(cap)s.framework/%(lower)sConfig.sh" % fw
+        fwpth = 'Library/Frameworks/Tcl.framework/Versions/Current'
+        sysfw = os.path.join(SDKPATH, 'System', fwpth)
         libfw = os.path.join('/', fwpth)
         usrfw = os.path.join(os.getenv('HOME'), fwpth)
-        version = "%(upper)s_VERSION" % fw
-        if getTclTkVersion(libfw, version) != getTclTkVersion(sysfw, version):
+        #version = "%(upper)s_VERSION" % fw
+        if os.readlink(libfw) != os.readlink(sysfw):
             fatal("Version of %s must match %s" % (libfw, sysfw) )
         if os.path.exists(usrfw):
             fatal("Please rename %s to avoid possible dynamic load issues."
@@ -696,6 +708,9 @@
         configure_args.insert(0, configure)
         configure_args = [ shellQuote(a) for a in configure_args ]
 
+        if 'configure_env' in recipe:
+            configure_args.insert(0, recipe['configure_env'])
+
         print "Running configure for %s"%(name,)
         runCommand(' '.join(configure_args) + ' 2>&1')
 
@@ -751,9 +766,9 @@
         shutil.rmtree(buildDir)
     if os.path.exists(rootDir):
         shutil.rmtree(rootDir)
-    os.mkdir(buildDir)
-    os.mkdir(rootDir)
-    os.mkdir(os.path.join(rootDir, 'empty-dir'))
+    os.makedirs(buildDir)
+    os.makedirs(rootDir)
+    os.makedirs(os.path.join(rootDir, 'empty-dir'))
     curdir = os.getcwd()
     os.chdir(buildDir)
 
@@ -825,12 +840,33 @@
             os.chmod(p, stat.S_IMODE(st.st_mode) | stat.S_IWGRP)
             os.chown(p, -1, gid)
 
+    if PYTHON_3:
+        LDVERSION=None
+        VERSION=None
+        ABIFLAGS=None
+
+        fp = open(os.path.join(buildDir, 'Makefile'), 'r')
+        for ln in fp:
+            if ln.startswith('VERSION='):
+                VERSION=ln.split()[1]
+            if ln.startswith('ABIFLAGS='):
+                ABIFLAGS=ln.split()[1]
+            if ln.startswith('LDVERSION='):
+                LDVERSION=ln.split()[1]
+        fp.close()
+
+        LDVERSION = LDVERSION.replace('$(VERSION)', VERSION)
+        LDVERSION = LDVERSION.replace('$(ABIFLAGS)', ABIFLAGS)
+        config_suffix = '-' + LDVERSION
+    else:
+        config_suffix = ''      # Python 2.x
+
     # We added some directories to the search path during the configure
     # phase. Remove those because those directories won't be there on
     # the end-users system.
     path =os.path.join(rootDir, 'Library', 'Frameworks', 'Python.framework',
                 'Versions', version, 'lib', 'python%s'%(version,),
-                'config', 'Makefile')
+                'config' + config_suffix, 'Makefile')
     fp = open(path, 'r')
     data = fp.read()
     fp.close()

Modified: python/branches/pep-3151/Mac/BuildScript/resources/ReadMe.txt
==============================================================================
--- python/branches/pep-3151/Mac/BuildScript/resources/ReadMe.txt	(original)
+++ python/branches/pep-3151/Mac/BuildScript/resources/ReadMe.txt	Sat Feb 26 08:16:32 2011
@@ -1,29 +1,36 @@
 This package will install Python $FULL_VERSION for Mac OS X
-$MACOSX_DEPLOYMENT_TARGET for the following 
-architecture(s): $ARCHITECTURES.
+$MACOSX_DEPLOYMENT_TARGET for the following architecture(s):
+$ARCHITECTURES.
 
-Separate installers are available for older versions
-of Mac OS X, see the homepage, below.
+Installation requires approximately $INSTALL_SIZE MB of disk space,
+ignore the message that it will take zero bytes.
 
-Installation requires approximately $INSTALL_SIZE MB of disk
-space, ignore the message that it will take zero bytes.
+You must install onto your current boot disk, even though the
+installer does not enforce this, otherwise things will not work.
 
-You must install onto your current boot disk, even
-though the installer does not enforce this, otherwise
-things will not work.
-
-Python consists of the Python programming language
-interpreter, plus a set of programs to allow easy
-access to it for Mac users including an integrated development
-environment, IDLE, plus a set of pre-built extension modules
-that open up specific Macintosh technologies to Python programs.
-
-The installer puts the applications in "Python $VERSION" 
-in your Applications folder, and the underlying machinery in
-$PYTHONFRAMEWORKINSTALLDIR. It can optionally place
-links to the command-line tools in /usr/local as well,
-by default you have to add the "bin" directory inside
-the framework to you shell's search path.
+Python consists of the Python programming language interpreter, plus
+a set of programs to allow easy access to it for Mac users including
+an integrated development environment, IDLE, plus a set of pre-built
+extension modules that open up specific Macintosh technologies to
+Python programs.
+
+                    **** IMPORTANT ****
+                    
+Before using IDLE or other programs using the tkinter graphical user
+interface toolkit, visit http://www.python.org/download/mac/tcltk/
+for current information about supported and recommended versions
+of Tcl/Tk for this version of Python and Mac OS X.
+
+                    *******************
+
+The installer puts applications, an "Update Shell Profile" command,
+and a link to the optionally installed Python Documentation into the
+"Python $VERSION" subfolder of the system Applications folder,
+and puts the underlying machinery into the folder
+$PYTHONFRAMEWORKINSTALLDIR. It can
+optionally place links to the command-line tools in /usr/local/bin as
+well. Double-click on the "Update Shell Profile" command to add the
+"bin" directory inside the framework to your shell's search path.
 
 More information on Python in general can be found at
 http://www.python.org.

Modified: python/branches/pep-3151/Mac/BuildScript/resources/Welcome.rtf
==============================================================================
--- python/branches/pep-3151/Mac/BuildScript/resources/Welcome.rtf	(original)
+++ python/branches/pep-3151/Mac/BuildScript/resources/Welcome.rtf	Sat Feb 26 08:16:32 2011
@@ -1,19 +1,35 @@
-{\rtf1\ansi\ansicpg1252\cocoartf949\cocoasubrtf430
+{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf350
 {\fonttbl\f0\fswiss\fcharset0 Helvetica;}
 {\colortbl;\red255\green255\blue255;}
-\paperw11900\paperh16840\margl1440\margr1440\vieww9920\viewh10660\viewkind0
+\paperw11904\paperh16836\margl1440\margr1440\vieww9640\viewh10620\viewkind0
 \pard\tx720\tx1440\tx2160\tx2880\tx3600\tx4320\tx5040\tx5760\tx6480\tx7200\tx7920\tx8640\ql\qnatural
 
 \f0\fs24 \cf0 This package will install 
-\b MacPython $FULL_VERSION
+\b Python $FULL_VERSION
 \b0  for 
 \b Mac OS X $MACOSX_DEPLOYMENT_TARGET
 \b0 .\
 \
-MacPython consists of the Python programming language interpreter, plus a set of programs to allow easy access to it for Mac users including an integrated development environment \b IDLE\b0  plus a set of pre-built extension modules that open up specific Macintosh technologies to Python programs.\
+
+\b Python for Mac OS X
+\b0  consists of the Python programming language interpreter, plus a set of programs to allow easy access to it for Mac OS X users including an integrated development environment 
+\b IDLE
+\b0  and a set of pre-built extension modules that open up specific Macintosh technologies to Python programs.\
 \
-See the ReadMe file for more information.\
+See the ReadMe file and the Python documentation for more information.\
 \
 
 \b NOTE: 
-\b0 This package will by default not update your shell profile and will also not install files in /usr/local.  Double-click \b Update Shell Profile\b0  at any time to make $FULL_VERSION the default Python.}
+\b0 This package will by default not update your shell profile and will also not install files in /usr/local.  Double-click 
+\b Update Shell Profile
+\b0  at any time to make $FULL_VERSION the default Python.\
+\
+
+\b IMPORTANT:
+\b0  
+\b IDLE
+\b0  and other programs using the 
+\b tkinter
+\b0  graphical user interface toolkit require specific versions of the 
+\b Tcl/Tk
+\b0  platform independent windowing toolkit.  Visit {\field{\*\fldinst{HYPERLINK "http://www.python.org/download/mac/tcltk/"}}{\fldrslt http://www.python.org/download/mac/tcltk/}} for current information on supported and recommended versions of Tcl/Tk for this version of Python and Mac OS X.}
\ No newline at end of file

Modified: python/branches/pep-3151/Mac/BuildScript/scripts/postflight.documentation
==============================================================================
--- python/branches/pep-3151/Mac/BuildScript/scripts/postflight.documentation	(original)
+++ python/branches/pep-3151/Mac/BuildScript/scripts/postflight.documentation	Sat Feb 26 08:16:32 2011
@@ -1,11 +1,32 @@
 #!/bin/sh
 
 PYVER="@PYVER@"
+FWK="/Library/Frameworks/Python.framework/Versions/${PYVER}"
+FWK_DOCDIR_SUBPATH="Resources/English.lproj/Documentation"
+FWK_DOCDIR="${FWK}/${FWK_DOCDIR_SUBPATH}"
+APPDIR="/Applications/Python ${PYVER}"
+DEV_DOCDIR="/Developer/Documentation"
+SHARE_DIR="${FWK}/share"
+SHARE_DOCDIR="${SHARE_DIR}/doc/python${PYVER}"
+SHARE_DOCDIR_TO_FWK="../../.."
 
-if [ -d /Developer/Documentation ]; then
-	if [ ! -d /Developer/Documentation/Python ]; then
-		mkdir -p /Developer/Documentation/Python
-	fi
+# make link in /Developer/Documentation/ for Xcode users
+if [ -d "${DEV_DOCDIR}" ]; then
+    if [ ! -d "${DEV_DOCDIR}/Python" ]; then
+        mkdir -p "${DEV_DOCDIR}/Python"
+    fi
+    ln -fhs "${FWK_DOCDIR}" "${DEV_DOCDIR}/Python/Reference Documentation ${PYVER}"
+fi
+
+# make link in /Applications/Python m.n/ for Finder users
+if [ -d "${APPDIR}" ]; then
+    ln -fhs "${FWK_DOCDIR}/index.html" "${APPDIR}/Python Documentation.html"
+fi
 
-	ln -fhs /Library/Frameworks/Python.framework/Versions/${PYVER}/Resources/English.lproj/Documentation "/Developer/Documentation/Python/Reference Documentation @PYVER@"
+# make share/doc link in framework for command line users
+if [ -d "${SHARE_DIR}" ]; then
+    mkdir -p "${SHARE_DOCDIR}"
+    # make relative link to html doc directory
+    ln -fhs "${SHARE_DOCDIR_TO_FWK}/${FWK_DOCDIR_SUBPATH}" "${SHARE_DOCDIR}/html"
 fi
+

Deleted: python/branches/pep-3151/Mac/Extras.ReadMe.txt
==============================================================================
--- python/branches/pep-3151/Mac/Extras.ReadMe.txt	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,5 +0,0 @@
-This folder contains examples of Python usage and useful scripts and tools.
-
-You should be aware that these are not Macintosh-specific but are shared
-among Python on all platforms, so there are some that only run on Windows
-or Unix or another platform, and/or make little sense on a Macintosh.

Modified: python/branches/pep-3151/Mac/IDLE/IDLE.app/Contents/Info.plist
==============================================================================
--- python/branches/pep-3151/Mac/IDLE/IDLE.app/Contents/Info.plist	(original)
+++ python/branches/pep-3151/Mac/IDLE/IDLE.app/Contents/Info.plist	Sat Feb 26 08:16:32 2011
@@ -36,7 +36,7 @@
 	<key>CFBundleExecutable</key>
 	<string>IDLE</string>
 	<key>CFBundleGetInfoString</key>
-	<string>%version%, © 2001-2008 Python Software Foundation</string>
+	<string>%version%, © 2001-2011 Python Software Foundation</string>
 	<key>CFBundleIconFile</key>
 	<string>IDLE.icns</string>
 	<key>CFBundleIdentifier</key>

Deleted: python/branches/pep-3151/Mac/IDLE/idlemain.py
==============================================================================
--- python/branches/pep-3151/Mac/IDLE/idlemain.py	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,30 +0,0 @@
-"""
-Bootstrap script for IDLE as an application bundle.
-"""
-import sys, os
-
-from idlelib.PyShell import main
-
-# Change the current directory the user's home directory, that way we'll get
-# a more useful default location in the open/save dialogs.
-os.chdir(os.path.expanduser('~/Documents'))
-
-
-# Make sure sys.executable points to the python interpreter inside the
-# framework, instead of at the helper executable inside the application
-# bundle (the latter works, but doesn't allow access to the window server)
-if sys.executable.endswith('-32'):
-    sys.executable = os.path.join(sys.prefix, 'bin', 'python-32')
-else:
-    sys.executable = os.path.join(sys.prefix, 'bin', 'python')
-
-# Look for the -psn argument that the launcher adds and remove it, it will
-# only confuse the IDLE startup code.
-for idx, value in enumerate(sys.argv):
-    if value.startswith('-psn_'):
-        del sys.argv[idx]
-        break
-
-#argvemulator.ArgvCollector().mainloop()
-if __name__ == '__main__':
-    main()

Modified: python/branches/pep-3151/Mac/Makefile.in
==============================================================================
--- python/branches/pep-3151/Mac/Makefile.in	(original)
+++ python/branches/pep-3151/Mac/Makefile.in	Sat Feb 26 08:16:32 2011
@@ -47,8 +47,7 @@
 compileall=$(srcdir)/../Lib/compileall.py
 
 installapps: install_Python install_pythonw install_PythonLauncher install_IDLE \
-	checkapplepython install_versionedtools
-
+	checkapplepython
 
 install_pythonw: pythonw
 	$(INSTALL_PROGRAM) $(STRIPFLAG) pythonw "$(DESTDIR)$(prefix)/bin/pythonw$(VERSION)"
@@ -92,27 +91,6 @@
 		ln -fs "$(prefix)/bin/$${fn}" "$(DESTDIR)$(FRAMEWORKUNIXTOOLSPREFIX)/bin/$${fn}" ;\
 	done
 
-# By default most tools are installed without a version in their basename, to
-# make it easier to install (and use) several python versions side-by-side move
-# the tools to a version-specific name and add the non-versioned name as an
-# alias.
-install_versionedtools:
-	for fn in idle pydoc ;\
-	do \
-		if [ -h "$(DESTDIR)$(prefix)/bin/$${fn}3" ]; then \
-			continue ;\
-		fi ;\
-		mv "$(DESTDIR)$(prefix)/bin/$${fn}3" "$(DESTDIR)$(prefix)/bin/$${fn}$(VERSION)"  ;\
-		ln -sf "$${fn}$(VERSION)" "$(DESTDIR)$(prefix)/bin/$${fn}3" ;\
-	done
-	mv "$(DESTDIR)$(prefix)/bin/2to3" "$(DESTDIR)$(prefix)/bin/2to3-$(VERSION)"
-	ln -sf "2to3-$(VERSION)" "$(DESTDIR)$(prefix)/bin/2to3"
-	if [ ! -h "$(DESTDIR)$(prefix)/bin/python3-config" ]; then \
-		mv "$(DESTDIR)$(prefix)/bin/python3-config" "$(DESTDIR)$(prefix)/bin/python$(VERSION)-config" ;\
-		ln -sf "python$(VERSION)-config" "$(DESTDIR)$(prefix)/bin/python3-config" ; \
-	fi
-
-
 pythonw: $(srcdir)/Tools/pythonw.c Makefile
 	$(CC) $(LDFLAGS) -DPYTHONFRAMEWORK='"$(PYTHONFRAMEWORK)"' -o $@ $(srcdir)/Tools/pythonw.c -I.. -I$(srcdir)/../Include ../$(PYTHONFRAMEWORK).framework/Versions/$(VERSION)/$(PYTHONFRAMEWORK)
 
@@ -199,13 +177,11 @@
 
 $(INSTALLED_PYTHONAPP): install_Python
 
-installextras: $(srcdir)/Extras.ReadMe.txt $(srcdir)/Extras.install.py
-	$(INSTALL) -d "$(DESTDIR)$(PYTHONAPPSDIR)/Extras"
-	$(INSTALL) $(srcdir)/Extras.ReadMe.txt "$(DESTDIR)$(PYTHONAPPSDIR)/Extras/ReadMe.txt"
-	$(RUNSHARED) $(BUILDPYTHON) $(srcdir)/Extras.install.py $(srcdir)/../Demo \
-		"$(DESTDIR)$(PYTHONAPPSDIR)/Extras/Demo"
-	$(RUNSHARED) $(BUILDPYTHON) $(srcdir)/Extras.install.py $(srcdir)/Demo \
-		"$(DESTDIR)$(PYTHONAPPSDIR)/Extras/Demo.Mac"
+installextras: $(srcdir)/Extras.install.py
+	$(INSTALL) -d "$(DESTDIR)$(prefix)/share/doc/python$(VERSION)/examples"
+	$(RUNSHARED) $(BUILDPYTHON) $(srcdir)/Extras.install.py $(srcdir)/../Tools \
+		"$(DESTDIR)$(prefix)/share/doc/python$(VERSION)/examples/Tools" ; \
+		chmod -R ugo+rX,go-w "$(DESTDIR)$(prefix)/share/doc/python$(VERSION)/examples/Tools"
 
 
 checkapplepython: $(srcdir)/Tools/fixapplepython23.py

Modified: python/branches/pep-3151/Mac/PythonLauncher/Info.plist.in
==============================================================================
--- python/branches/pep-3151/Mac/PythonLauncher/Info.plist.in	(original)
+++ python/branches/pep-3151/Mac/PythonLauncher/Info.plist.in	Sat Feb 26 08:16:32 2011
@@ -40,7 +40,7 @@
 	<key>CFBundleExecutable</key>
 	<string>PythonLauncher</string>
 	<key>CFBundleGetInfoString</key>
-	<string>%VERSION%, © 2001-2008 Python Software Foundation</string>
+	<string>%VERSION%, © 2001-2011 Python Software Foundation</string>
 	<key>CFBundleIconFile</key>
 	<string>PythonLauncher.icns</string>
 	<key>CFBundleIdentifier</key>

Modified: python/branches/pep-3151/Mac/README
==============================================================================
--- python/branches/pep-3151/Mac/README	(original)
+++ python/branches/pep-3151/Mac/README	Sat Feb 26 08:16:32 2011
@@ -188,8 +188,8 @@
 framework itself, the Mac subtree, the applications and the unix tools.
 
 There is an extra target frameworkinstallextras that is not part of the
-normal frameworkinstall which installs the Demo and Tools directories
-into "/Applications/MacPython <VERSION>", this is useful for binary
+normal frameworkinstall which installs the Tools directory into
+"/Applications/MacPython <VERSION>", this is useful for binary
 distributions.
 
 What do all these programs do?

Modified: python/branches/pep-3151/Mac/Resources/app/Info.plist.in
==============================================================================
--- python/branches/pep-3151/Mac/Resources/app/Info.plist.in	(original)
+++ python/branches/pep-3151/Mac/Resources/app/Info.plist.in	Sat Feb 26 08:16:32 2011
@@ -20,7 +20,7 @@
 	<key>CFBundleExecutable</key>
 	<string>Python</string>
 	<key>CFBundleGetInfoString</key>
-	<string>%version%, (c) 2004-2010 Python Software Foundation.</string>
+	<string>%version%, (c) 2004-2011 Python Software Foundation.</string>
 	<key>CFBundleHelpBookFolder</key>
 	<array>
 		<string>Documentation</string>
@@ -37,7 +37,7 @@
 	<key>CFBundleInfoDictionaryVersion</key>
 	<string>6.0</string>
 	<key>CFBundleLongVersionString</key>
-	<string>%version%, (c) 2004-2010 Python Software Foundation.</string>
+	<string>%version%, (c) 2004-2011 Python Software Foundation.</string>
 	<key>CFBundleName</key>
 	<string>Python</string>
 	<key>CFBundlePackageType</key>
@@ -55,6 +55,6 @@
 	<key>NSAppleScriptEnabled</key>
 	<true/>
 	<key>NSHumanReadableCopyright</key>
-	<string>(c) 2004 Python Software Foundation.</string>
+	<string>(c) 2011 Python Software Foundation.</string>
 </dict>
 </plist>

Modified: python/branches/pep-3151/Mac/Resources/framework/Info.plist.in
==============================================================================
--- python/branches/pep-3151/Mac/Resources/framework/Info.plist.in	(original)
+++ python/branches/pep-3151/Mac/Resources/framework/Info.plist.in	Sat Feb 26 08:16:32 2011
@@ -17,9 +17,9 @@
 	<key>CFBundlePackageType</key>
 	<string>FMWK</string>
 	<key>CFBundleShortVersionString</key>
-	<string>%VERSION%, (c) 2004-2008 Python Software Foundation.</string>
+	<string>%VERSION%, (c) 2004-2011 Python Software Foundation.</string>
 	<key>CFBundleLongVersionString</key>
-	<string>%VERSION%, (c) 2004-2008 Python Software Foundation.</string>
+	<string>%VERSION%, (c) 2004-2011 Python Software Foundation.</string>
 	<key>CFBundleSignature</key>
 	<string>????</string>
 	<key>CFBundleVersion</key>

Modified: python/branches/pep-3151/Makefile.pre.in
==============================================================================
--- python/branches/pep-3151/Makefile.pre.in	(original)
+++ python/branches/pep-3151/Makefile.pre.in	Sat Feb 26 08:16:32 2011
@@ -108,9 +108,8 @@
 # Detailed destination directories
 BINLIBDEST=	$(LIBDIR)/python$(VERSION)
 LIBDEST=	$(SCRIPTDIR)/python$(VERSION)
-INCLUDEPY=	$(INCLUDEDIR)/python$(VERSION)
-CONFINCLUDEPY=	$(CONFINCLUDEDIR)/python$(VERSION)
-LIBP=		$(LIBDIR)/python$(VERSION)
+INCLUDEPY=	$(INCLUDEDIR)/python$(LDVERSION)
+CONFINCLUDEPY=	$(CONFINCLUDEDIR)/python$(LDVERSION)
 
 # Symbols used for using shared libraries
 SO=		@SO@
@@ -155,7 +154,7 @@
 SRCDIRS= 	@SRCDIRS@
 
 # Other subdirectories
-SUBDIRSTOO=	Include Lib Misc Demo
+SUBDIRSTOO=	Include Lib Misc
 
 # Files and directories to be distributed
 CONFIGFILES=	configure configure.in acconfig.h pyconfig.h.in Makefile.pre.in
@@ -167,6 +166,7 @@
 LIBRARY=	@LIBRARY@
 LDLIBRARY=      @LDLIBRARY@
 BLDLIBRARY=     @BLDLIBRARY@
+PY3LIBRARY=     @PY3LIBRARY@
 DLLLIBRARY=	@DLLLIBRARY@
 LDLIBRARYDIR=   @LDLIBRARYDIR@
 INSTSONAME=	@INSTSONAME@
@@ -421,7 +421,7 @@
 
 
 # Build the interpreter
-$(BUILDPYTHON):	Modules/python.o $(LIBRARY) $(LDLIBRARY)
+$(BUILDPYTHON):	Modules/python.o $(LIBRARY) $(LDLIBRARY) $(PY3LIBRARY)
 	$(LINKCC) $(PY_LDFLAGS) $(LINKFORSHARED) -o $@ Modules/python.o $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST)
 
 platform: $(BUILDPYTHON)
@@ -455,8 +455,11 @@
 		$(BLDSHARED) -o $@ $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 	fi
 
-libpython$(VERSION).dylib: $(LIBRARY_OBJS)
-	 $(CC) -dynamiclib -Wl,-single_module $(PY_LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(VERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
+libpython3.so:	libpython$(LDVERSION).so
+	$(BLDSHARED) -o $@ -Wl,-hl$@ $^
+
+libpython$(LDVERSION).dylib: $(LIBRARY_OBJS)
+	 $(CC) -dynamiclib -Wl,-single_module $(PY_LDFLAGS) -undefined dynamic_lookup -Wl,-install_name,$(prefix)/lib/libpython$(LDVERSION).dylib -Wl,-compatibility_version,$(VERSION) -Wl,-current_version,$(VERSION) -o $@ $(LIBRARY_OBJS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
 
 
 libpython$(VERSION).sl: $(LIBRARY_OBJS)
@@ -499,7 +502,6 @@
 		$(PYTHONFRAMEWORKDIR)/Versions/$(VERSION)/Resources/Info.plist
 	$(LN) -fsn $(VERSION) $(PYTHONFRAMEWORKDIR)/Versions/Current
 	$(LN) -fsn Versions/Current/$(PYTHONFRAMEWORK) $(PYTHONFRAMEWORKDIR)/$(PYTHONFRAMEWORK)
-	$(LN) -fsn Versions/Current/Headers $(PYTHONFRAMEWORKDIR)/Headers
 	$(LN) -fsn Versions/Current/Resources $(PYTHONFRAMEWORKDIR)/Resources
 
 # This rule builds the Cygwin Python DLL and import library if configured
@@ -579,7 +581,7 @@
 $(GRAMMAR_H) $(GRAMMAR_C): Parser/pgen.stamp
 Parser/pgen.stamp: $(PGEN) $(GRAMMAR_INPUT)
 		-@$(INSTALL) -d Include
-		-$(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C)
+		$(PGEN) $(GRAMMAR_INPUT) $(GRAMMAR_H) $(GRAMMAR_C)
 		-touch Parser/pgen.stamp
 
 $(PGEN):	$(PGENOBJS)
@@ -642,6 +644,9 @@
 				$(BYTESTR_DEPS) \
 				$(srcdir)/Objects/stringlib/formatter.h
 
+Objects/typeobject.o: $(srcdir)/Objects/typeslots.inc
+$(srcdir)/Objects/typeslots.inc: $(srcdir)/Include/typeslots.h $(srcdir)/Objects/typeslots.py
+	$(PYTHON) $(srcdir)/Objects/typeslots.py < $(srcdir)/Include/typeslots.h > $(srcdir)/Objects/typeslots.inc
 
 ############################################################################
 # Header files
@@ -834,7 +839,13 @@
 		else	true; \
 		fi; \
 	done
-	$(INSTALL_PROGRAM) $(BUILDPYTHON) $(DESTDIR)$(BINDIR)/python$(VERSION)$(EXE)
+	$(INSTALL_PROGRAM) $(BUILDPYTHON) $(DESTDIR)$(BINDIR)/python$(LDVERSION)$(EXE)
+	-if test "$(VERSION)" != "$(LDVERSION)"; then \
+		if test -f $(DESTDIR)$(BINDIR)/$(PYTHON)$(VERSION)$(EXE) -o -h $(DESTDIR)$(BINDIR)/$(PYTHON)$(VERSION)$(EXE); \
+		then rm -f $(DESTDIR)$(BINDIR)/python$(VERSION)$(EXE); \
+		fi; \
+		(cd $(DESTDIR)$(BINDIR); $(LN) python$(LDVERSION)$(EXE) python$(VERSION)$(EXE)); \
+	fi
 	if test -f $(LDLIBRARY); then \
 		if test -n "$(DLLLIBRARY)" ; then \
 			$(INSTALL_SHARED) $(DLLLIBRARY) $(DESTDIR)$(BINDIR); \
@@ -844,6 +855,9 @@
 				(cd $(DESTDIR)$(LIBDIR); $(LN) -sf $(INSTSONAME) $(LDLIBRARY)) \
 			fi \
 		fi; \
+		if test -n "$(PY3LIBRARY)"; then \
+			$(INSTALL_SHARED) $(PY3LIBRARY) $(DESTDIR)$(LIBDIR)/$(PY3LIBRARY); \
+		fi; \
 	else	true; \
 	fi
 
@@ -853,10 +867,22 @@
 	else true; \
 	fi
 	(cd $(DESTDIR)$(BINDIR); $(LN) python$(VERSION)$(EXE) $(PYTHON)3$(EXE))
+	-if test "$(VERSION)" != "$(LDVERSION)"; then \
+		rm -f $(DESTDIR)$(BINDIR)/python$(VERSION)-config; \
+		(cd $(DESTDIR)$(BINDIR); $(LN) -s python$(LDVERSION)-config python$(VERSION)-config); \
+		rm -f $(DESTDIR)$(LIBPC)/python-$(LDVERSION).pc; \
+		(cd $(DESTDIR)$(LIBPC); $(LN) -s python-$(VERSION).pc python-$(LDVERSION).pc); \
+	fi
 	-rm -f $(DESTDIR)$(BINDIR)/python3-config
 	(cd $(DESTDIR)$(BINDIR); $(LN) -s python$(VERSION)-config python3-config)
 	-rm -f $(DESTDIR)$(LIBPC)/python3.pc
 	(cd $(DESTDIR)$(LIBPC); $(LN) -s python-$(VERSION).pc python3.pc)
+	-rm -f $(DESTDIR)$(BINDIR)/idle3
+	(cd $(DESTDIR)$(BINDIR); $(LN) -s idle$(VERSION) idle3)
+	-rm -f $(DESTDIR)$(BINDIR)/pydoc3
+	(cd $(DESTDIR)$(BINDIR); $(LN) -s pydoc$(VERSION) pydoc3)
+	-rm -f $(DESTDIR)$(BINDIR)/2to3
+	(cd $(DESTDIR)$(BINDIR); $(LN) -s 2to3-$(VERSION) 2to3)
 
 # Install the manual page
 maninstall:
@@ -878,11 +904,11 @@
 XMLLIBSUBDIRS=  xml xml/dom xml/etree xml/parsers xml/sax
 LIBSUBDIRS=	tkinter tkinter/test tkinter/test/test_tkinter \
                 tkinter/test/test_ttk site-packages test \
-		test/decimaltestdata test/xmltestdata \
+		test/decimaltestdata test/xmltestdata test/subprocessdata \
 		test/tracedmodules test/encoded_modules \
-		concurrent concurrent/futures encodings \
+		collections concurrent concurrent/futures encodings \
 		email email/mime email/test email/test/data \
-		html json json/tests http dbm xmlrpc \
+		html json test/json_tests http dbm xmlrpc \
 		sqlite3 sqlite3/test \
 		logging csv wsgiref urllib \
 		lib2to3 lib2to3/fixes lib2to3/pgen2 lib2to3/tests \
@@ -986,7 +1012,7 @@
 python-config: $(srcdir)/Misc/python-config.in
 	# Substitution happens here, as the completely-expanded BINDIR
 	# is not available in configure
-	sed -e "s, at EXENAME@,$(BINDIR)/python$(VERSION)$(EXE)," < $(srcdir)/Misc/python-config.in >python-config
+	sed -e "s, at EXENAME@,$(BINDIR)/python$(LDVERSION)$(EXE)," < $(srcdir)/Misc/python-config.in >python-config
 
 # Install the include files
 INCLDIRSTOMAKE=$(INCLUDEDIR) $(CONFINCLUDEDIR) $(INCLUDEPY) $(CONFINCLUDEPY)
@@ -1008,13 +1034,13 @@
 
 # Install the library and miscellaneous stuff needed for extending/embedding
 # This goes into $(exec_prefix)
-LIBPL=		$(LIBP)/config
+LIBPL=		$(LIBDEST)/config-$(LDVERSION)
 
 # pkgconfig directory
 LIBPC=		$(LIBDIR)/pkgconfig
 
 libainstall:	all python-config
-	@for i in $(LIBDIR) $(LIBP) $(LIBPL) $(LIBPC); \
+	@for i in $(LIBDIR) $(LIBPL) $(LIBPC); \
 	do \
 		if test ! -d $(DESTDIR)$$i; then \
 			echo "Creating directory $$i"; \
@@ -1044,7 +1070,7 @@
 	$(INSTALL_DATA) Misc/python.pc $(DESTDIR)$(LIBPC)/python-$(VERSION).pc
 	$(INSTALL_SCRIPT) $(srcdir)/Modules/makesetup $(DESTDIR)$(LIBPL)/makesetup
 	$(INSTALL_SCRIPT) $(srcdir)/install-sh $(DESTDIR)$(LIBPL)/install-sh
-	$(INSTALL_SCRIPT) python-config $(DESTDIR)$(BINDIR)/python$(VERSION)-config
+	$(INSTALL_SCRIPT) python-config $(DESTDIR)$(BINDIR)/python$(LDVERSION)-config
 	rm python-config
 	@if [ -s Modules/python.exp -a \
 		"`echo $(MACHDEP) | sed 's/^\(...\).*/\1/'`" = "aix" ]; then \
@@ -1102,7 +1128,7 @@
 		else	true; \
 		fi; \
 	done
-	$(LN) -fsn include/python$(VERSION) $(DESTDIR)$(prefix)/Headers
+	$(LN) -fsn include/python$(LDVERSION) $(DESTDIR)$(prefix)/Headers
 	sed 's/%VERSION%/'"`$(RUNSHARED) ./$(BUILDPYTHON) -c 'import platform; print(platform.python_version())'`"'/g' < $(RESSRCDIR)/Info.plist > $(DESTDIR)$(prefix)/Resources/Info.plist
 	$(LN) -fsn $(VERSION) $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/Versions/Current
 	$(LN) -fsn Versions/Current/$(PYTHONFRAMEWORK) $(DESTDIR)$(PYTHONFRAMEWORKINSTALLDIR)/$(PYTHONFRAMEWORK)
@@ -1114,8 +1140,8 @@
 # Install a number of symlinks to keep software that expects a normal unix
 # install (which includes python-config) happy.
 frameworkinstallmaclib:
-	ln -fs "../../../$(PYTHONFRAMEWORK)" "$(DESTDIR)$(prefix)/lib/python$(VERSION)/config/libpython$(VERSION).a"
-	ln -fs "../../../$(PYTHONFRAMEWORK)" "$(DESTDIR)$(prefix)/lib/python$(VERSION)/config/libpython$(VERSION).dylib"
+	ln -fs "../../../$(PYTHONFRAMEWORK)" "$(DESTDIR)$(prefix)/lib/python$(VERSION)/config-$(LDVERSION)/libpython$(VERSION).a"
+	ln -fs "../../../$(PYTHONFRAMEWORK)" "$(DESTDIR)$(prefix)/lib/python$(VERSION)/config-$(LDVERSION)/libpython$(VERSION).dylib"
 	ln -fs "../$(PYTHONFRAMEWORK)" "$(DESTDIR)$(prefix)/lib/libpython$(VERSION).dylib"
 
 # This installs the IDE, the Launcher and other apps into /Applications
@@ -1129,7 +1155,7 @@
 frameworkaltinstallunixtools:
 	cd Mac && $(MAKE) altinstallunixtools DESTDIR="$(DESTDIR)"
 
-# This installs the Demos and Tools into the applications directory.
+# This installs the Tools into the applications directory.
 # It is not part of a normal frameworkinstall
 frameworkinstallextras:
 	cd Mac && $(MAKE) installextras DESTDIR="$(DESTDIR)"
@@ -1230,7 +1256,7 @@
 	done
 	-rm -f core Makefile Makefile.pre config.status \
 		Modules/Setup Modules/Setup.local Modules/Setup.config \
-		Modules/ld_so_aix Misc/python.pc
+		Modules/ld_so_aix Modules/python.exp Misc/python.pc
 	-rm -f python*-gdb.py
 	-rm -f pybuilddir.txt
 	find $(srcdir) '(' -name '*.fdc' -o -name '*~' \
@@ -1297,3 +1323,6 @@
 .PHONY: gdbhooks
 
 # IF YOU PUT ANYTHING HERE IT WILL GO AWAY
+# Local Variables:
+# mode: makefile
+# End:

Modified: python/branches/pep-3151/Misc/ACKS
==============================================================================
--- python/branches/pep-3151/Misc/ACKS	(original)
+++ python/branches/pep-3151/Misc/ACKS	Sat Feb 26 08:16:32 2011
@@ -12,12 +12,14 @@
 and the list is in rough alphabetical order by last names.
 
 David Abrahams
+Ron Adam
 Jim Ahlstrom
 Farhan Ahmad
 Matthew Ahrens
 Nir Aides
 Yaniv Aknin
 Jyrki Alakuijala
+Ray Allen
 Billy G. Allie
 Kevin Altis
 Joe Amenta
@@ -44,6 +46,7 @@
 Greg Ball
 Luigi Ballabio
 Jeff Balogh
+Matt Bandy
 Michael J. Barber
 Chris Barker
 Nick Barnes
@@ -76,6 +79,7 @@
 Steven Bethard
 Stephen Bevan
 Ron Bickers
+Adrian von Bidder
 David Binger
 Dominic Binks
 Philippe Biondi
@@ -235,6 +239,7 @@
 Maxim Dzumanenko
 Walter Dörwald
 Hans Eckardt
+Rodolpho Eckhardt
 Grant Edwards
 John Ehresman
 Eric Eisner
@@ -257,6 +262,7 @@
 David Everly
 Greg Ewing
 Martijn Faassen
+Clovis Fabricio
 Andreas Faerber
 Bill Fancher
 Troy J. Farrell
@@ -317,6 +323,8 @@
 Hans de Graaff
 Eddy De Greef
 Duncan Grisby
+Fabian Groffen
+Eric Groo
 Dag Gruneau
 Michael Guravage
 Lars Gustäbel
@@ -337,6 +345,7 @@
 Lynda Hardman
 Derek Harland
 Jason Harper
+Brian Harring
 Larry Hastings
 Shane Hathaway
 Rycharde Hawkes
@@ -392,6 +401,7 @@
 Fredrik Håård
 Mihai Ibanescu
 Lars Immisch
+Bobby Impollonia
 Meador Inge
 Tony Ingraldi
 John Interrante
@@ -415,6 +425,7 @@
 Gregory K. Johnson
 Simon Johnston
 Thomas Jollans
+Nicolas Joly
 Evan Jones
 Jeremy Jones
 Richard Jones
@@ -447,6 +458,7 @@
 Steve Kirsch
 Sebastian Kirsche
 Ron Klatchko
+Reid Kleckner
 Bastian Kleineidam
 Bob Kline
 Matthias Klose
@@ -455,6 +467,7 @@
 Pat Knight
 Greg Kochanski
 Damon Kohler
+Vlad Korolev
 Joseph Koshy
 Maksim Kozyarchuk
 Stefan Krah
@@ -467,6 +480,7 @@
 Ivan Krstić
 Andrew Kuchling
 Vladimir Kushnir
+Ross Lagerwall
 Cameron Laird
 Jean-Baptiste "Jiba" Lamy
 Torsten Landschoff
@@ -497,6 +511,7 @@
 Christopher Tur Lesniewski-Laas
 Mark Levinson
 William Lewis
+Xuanji Li
 Robert van Liere
 Ross Light
 Shawn Ligocki
@@ -534,6 +549,7 @@
 Doug Marien
 Alex Martelli
 Anthony Martin
+Owen Martin
 Sébastien Martini
 Roger Masse
 Nick Mathewson
@@ -558,6 +574,7 @@
 Mike Meyer
 Steven Miale
 Trent Mick
+Stan Mihai
 Aristotelis Mikropoulos
 Damien Miller
 Chad Miller
@@ -637,6 +654,7 @@
 Gabriel de Perthuis
 Tim Peters
 Benjamin Peterson
+Joe Peterson
 Chris Petrilli
 Bjorn Pettersen
 Geoff Philbrick
@@ -663,6 +681,7 @@
 Steve Purcell
 Fernando Pérez
 Eduardo Pérez
+Pierre Quentel
 Brian Quinlan
 Anders Qvist
 Burton Radons
@@ -684,6 +703,7 @@
 Steven Reiz
 Roeland Rengelink
 Tim Rice
+Francesco Ricciardi
 Jan Pieter Riegel
 Armin Rigo
 Nicholas Riley
@@ -693,6 +713,7 @@
 Mark Roberts
 Jim Robinson
 Andy Robinson
+Mark Roddy
 Kevin Rodgers
 Giampaolo Rodola
 Mike Romberg
@@ -721,14 +742,17 @@
 George Sakkis
 Rich Salz
 Kevin Samborn
+Adrian Sampson
 Ilya Sandler
 Mark Sapiro
 Ty Sarna
 Ben Sayer
+Andrew Schaaf
 Michael Scharf
 Andreas Schawo
 Neil Schemenauer
 David Scherer
+Bob Schmertz
 Gregor Schmid
 Ralf Schmitt
 Michael Schneider
@@ -774,6 +798,7 @@
 Dirk Soede
 Paul Sokolovsky
 Cody Somerville
+Edoardo Spadolini
 Clay Spence
 Per Spilling
 Joshua Spoerri
@@ -793,6 +818,7 @@
 Ken Stox
 Dan Stromberg
 Daniel Stutzbach
+Andreas Stührk
 Pal Subbiah
 Nathan Sullivan
 Mark Summerfield
@@ -816,7 +842,9 @@
 Tobias Thelen
 James Thomas
 Robin Thomas
+Jeremy Thurgood
 Eric Tiedemann
+July Tikhonov
 Tracy Tims
 Oren Tirosh
 Jason Tishler
@@ -848,6 +876,7 @@
 Atul Varma
 Dmitry Vasiliev
 Alexandre Vassalotti
+Nadeem Vawda
 Frank Vercruesse
 Mike Verdone
 Jaap Vermeulen
@@ -864,6 +893,7 @@
 Charles Waldman
 Richard Walker
 Larry Wall
+Kevin Walzer
 Rodrigo Steinmuller Wanderley
 Greg Ward
 Barry Warsaw
@@ -880,6 +910,7 @@
 Rickard Westman
 Jeff Wheeler
 Christopher White
+David White
 Mats Wichmann
 Truida Wiedijk
 Felix Wiemann

Deleted: python/branches/pep-3151/Misc/AIX-NOTES
==============================================================================
--- python/branches/pep-3151/Misc/AIX-NOTES	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,155 +0,0 @@
-Subject: AIX - Misc/AIX-NOTES
-From: Vladimir Marangozov <Vladimir.Marangozov at imag.fr>
-To: guido at CNRI.Reston.Va.US (Guido van Rossum)
-Date: Wed, 6 Aug 1997 11:41:00 +0200 (EET)
-
-==============================================================================
-                              COMPILER INFORMATION
-------------------------------------------------------------------------------
-
-(1) A problem has been reported with "make test" failing because of "weird
-    indentation."  Searching the comp.lang.python newsgroup reveals several
-    threads on this subject, and it seems to be a compiler bug in an old
-    version of the AIX CC compiler.  However, the compiler/OS combination
-    which has this problem is not identified.  In preparation for the 1.4
-    release, Vladimir Marangozov (Vladimir.Marangozov at imag.fr) and Manus Hand
-    (mhand at csn.net) reported no such troubles for the following compilers and
-    operating system versions:
-       AIX C compiler version 3.1.2 on AIX 4.1.3 and AIX 4.1.4
-       AIX C compiler version 1.3.0 on AIX 3.2.5
-    If you have this problem, please report the compiler/OS version.
-
-(2) Stefan Esser (se at MI.Uni-Koeln.DE), in work done to compile Python
-    1.0.0 on AIX 3.2.4, reports that AIX compilers don't like the LANG
-    environment varaiable set to European locales.  This makes the compiler
-    generate floating point constants using "," as the decimal separator,
-    which the assembler doesn't understand (or perhaps it is the other way
-    around, with the assembler expecting, but not getting "," in float
-    numbers).  "LANG=C; export LANG" solves the problem, as does
-    "LANG=C $(MAKE) ..." in the master Makefile.
-
-(3) The cc (or xlc) compiler considers "Python/ceval.c" too complex to
-    optimize, except when invoked with "-qmaxmem=4000"
-
-(4) Some problems (due to _AIX not being #defined) when python 1.0.0 was
-    compiled using 'gcc -ansi' were reported by Stefan Esser, but were not
-    investigated.
-
-(5) The cc compiler has internal variables named "__abs" and "__div".  These
-    names are reserved and may not be used as program variables in compiled
-    source.  (As an anecdote in support of this, the implementation of
-    Python/operator.c had this problem in the 1.4 beta releases, and the
-    solution was to re#define some core-source variables having these names,
-    to give these python variables different names if the build is being done
-    on AIX.)
-
-(6) As mentioned in the README, builds done immediately after previous builds
-    (without "make clean" or "make clobber") sometimes fail for mysterious
-    reasons.  There are some unpredictable results when the configuration
-    is changed (that is, if you "configure" with different parameters) or if
-    intermediate changes are made to some files.  Performing "make clean" or
-    "make clobber" resolves the problems.
-
-==============================================================================
-                                THREAD SUPPORT
-------------------------------------------------------------------------------
-
-As of AIX version 4, there are two (incompatible) types of pthreads on AIX:
-        a)  AIX DCE pthreads (on AIX 3.2.5)
-        b)  AIX 4 pthreads (on AIX 4.1 and up)
-Support has been added to Python to handle the distinction.
-
-The cc and gcc compilers do not initialize pthreads properly. The only
-compilers that can initialize pthreads properly are IBM *_r* compilers,
-which use the crt0_r.o module, and which invoke ld with the reentrant
-version of libc (libc_r).
-
-In order to enable thread support, follow these steps:
-   1.  Uncomment the thread module in Modules/Setup
-   2.  configure --without-gcc --with-thread ...
-   3.  make CC="cc_r" OPT="-O -qmaxmem=4000"
-
-For example, to make with both threads and readline, use:
-  ./configure --without-gcc --with-thread --with-readline=/usr/local/lib
-  make CC=cc_r OPT="-O2 -qmaxmem=4000"
-
-If the "make" which is used ignores the "CC=cc_r" directive, one could alias
-the cc command to cc_r (for example, in C-shell, perform an "alias cc cc_r").
-
-Vladimir Marangozov (Vladimir.Marangozov at imag.fr) provided this information,
-and he reports that a cc_r build initializes threads properly and that all
-demos on threads run okay with cc_r.
-
-==============================================================================
-                            SHARED LIBRARY SUPPORT
-------------------------------------------------------------------------------
-
-AIX shared library support was added to Python in the 1.4 release by Manus
-Hand (mhand at csn.net) and Vladimir Marangozov (Vladimir.Marangozov at imag.fr).
-
-Python modules may now be built as shared libraries on AIX using the normal
-process of uncommenting the "*shared*" line in Modules/Setup before the
-build.
-
-AIX shared libraries require that an "export" and "import" file be provided
-at compile time to list all extern symbols which may be shared between
-modules.  The "export" file (named python.exp) for the modules and the
-libraries that belong to the Python core is created by the "makexp_aix"
-script before performing the link of the python binary. It lists all global
-symbols (exported during the link) of the modules and the libraries that
-make up the python executable.
-
-When shared library modules (.so files) are made, a second shell script
-is invoked.  This script is named "ld_so_aix" and is also provided with
-the distribution in the Modules subdirectory.  This script acts as an "ld"
-wrapper which hides the explicit management of "export" and "import" files;
-it adds the appropriate arguments (in the appropriate order) to the link
-command that creates the shared module.  Among other things, it specifies
-that the "python.exp" file is an "import" file for the shared module.
-
-At the time of this writing, neither the python.exp file nor the makexp_aix
-or ld_so_aix scripts are installed by the make procedure, so you should
-remember to keep these and/or copy them to a different location for
-safekeeping if you wish to use them to add shared extension modules to
-python.  However, if the make process has been updated since this writing,
-these files MAY have been installed for you during the make by the
-LIBAINSTALL rule, in which case the need to make safe copies is obviated.
-
-If you wish to add a shared extension module to the language, you would follow
-the steps given in the example below (the example adds the shared extension
-module "spam" to python):
-    1.  Make sure that "ld_so_aix" and "makexp_aix" are in your path.
-    2.  The "python.exp" file should be in the current directory.
-    3.  Issue the following commands or include them in your Makefile:
-            cc -c spammodule.c
-            ld_so_aix cc spammodule.o -o spammodule.so
-
-For more detailed information on the shared library support, examine the
-contents of the "ld_so_aix" and "makexp_aix" scripts or refer to the AIX
-documentation.
-
-NOTE:  If the extension module is written in C++ and contains templates,
-       an alternative to "ld_so_aix" is the /usr/lpp/xlC/bin/makeC++SharedLib
-       script.  Chris Myers (myers at TC.Cornell.EDU) reports that ld_so_aix
-       works well for some C++ (including the C++ that is generated
-       automatically by the Python SWIG package [SWIG can be found at
-       http://www.cs.utah.edu/~beazley/SWIG/swig.html]).  However, it is not
-       known whether makeC++SharedLib can be used as a complete substitute
-       for ld_so_aix.
-
-According to Gary Hook from IBM, the format of the export file changed
-in AIX 4.2.  For AIX 4.2 and later, a period "." is required on the
-first line after "#!".  If python crashes while importing a shared
-library, you can try modifying the LINKCC variable in the Makefile.
-It probably looks like this:
-
-	LINKCC=     $(srcdir)/Modules/makexp_aix Modules/python.exp \"\" $(LIBRARY); $(PURIFY) $(CXX)
-
-You should modify the \"\" to be a period:
-
-	LINKCC=     $(srcdir)/Modules/makexp_aix Modules/python.exp . $(LIBRARY); $(PURIFY) $(CXX)
-
-Using a period fixed the problem in the snake farm.  YMMV.
-This fix has been incorporated into Python 2.3.
-
-==============================================================================

Modified: python/branches/pep-3151/Misc/NEWS
==============================================================================
--- python/branches/pep-3151/Misc/NEWS	(original)
+++ python/branches/pep-3151/Misc/NEWS	Sat Feb 26 08:16:32 2011
@@ -2,10 +2,986 @@
 Python News
 +++++++++++
 
+What's New in Python 3.3 Alpha 1?
+=================================
+
+*Release date: XX-XXX-20XX*
+
+Core and Builtins
+-----------------
+
+- Issue #11286: Raise a ValueError from calling PyMemoryView_FromBuffer with
+  a buffer struct having a NULL data pointer.
+
+- Issue #11272: On Windows, input() strips '\r' (and not only '\n'), and
+  sys.stdin uses universal newline (replace '\r\n' by '\n').
+
+- Issue #10830: Fix PyUnicode_FromFormatV("%c") for non-BMP characters on
+  narrow build.
+
+- Issue #11168: Remove filename debug variable from PyEval_EvalFrameEx().
+  It encoded the Unicode filename to UTF-8, but the encoding fails on
+  undecodable filename (on surrogate characters) which raises an unexpected
+  UnicodeEncodeError on recursion limit.
+
+- Issue #11187: Remove bootstrap code (use ASCII) of
+  PyUnicode_AsEncodedString(), it was replaced by a better fallback (use the
+  locale encoding) in PyUnicode_EncodeFSDefault().
+
+- Check for NULL result in PyType_FromSpec.
+
+- Issue #10516: New copy() and clear() methods for lists.
+
+Library
+-------
+
+- Issue #11297: Add collections.ChainMap().
+
+- Issue #10755: Add the posix.fdlistdir() function.  Patch by Ross Lagerwall.
+
+- Issue #4761: Add the *at() family of functions (openat(), etc.) to the posix
+  module.  Patch by Ross Lagerwall.
+
+- Issue #7322: Trying to read from a socket's file-like object after a timeout
+  occurred now raises an error instead of silently losing data.
+
+- Issue 11291: poplib.POP no longer suppresses errors on quit().
+
+- Issue 11177: asyncore's create_socket() arguments can now be omitted.
+
+- Issue #6064: Add a ``daemon`` keyword argument to the threading.Thread
+  and multiprocessing.Process constructors in order to override the
+  default behaviour of inheriting the daemonic property from the current
+  thread/process.
+
+- Issue #10956: Buffered I/O classes retry reading or writing after a signal
+  has arrived and the handler returned successfully.
+
+- Issue #10784: New os.getpriority() and os.setpriority() functions.
+
+- Issue #11114: Fix catastrophic performance of tell() on text files (up
+  to 1000x faster in some cases).  It is still one to two order of magnitudes
+  slower than binary tell().
+
+- Issue 10882: Add os.sendfile function.
+
+- Issue #10868: Allow usage of the register method of an ABC as a class
+  decorator.
+
+- Issue #11224: Fixed a regression in tarfile that affected the file-like
+  objects returned by TarFile.extractfile() regarding performance, memory
+  consumption and failures with the stream interface.
+
+- Issue #10924: Adding salt and Modular Crypt Format to crypt library.
+  Moved old C wrapper to _crypt, and added a Python wrapper with
+  enhanced salt generation and simpler API for password generation.
+
+- Issue #11074: Make 'tokenize' so it can be reloaded.
+
+- Issue #11085: Moved collections abstract base classes into a separate
+  module called collections.abc, following the pattern used by importlib.abc.
+  For backwards compatibility, the names are imported into the collections
+  module.
+
+- Issue #4681: Allow mmap() to work on file sizes and offsets larger than
+  4GB, even on 32-bit builds.  Initial patch by Ross Lagerwall, adapted for
+  32-bit Windows.
+
+- Issue #11169: compileall module uses repr() to format filenames and paths to
+  escape surrogate characters and show spaces.
+
+- Issue #11089: Fix performance issue limiting the use of ConfigParser()
+  with large config files.
+
+- Issue #10276: Fix the results of zlib.crc32() and zlib.adler32() on buffers
+  larger than 4GB.  Patch by Nadeem Vawda.
+
+Build
+-----
+
+- Issue #11268: Prevent Mac OS X Installer failure if Documentation
+  package had previously been installed.
+
+Tests
+-----
+
+- Issue #10512: Properly close sockets under test.test_cgi.
+
+- Issue #10992: Make tests pass under coverage.
+
+- Issue #10826: Prevent sporadic failure in test_subprocess on Solaris due
+  to open door files.
+
+- Issue #10990: Prevent tests from clobbering a set trace function.
+
+
+What's New in Python 3.2?
+=========================
+
+*Release date: 20-Feb-2011*
+
+Core and Builtins
+-----------------
+
+- Issue #11249: Fix potential crashes when using the limited API.
+
+Build
+-----
+
+- Issue #11222: Fix non-framework shared library build on Mac OS X.
+
+- Issue #11184: Fix large-file support on AIX.
+
+- Issue #941346: Fix broken shared library build on AIX.
+
+Documentation
+-------------
+
+- Issue #10709: Add updated AIX notes in Misc/README.AIX.
+
+
+What's New in Python 3.2 Release Candidate 3?
+=============================================
+
+*Release date: 13-Feb-2011*
+
+Core and Builtins
+-----------------
+
+- Issue #11134: Add missing fields to typeslots.h.
+
+- Issue #11135: Remove redundant doc field from PyType_Spec.
+
+- Issue #11067: Add PyType_GetFlags, to support PyUnicode_Check in the limited
+  ABI.
+
+- Issue #11118: Fix bogus export of None in python3.dll.
+
+Library
+-------
+
+- Issue #11116: any error during addition of a message to a mailbox now causes a
+  rollback, instead of leaving the mailbox partially modified.
+
+- Issue #11132: Fix passing of "optimize" parameter when recursing in
+  compileall.compile_dir().
+
+- Issue #11110: Fix a potential decref of a NULL in sqlite3.
+
+- Issue #8275: Fix passing of callback arguments with ctypes under Win64.  Patch
+  by Stan Mihai.
+
+Build
+-----
+
+- Issue #11079: The /Applications/Python x.x folder created by the Mac OS X
+  installers now includes a link to the installed documentation and no longer
+  includes an Extras directory.  The Tools directory is now installed in the
+  framework under share/doc.
+
+- Issue #11121: Fix building with --enable-shared.
+
+Tests
+-----
+
+- Issue #10971: test_zipimport_support is once again compatible with the refleak
+  hunter feature of test.regrtest.
+
+
+What's New in Python 3.2 Release Candidate 2?
+=============================================
+
+*Release date: 30-Jan-2011*
+
+Core and Builtins
+-----------------
+
+- Issue #10451: memoryview objects could allow to mutate a readable buffer.
+  Initial patch by Ross Lagerwall.
+
+Library
+-------
+
+- Issue #9124: mailbox now accepts binary input and reads and writes mailbox
+  files in binary mode, using the email package's binary support to parse
+  arbitrary email messages.  StringIO and text file input is deprecated,
+  and string input fails early if non-ASCII characters are used, where
+  previously it would fail when the email was processed in a later step.
+
+- Issue #10845: Mitigate the incompatibility between the multiprocessing
+  module on Windows and the use of package, zipfile or directory execution
+  by special casing main modules that actually *are* called __main__.py.
+
+- Issue #11045: Protect logging call against None argument.
+
+- Issue #11052: Correct IDLE menu accelerators on Mac OS X for Save
+  commands.
+
+- Issue #11053: Fix IDLE "Syntax Error" windows to behave as in 2.x,
+  preventing a confusing hung appearance on OS X with the windows
+  obscured.
+
+- Issue #10940: Workaround an IDLE hang on Mac OS X 10.6 when using the
+  menu accelerators for Open Module, Go to Line, and New Indent Width.
+  The accelerators still work but no longer appear in the menu items.
+
+- Issue #10989: Fix a crash on SSLContext.load_verify_locations(None, True).
+
+- Issue #11020: Command-line pyclbr was broken because of missing 2-to-3
+  conversion.
+
+- Issue #11019: Fixed BytesGenerator so that it correctly handles a Message
+  with a None body.
+
+- Issue #11014: Make 'filter' argument in tarfile.Tarfile.add() into a
+  keyword-only argument.  The preceding positional argument was deprecated,
+  so it made no sense to add filter as a positional argument.
+
+- Issue #11004: Repaired edge case in deque.count().
+
+- Issue #10974: IDLE no longer crashes if its recent files list includes files
+  with non-ASCII characters in their path names.
+
+- Have hashlib.algorithms_available and hashlib.algorithms_guaranteed both
+  return sets instead of one returning a tuple and the other a frozenset.
+
+- Issue #10987: Fix the recursion limit handling in the _pickle module.
+
+- Issue #10983: Fix several bugs making tunnel requests in http.client.
+
+- Issue #10955: zipimport uses ASCII encoding instead of cp437 to decode
+  filenames, at bootstrap, if the codec registry is not ready yet. It is still
+  possible to have non-ASCII filenames using the Unicode flag (UTF-8 encoding)
+  for all file entries in the ZIP file.
+
+- Issue #10949: Improved robustness of rotating file handlers.
+
+- Issue #10955: Fix a potential crash when trying to mmap() a file past its
+  length.  Initial patch by Ross Lagerwall.
+
+- Issue #10898: Allow compiling the posix module when the C library defines
+  a symbol named FSTAT.
+
+- Issue #10980: the HTTP server now encodes headers with iso-8859-1 (latin1)
+  encoding.  This is the preferred encoding of PEP 3333 and the base encoding
+  of HTTP 1.1.
+
+- To match the behaviour of HTTP server, the HTTP client library now also
+  encodes headers with iso-8859-1 (latin1) encoding.  It was already doing
+  that for incoming headers which makes this behaviour now consistent in
+  both incoming and outgoing direction.
+
+- Issue #9509: argparse now properly handles IOErrors raised by
+  argparse.FileType.
+
+- Issue #10961: The new pydoc server now better handles exceptions raised
+  during request handling.
+
+- Issue #10680: Fix mutually exclusive arguments for argument groups in
+  argparse.
+
+Build
+-----
+
+- Issue #11054: Allow Mac OS X installer builds to again work on 10.5 with
+  the system-provided Python.
+
+
+What's New in Python 3.2 Release Candidate 1
+============================================
+
+*Release date: 16-Jan-2011*
+
+Core and Builtins
+-----------------
+
+- Issue #10889: range indexing and slicing now works correctly on ranges with
+  a length that exceeds sys.maxsize.
+
+- Issue #10892: Don't segfault when trying to delete __abstractmethods__ from a
+  class.
+
+- Issue #8020: Avoid a crash where the small objects allocator would read
+  non-Python managed memory while it is being modified by another thread.  Patch
+  by Matt Bandy.
+
+- Issue #10841: On Windows, set the binary mode on stdin, stdout, stderr and all
+  io.FileIO objects (to not translate newlines, \r\n <=> \n).  The Python parser
+  translates newlines (\r\n => \n).
+
+- Remove buffer API from stable ABI for now, see #10181.
+
+- Issue #8651: PyArg_Parse*() functions raise an OverflowError if the file
+  doesn't have PY_SSIZE_T_CLEAN define and the size doesn't fit in an int
+  (length bigger than 2^31-1 bytes).
+
+- Issue #9015, #9611: FileIO.readinto(), FileIO.write(), os.write() and
+  stdprinter.write() clamp the length to 2^31-1 on Windows.
+
+- Issue #8278: On Windows and with a NTFS filesystem, os.stat() and os.utime()
+  can now handle dates after 2038.
+
+- Issue #10780: PyErr_SetFromWindowsErrWithFilename() and
+  PyErr_SetExcFromWindowsErrWithFilename() decode the filename from the
+  filesystem encoding instead of UTF-8.
+
+- Issue #10779: PyErr_WarnExplicit() decodes the filename from the filesystem
+  encoding instead of UTF-8.
+
+- Add sys.flags attribute for the new -q command-line option.
+
+Library
+-------
+
+- Issue #10916: mmap should not segfault when a file is mapped using 0 as length
+  and a non-zero offset, and an attempt to read past the end of file is made
+  (IndexError is raised instead).  Patch by Ross Lagerwall.
+
+- Issue #10907: Warn OS X 10.6 IDLE users to use ActiveState Tcl/Tk 8.5, rather
+  than the currently problematic Apple-supplied one, when running with the
+  64-/32-bit installer variant.
+
+- Issue #4953: cgi.FieldStorage and cgi.parse() parse the request as bytes, not
+  as unicode, and accept binary files. Add encoding and errors attributes to
+  cgi.FieldStorage. Patch written by Pierre Quentel (with many inputs by Glenn
+  Linderman).
+
+- Add encoding and errors arguments to urllib.parse_qs() and urllib.parse_qsl().
+
+- Issue #10899: No function type annotations in the standard library.  Removed
+  function type annotations from _pyio.py.
+
+- Issue #10875: Update Regular Expression HOWTO; patch by 'SilentGhost'.
+
+- Issue #10872: The repr() of TextIOWrapper objects now includes the mode
+  if available.
+
+- Issue #10869: Fixed bug where ast.increment_lineno modified the root node
+  twice.
+
+- Issue #5871: email.header.Header.encode now raises an error if any
+  continuation line in the formatted value has no leading white space and looks
+  like a header.  Since Generator uses Header to format all headers, this check
+  is made for all headers in any serialized message at serialization time.  This
+  provides protection against header injection attacks.
+
+- Issue #10859: Make ``contextlib.GeneratorContextManager`` officially
+  private by renaming it to ``_GeneratorContextManager``.
+
+- Issue #10042: Fixed the total_ordering decorator to handle cross-type
+  comparisons that could lead to infinite recursion.
+
+- Issue #10686: the email package now :rfc:`2047`\ -encodes headers with
+  non-ASCII bytes (parsed by a Bytes Parser) when doing conversion to 7bit-clean
+  presentation, instead of replacing them with ?s.
+
+- email.header.Header was incorrectly encoding folding white space when
+  rfc2047-encoding header values with embedded newlines, leaving them without
+  folding whitespace.  It now uses the continuation_ws, as it does for
+  continuation lines that it creates itself.
+
+- Issue #1777412, #10827: Changed the rules for 2-digit years. The
+  time.asctime(), time.ctime() and time.strftime() functions will now format
+  any year when ``time.accept2dyear`` is False and will accept years >= 1000
+  otherwise. ``time.mktime`` and ``time.strftime`` now accept full range
+  supported by the OS. With Visual Studio or on Solaris, the year is limited to
+  the range [1; 9999]. Conversion of 2-digit years to 4-digit is deprecated.
+
+- Issue #7858: Raise an error properly when os.utime() fails under Windows
+  on an existing file.
+
+- Issue #3839: wsgiref should not override a Content-Length header set by
+  the application.  Initial patch by Clovis Fabricio.
+
+- Issue #10492: bdb.Bdb.run() only traces the execution of the code, not the
+  compilation (if the input is a string).
+
+- Issue #7995: When calling accept() on a socket with a timeout, the returned
+  socket is now always blocking, regardless of the operating system.
+
+- Issue #10756: atexit normalizes the exception before displaying it. Patch by
+  Andreas Stührk.
+
+- Issue #10790: email.header.Header.append's charset logic now works correctly
+  for charsets whose output codec is different from its input codec.
+
+- Issue #10819: SocketIO.name property returns -1 when its closed, instead of
+  raising a ValueError, to fix repr().
+
+- Issue #8650: zlib.compress() and zlib.decompress() raise an OverflowError if
+  the input buffer length doesn't fit into an unsigned int (length bigger than
+  2^32-1 bytes).
+
+- Issue #6643: Reinitialize locks held within the threading module after fork to
+  avoid a potential rare deadlock or crash on some platforms.
+
+- Issue #10806, issue #9905: Fix subprocess pipes when some of the standard file
+  descriptors (0, 1, 2) are closed in the parent process.  Initial patch by Ross
+  Lagerwall.
+
+- `unittest.TestCase` can be instantiated without a method name; for simpler
+  exploration from the interactive interpreter.
+
+- Issue #10798: Reject supporting concurrent.futures if the system has too
+  few POSIX semaphores.
+
+- Issue #10807: Remove base64, bz2, hex, quopri, rot13, uu and zlib codecs from
+  the codec aliases. They are still accessible via codecs.lookup().
+
+- Issue #10801: In zipfile, support different encodings for the header and the
+  filenames.
+
+- Issue #6285: IDLE no longer crashes on missing help file; patch by Scott
+  David Daniels.
+
+- Fix collections.OrderedDict.setdefault() so that it works in subclasses that
+  define __missing__().
+
+- Issue #10786: unittest.TextTestRunner default stream no longer bound at import
+  time. `sys.stderr` now looked up at instantiation time.  Fix contributed by
+  Mark Roddy.
+
+- Issue #10753: Characters ';','=' and ',' in the PATH_INFO environment variable
+  won't be quoted when the URI is constructed by the wsgiref.util 's request_uri
+  method. According to RFC 3986, these characters can be a part of params in
+  PATH component of URI and need not be quoted.
+
+- Issue #10738: Fix webbrowser.Opera.raise_opts.
+
+- Issue #9824: SimpleCookie now encodes , and ; in values to cater to how
+  browsers actually parse cookies.
+
+- Issue #9333: os.symlink now available regardless of user privileges.  The
+  function now raises OSError on Windows >=6.0 when the user is unable to create
+  symbolic links. XP and 2003 still raise NotImplementedError.
+
+- Issue #10783: struct.pack() no longer implicitly encodes unicode to UTF-8.
+
+- Issue #10730: Add SVG mime types to mimetypes module.
+
+- Issue #10768: Make the Tkinter ScrolledText widget work again.
+
+- Issue #10777: Fix "dictionary changed size during iteration" bug in
+  ElementTree register_namespace().
+
+- Issue #10626: test_logging now preserves logger disabled states.
+
+- Issue #10774: test_logging now removes temp files created during tests.
+
+- Issue #5258/#10642: if site.py encounters a .pth file that generates an error,
+  it now prints the filename, line number, and traceback to stderr and skips
+  the rest of that individual file, instead of stopping processing entirely.
+
+- Issue #10763: subprocess.communicate() closes stdout and stderr if both are
+  pipes (bug specific to Windows).
+
+- Issue #1693546: fix email.message RFC 2231 parameter encoding to be in better
+  compliance (no "s around encoded values).
+
+- Improved the diff message in the unittest module's assertCountEqual().
+
+- Issue #1155362: email.utils.parsedate_tz now handles a missing space before
+  the '-' of a timezone field as well as before a '+'.
+
+- Issue #4871: The zipfile module now gives a more useful error message if
+  an attempt is made to use a string to specify the archive password.
+
+- Issue #10750: The ``raw`` attribute of buffered IO objects is now read-only.
+
+- Deprecated assertDictContainsSubset() in the unittest module.
+
+C-API
+-----
+
+- Issue #10913: Deprecate misleading functions PyEval_AcquireLock() and
+  PyEval_ReleaseLock().  The thread-state aware APIs should be used instead.
+
+- Issue #10333: Remove ancient GC API, which has been deprecated since Python
+  2.2.
+
+Build
+-----
+
+- Issue #10843: Update third-party library versions used in OS X 32-bit
+  installer builds: bzip2 1.0.6, readline 6.1.2, SQLite 3.7.4 (with FTS3/FTS4
+  and RTREE enabled), and ncursesw 5.5 (wide-char support enabled).
+
+- Issue #10820: Fix OS X framework installs to support version-specific
+  scripts (#10679).
+
+- Issue #7716: Under Solaris, don't assume existence of /usr/xpg4/bin/grep in
+  the configure script but use $GREP instead.  Patch by Fabian Groffen.
+
+- Issue #10475: Don't hardcode compilers for LDSHARED/LDCXXSHARED on NetBSD
+  and DragonFly BSD.  Patch by Nicolas Joly.
+
+- Issue #10679: The "idle", "pydoc" and "2to3" scripts are now installed with
+  a version-specific suffix on "make altinstall".
+
+- Issue #10655: Fix the build on PowerPC on Linux with GCC when building with
+  timestamp profiling (--with-tsc): the preprocessor test for the PowerPC
+  support now looks for "__powerpc__" as well as "__ppc__": the latter seems to
+  only be present on OS X; the former is the correct one for Linux with GCC.
+
+Tools/Demos
+-----------
+
+- Issue #10843: Install the Tools directory on OS X in the applications Extras
+  (/Applications/Python 3.n/Extras/) where the Demo directory had previous been
+  installed.
+
+- Issue #7962: The Demo directory is gone.  Most of the old and unmaintained
+  demos have been removed, others integrated in documentation or a new
+  Tools/demo subdirectory.
+
+- Issue #10502: Addition of the unittestgui tool. Originally by Steve Purcell.
+  Updated for test discovery by Mark Roddy and Python 3 compatibility by Brian
+  Curtin.
+
+Tests
+-----
+
+- Issue #10822: Fix test_posix:test_getgroups failure under Solaris.  Patch
+  by Ross Lagerwall.
+
+- Make the --coverage flag work for test.regrtest.
+
+- Issue #1677694: Refactor and improve test_timeout.  Original patch by
+  Björn Lindqvist.
+
+- Issue #5485: Add tests for the UseForeignDTD method of expat parser objects.
+  Patch by Jean-Paul Calderone and Sandro Tosi.
+
+- Issue #6293: Have regrtest.py echo back sys.flags.  This is done by default in
+  whole runs and enabled selectively using ``--header`` when running an explicit
+  list of tests.  Original patch by Collin Winter.
+
+
+What's New in Python 3.2 Beta 2?
+================================
+
+*Release date: 19-Dec-2010*
+
+Core and Builtins
+-----------------
+
+- Issue #8844: Regular and recursive lock acquisitions can now be interrupted
+  by signals on platforms using pthreads.  Patch by Reid Kleckner.
+
+- Issue #4236: PyModule_Create2 now checks the import machinery directly
+  rather than the Py_IsInitialized flag, avoiding a Fatal Python
+  error in certain circumstances when an import is done in __del__.
+
+- Issue #5587: add a repr to dict_proxy objects.  Patch by David Stanek and
+  Daniel Urban.
+
+Library
+-------
+
+- Issue #3243:  Support iterable bodies in httplib. Patch Contributions by
+  Xuanji Li and Chris AtLee.
+
+- Issue #10611: SystemExit exception will no longer kill a unittest run.
+
+- Issue #9857: It is now possible to skip a test in a setUp, tearDown or clean
+  up function.
+
+- Issue #10573: use actual/expected consistently in unittest methods.
+  The order of the args of assertCountEqual is also changed.
+
+- Issue #9286: email.utils.parseaddr no longer concatenates blank-separated
+  words in the local part of email addresses, thereby preserving the input.
+
+- Issue #6791: Limit header line length (to 65535 bytes) in http.client
+  and http.server, to avoid denial of services from the other party.
+
+- Issue #10404: Use ctl-button-1 on OSX for the context menu in Idle.
+
+- Issue #9907: Fix tab handling on OSX when using editline by calling
+  rl_initialize first, then setting our custom defaults, then reading .editrc.
+
+- Issue #4188: Avoid creating dummy thread objects when logging operations
+  from the threading module (with the internal verbose flag activated).
+
+- Issue #10711: Remove HTTP 0.9 support from http.client.  The ``strict``
+  parameter to HTTPConnection and friends is deprecated.
+
+- Issue #9721: Fix the behavior of urljoin when the relative url starts with a
+  ';' character. Patch by Wes Chow.
+
+- Issue #10714: Limit length of incoming request in http.server to 65536 bytes
+  for security reasons.  Initial patch by Ross Lagerwall.
+
+- Issue #9558: Fix distutils.command.build_ext with VS 8.0.
+
+- Issue #10667: Fast path for collections.Counter().
+
+- Issue #10695: passing the port as a string value to telnetlib no longer
+  causes debug mode to fail.
+
+- Issue #1078919: add_header now automatically RFC2231 encodes parameters
+  that contain non-ascii values.
+
+- Issue #10188 (partial resolution): tempfile.TemporaryDirectory emits
+  a warning on sys.stderr rather than throwing a misleading exception
+  if cleanup fails due to nulling out of modules during shutdown.
+  Also avoids an AttributeError when mkdtemp call fails and issues
+  a ResourceWarning on implicit cleanup via __del__.
+
+- Issue #10107: Warn about unsaved files in IDLE on OSX.
+
+- Issue #7213: subprocess.Popen's default for close_fds has been changed.
+  It is now True in most cases other than on Windows when input, output or
+  error handles are provided.
+
+- Issue #6559: subprocess.Popen has a new pass_fds parameter (actually
+  added in 3.2beta1) to allow specifying a specific list of file descriptors
+  to keep open in the child process.
+
+- Issue #1731717: Fixed the problem where subprocess.wait() could cause an
+  OSError exception when The OS had been told to ignore SIGCLD in our process
+  or otherwise not wait for exiting child processes.
+
+Tests
+-----
+
+- Issue #775964: test_grp now skips YP/NIS entries instead of failing when
+  encountering them.
+
+Tools/Demos
+-----------
+
+- Issue #6075: IDLE on Mac OS X now works with both Carbon AquaTk and
+  Cocoa AquaTk.
+
+- Issue #10710: ``Misc/setuid-prog.c`` is removed from the source tree.
+
+- Issue #10706: Remove outdated script runtests.sh.  Either ``make test``
+  or ``python -m test`` should be used instead.
+
+Build
+-----
+
+- The Windows build now uses Tcl/Tk 8.5.9 and sqlite3 3.7.4.
+
+- Issue #9234: argparse supports alias names for subparsers.
+
+
+What's New in Python 3.2 Beta 1?
+================================
+
+*Release date: 05-Dec-2010*
+
+Core and Builtins
+-----------------
+
+- Issue #10630: Return dict views from the dict proxy keys()/values()/items()
+  methods.
+
+- Issue #10596: Fix float.__mod__ to have the same behaviour as float.__divmod__
+  with respect to signed zeros.  -4.0 % 4.0 should be 0.0, not -0.0.
+
+- Issue #1772833: Add the -q command-line option to suppress copyright and
+  version output in interactive mode.
+
+- Provide an *optimize* parameter in the built-in compile() function.
+
+- Fixed several corner case issues on Windows in os.stat/os.lstat related to
+  reparse points.
+
+- PEP 384 (Defining a Stable ABI) is implemented.
+
+- Issue #2690: Range objects support negative indices and slicing.
+
+- Issue #9915: Speed up sorting with a key.
+
+- Issue #8685: Speed up set difference ``a - b`` when source set ``a`` is much
+  larger than operand ``b``.  Patch by Andrew Bennetts.
+
+- Issue #10518: Bring back the callable() builtin.
+
+- Issue #7094: Added alternate formatting (specified by '#') to ``__format__``
+  method of float, complex, and Decimal. This allows more precise control over
+  when decimal points are displayed.
+
+- Issue #10474: range.count() should return integers.
+
+- Issue #1574217: isinstance now catches only AttributeError, rather than
+  masking all errors.
+
+Library
+-------
+
+- logging: added "handler of last resort". See http://bit.ly/last-resort-handler
+
+- test.support: Added TestHandler and Matcher classes for better support of
+  assertions about logging.
+
+- Issue #4391: Use proper plural forms in argparse.
+
+- Issue #10601: sys.displayhook uses 'backslashreplace' error handler on
+  UnicodeEncodeError.
+
+- Add the "display" and "undisplay" pdb commands.
+
+- Issue #7245: Add a SIGINT handler in pdb that allows to break a program again
+  after a "continue" command.
+
+- Add the "interact" pdb command.
+
+- Issue #7905: Actually respect the keyencoding parameter to shelve.Shelf.
+
+- Issue #1569291: Speed up array.repeat().
+
+- Provide an interface to set the optimization level of compilation in
+  py_compile, compileall and zipfile.PyZipFile.
+
+- Issue #7904: Changes to urllib.parse.urlsplit to handle schemes as defined by
+  RFC3986. Anything before :// is considered a scheme and is followed by an
+  authority (or netloc) and by '/' led path, which is optional.
+
+- Issue #6045: dbm.gnu databases now support get() and setdefault() methods.
+
+- Issue #10620: `python -m unittest` can accept file paths instead of module
+  names for running specific tests.
+
+- Issue #9424: Deprecate the `unittest.TestCase` methods `assertEquals`,
+  `assertNotEquals`, `assertAlmostEquals`, `assertNotAlmostEquals` and `assert_`
+  and replace them with the correct methods in the Python test suite.
+
+- Issue #10272: The ssl module now raises socket.timeout instead of a generic
+  SSLError on socket timeouts.
+
+- Issue #10528: Allow translators to reorder placeholders in localizable
+  messages from argparse.
+
+- Issue #10497: Fix incorrect use of gettext in argparse.
+
+- Issue #10478: Reentrant calls inside buffered IO objects (for example by
+  way of a signal handler) now raise a RuntimeError instead of freezing the
+  current process.
+
+- logging: Added getLogRecordFactory/setLogRecordFactory with docs and tests.
+
+- Issue #10549: Fix pydoc traceback when text-documenting certain classes.
+
+- Issue #2001: New HTML server with enhanced Web page features.  Patch by Ron
+  Adam.
+
+- Issue #10360: In WeakSet, do not raise TypeErrors when testing for membership
+  of non-weakrefable objects.
+
+- Issue #940286: pydoc.Helper.help() ignores input/output init parameters.
+
+- Issue #1745035: Add a command size and data size limit to smtpd.py, to prevent
+  DoS attacks.  Patch by Savio Sena.
+
+- Issue #4925: Add filename to error message when executable can't be found in
+  subprocess.
+
+- Issue #10391: Don't dereference invalid memory in error messages in the ast
+  module.
+
+- Issue #10027: st_nlink was not being set on Windows calls to os.stat or
+  os.lstat. Patch by Hirokazu Yamamoto.
+
+- Issue #9333: Expose os.symlink only when the SeCreateSymbolicLinkPrivilege is
+  held by the user's account, i.e., when the function can actually be used.
+
+- Issue #8879: Add os.link support for Windows.
+
+- Issue #7911: ``unittest.TestCase.longMessage`` defaults to True for improved
+  failure messages by default. Patch by Mark Roddy.
+
+- Issue #1486713: HTMLParser now has an optional tolerant mode where it tries to
+  guess at the correct parsing of invalid html.
+
+- Issue #10554: Add context manager support to subprocess.Popen objects.
+
+- Issue #8989: email.utils.make_msgid now has a domain parameter that can
+  override the domain name used in the generated msgid.
+
+- Issue #9299: Add exist_ok parameter to os.makedirs to suppress the 'File
+  exists' exception when a target directory already exists with the specified
+  mode. Patch by Ray Allen.
+
+- Issue #9573: os.fork() now works correctly when triggered as a side effect of
+  a module import.
+
+- Issue #10464: netrc now correctly handles lines with embedded '#' characters.
+
+- Added itertools.accumulate().
+
+- Issue #4113: Added custom ``__repr__`` method to ``functools.partial``.
+  Original patch by Daniel Urban.
+
+- Issue #10273: Rename `assertRegexpMatches` and `assertRaisesRegexp` to
+  `assertRegex` and `assertRaisesRegex`.
+
+- Issue #10535: Enable silenced warnings in unittest by default.
+
+- Issue #9873: The URL parsing functions in urllib.parse now accept ASCII byte
+  sequences as input in addition to character strings.
+
+- Issue #10586: The statistics API for the new functools.lru_cache has been
+  changed to a single cache_info() method returning a named tuple.
+
+- Issue #10323: itertools.islice() now consumes the minimum number of inputs
+  before stopping.  Formerly, the final state of the underlying iterator was
+  undefined.
+
+- Issue #10565: The collections.Iterator ABC now checks for both __iter__ and
+  __next__.
+
+- Issue #10242: Fixed implementation of unittest.ItemsEqual and gave it a new
+  more informative name, unittest.CountEqual.
+
+- Issue #10561: In pdb, clear the breakpoints by the breakpoint number.
+
+- Issue #2986: difflib.SequenceMatcher gets a new parameter, autojunk, which can
+  be set to False to turn off the previously undocumented 'popularity'
+  heuristic. Patch by Terry Reedy and Eli Bendersky.
+
+- Issue #10534: in difflib, expose bjunk and bpopular sets; deprecate
+  undocumented and now redundant isbjunk and isbpopular methods.
+
+- Issue #9846: zipfile is now correctly closing underlying file objects.
+
+- Issue #10459: Update CJK character names to Unicode 6.0.
+
+- Issue #4493: urllib.request adds '/' in front of path components which does not
+  start with '/. Common behavior exhibited by browsers and other clients.
+
+- Issue #6378: idle.bat now runs with the appropriate Python version rather than
+  the system default. Patch by Sridhar Ratnakumar.
+
+- Issue #10470: 'python -m unittest' will now run test discovery by default,
+  when no extra arguments have been provided.
+
+- Issue #3709: BaseHTTPRequestHandler will buffer the headers and write to
+  output stream only when end_headers is invoked. This is a speedup and an
+  internal optimization.  Patch by endian.
+
+- Issue #10220: Added inspect.getgeneratorstate. Initial patch by Rodolpho
+  Eckhardt.
+
+- Issue #10453: compileall now uses argparse instead of getopt, and thus
+  provides clean output when called with '-h'.
+
+- Issue #8078: Add constants for higher baud rates in the termios module.  Patch
+  by Rodolpho Eckhardt.
+
+- Issue #10407: Fix two NameErrors in distutils.
+
+- Issue #10371: Deprecated undocumented functions in the trace module.
+
+- Issue #10467: Fix BytesIO.readinto() after seeking into a position after the
+  end of the file.
+
+- configparser: 100% test coverage.
+
+- Issue #10499: configparser supports pluggable interpolation handlers. The
+  default classic interpolation handler is called BasicInterpolation. Another
+  interpolation handler added (ExtendedInterpolation) which supports the syntax
+  used by zc.buildout (e.g. interpolation between sections).
+
+- configparser: the SafeConfigParser class has been renamed to ConfigParser.
+  The legacy ConfigParser class has been removed but its interpolation mechanism
+  is still available as LegacyInterpolation.
+
+- configparser: Usage of RawConfigParser is now discouraged for new projects
+  in favor of ConfigParser(interpolation=None).
+
+- Issue #1682942: configparser supports alternative option/value delimiters.
+
+- Issue #5412: configparser supports mapping protocol access.
+
+- Issue #9411: configparser supports specifying encoding for read operations.
+
+- Issue #9421: configparser's getint(), getfloat() and getboolean() methods
+  accept vars and default arguments just like get() does.
+
+- Issue #9452: configparser supports reading from strings and dictionaries
+  (thanks to the mapping protocol API, the latter can be used to copy data
+  between parsers).
+
+- configparser: accepted INI file structure is now customizable, including
+  comment prefixes, name of the DEFAULT section, empty lines in multiline
+  values, and indentation.
+
+- Issue 10326: unittest.TestCase instances can be pickled.
+
+- Issue 9926: Wrapped TestSuite subclass does not get __call__ executed.
+
+- Issue #9920: Skip tests for cmath.atan and cmath.atanh applied to complex
+  zeros on systems where the log1p function fails to respect the sign of zero.
+  This fixes a test failure on AIX.
+
+- Issue #9732: Addition of getattr_static to the inspect module.
+
+- Issue #10446: Module documentation generated by pydoc now links to a
+  version-specific online reference manual.
+
+- Make the 'No module named' exception message from importlib consistent.
+
+- Issue #10443: Add the SSLContext.set_default_verify_paths() method.
+
+- Issue #10440: Support RUSAGE_THREAD as a constant in the resource module.
+  Patch by Robert Collins.
+
+- Issue #10429: IMAP.starttls() stored the capabilities as bytes objects, rather
+  than strings.
+
+C-API
+-----
+
+- Issue #10557: Added a new API function, PyUnicode_TransformDecimalToASCII(),
+  which transforms non-ASCII decimal digits in a Unicode string to their ASCII
+  equivalents.
+
+- Issue #9518: Extend the PyModuleDef_HEAD_INIT macro to explicitly
+  zero-initialize all fields, fixing compiler warnings seen when building
+  extension modules with gcc with "-Wmissing-field-initializers" (implied by
+  "-W").
+
+- Issue #10255: Fix reference leak in Py_InitializeEx().  Patch by Neil
+  Schemenauer.
+
+- structseq.h is now included in Python.h.
+
+- Loosen PyArg_ValidateKeywordArguments to allow dict subclasses.
+
+Tests
+-----
+
+- regrtest.py once again ensures the test directory is removed from sys.path
+  when it is invoked directly as the __main__ module.
+
+- `python -m test` can be used to run the test suite as well as `python -m
+  test.regrtest`.
+
+- Do not fail test_socket when the IP address of the local hostname cannot be
+  looked up.
+
+- Issue #8886: Use context managers throughout test_zipfile. Patch by Eric
+  Carstensen.
+
+Build
+-----
+
+- Issue #10325: Fix two issues in the fallback definitions for PY_ULLONG_MAX and
+  PY_LLONG_MAX that made them unsuitable for use in preprocessor conditionals.
+
+Documentation
+-------------
+
+- Issue #10299: List the built-in functions in a table in functions.rst.
+
+
 What's New in Python 3.2 Alpha 4?
 =================================
 
-*Release date: XX-Nov-2010*
+*Release date: 13-Nov-2010*
 
 Core and Builtins
 -----------------
@@ -13,46 +989,46 @@
 - Issue #10372: Import the warnings module only after the IO library is
   initialized, so as to avoid bootstrap issues with the '-W' option.
 
-- Issue #10293: Remove obsolete field in the PyMemoryView structure,
-  unused undocumented value PyBUF_SHADOW, and strangely-looking code in
+- Issue #10293: Remove obsolete field in the PyMemoryView structure, unused
+  undocumented value PyBUF_SHADOW, and strangely-looking code in
   PyMemoryView_GetContiguous.
 
-- Issue #6081: Add str.format_map, similar to str.format(**mapping).
+- Issue #6081: Add str.format_map(), similar to ``str.format(**mapping)``.
 
 - If FileIO.__init__ fails, close the file descriptor.
 
 - Issue #10221: dict.pop(k) now has a key error message that includes the
   missing key (same message d[k] returns for missing keys).
 
-- Issue #5437: A preallocated MemoryError instance should not hold traceback
+- Issue #5437: A preallocated MemoryError instance should not keep traceback
   data (including local variables caught in the stack trace) alive infinitely.
 
 - Issue #10186: Fix the SyntaxError caret when the offset is equal to the length
   of the offending line.
 
-- Issue #10089: Add support for arbitrary -X options on the command-line.
-  They can be retrieved through a new attribute ``sys._xoptions``.
+- Issue #10089: Add support for arbitrary -X options on the command line.  They
+  can be retrieved through a new attribute ``sys._xoptions``.
 
-- Issue #4388: On Mac OS X, decode command line arguments from UTF-8, instead
-  of the locale encoding. If the LANG (and LC_ALL and LC_CTYPE) environment
+- Issue #4388: On Mac OS X, decode command line arguments from UTF-8, instead of
+  the locale encoding.  If the LANG (and LC_ALL and LC_CTYPE) environment
   variable is not set, the locale encoding is ISO-8859-1, whereas most programs
-  (including Python) expect UTF-8. Python already uses UTF-8 for the filesystem
+  (including Python) expect UTF-8.  Python already uses UTF-8 for the filesystem
   encoding and to encode command line arguments on this OS.
 
-- Issue #9713, #10114: Parser functions (eg. PyParser_ASTFromFile) expects
-  filenames encoded to the filesystem encoding with surrogateescape error
+- Issue #9713, #10114: Parser functions (e.g. PyParser_ASTFromFile) expect
+  filenames encoded to the filesystem encoding with the surrogateescape error
   handler (to support undecodable bytes), instead of UTF-8 in strict mode.
 
 - Issue #9997: Don't let the name "top" have special significance in scope
   resolution.
 
-- Issue #9862: Compensate for broken PIPE_BUF in AIX by hard coding
-  its value as the default 512 when compiling on AIX.
+- Issue #9862: Compensate for broken PIPE_BUF in AIX by hard coding its value as
+  the default 512 when compiling on AIX.
 
 - Use locale encoding instead of UTF-8 to encode and decode filenames if
   Py_FileSystemDefaultEncoding is not set.
 
-- Issue #10095: fp_setreadl() doesn't reopen the file, reuse instead the file
+- Issue #10095: fp_setreadl() doesn't reopen the file, instead reuse the file
   descriptor.
 
 - Issue #9418: Moved private string methods ``_formatter_parser`` and
@@ -63,34 +1039,54 @@
 Library
 -------
 
-- Issue #4471: Properly shutdown socket in IMAP.shutdown().  Patch by
-  Lorenzo M. Catucci.
+- Issue #10465: fix broken delegating of attributes by gzip._PaddedFile.
+
+- Issue #10356: Decimal.__hash__(-1) should return -2.
+
+- Issue #1553375: logging: Added stack_info kwarg to display stack information.
+
+- Issue #5111: IPv6 Host in the Header is wrapped inside [ ]. Patch by Chandru.
+
+- Fix Fraction.__hash__ so that Fraction.__hash__(-1) is -2.  (See also issue
+  #10356.)
+
+- Issue #4471: Add the IMAP.starttls() method to enable encryption on standard
+  IMAP4 connections.  Original patch by Lorenzo M. Catucci.
+
+- Issue #1466065: Add 'validate' option to base64.b64decode to raise an error if
+  there are non-base64 alphabet characters in the input.
+
+- Issue #10386: Add __all__ to token module; this simplifies importing in
+  tokenize module and prevents leaking of private names through ``import *``.
+
+- Issue #4471: Properly shutdown socket in IMAP.shutdown().  Patch by Lorenzo
+  M. Catucci.
 
 - Fix IMAP.login() to work properly.
 
 - Issue #9244: multiprocessing pool worker processes could terminate
-  unexpectedly if the return value of a task could not be pickled.  Only
-  the ``repr`` of such errors are now sent back, wrapped in an
+  unexpectedly if the return value of a task could not be pickled.  Only the
+  ``repr`` of such errors are now sent back, wrapped in an
   ``MaybeEncodingError`` exception.
 
-- Issue #9244: The ``apply_async()`` and ``map_async()`` methods
-  of ``multiprocessing.Pool`` now accepts a ``error_callback`` argument.
-  This can be a callback with the signature ``callback(exc)``, which will
-  be called if the target raises an exception.
+- Issue #9244: The ``apply_async()`` and ``map_async()`` methods of
+  ``multiprocessing.Pool`` now accepts a ``error_callback`` argument.  This can
+  be a callback with the signature ``callback(exc)``, which will be called if
+  the target raises an exception.
 
-- Issue #10022: The dictionary returned by the ``getpeercert()`` method
-  of SSL sockets now has additional items such as ``issuer`` and ``notBefore``.
+- Issue #10022: The dictionary returned by the ``getpeercert()`` method of SSL
+  sockets now has additional items such as ``issuer`` and ``notBefore``.
 
 - ``usenetrc`` is now false by default for NNTP objects.
 
-- Issue #1926: Add support for NNTP over SSL on port 563, as well as
-  STARTTLS.  Patch by Andrew Vant.
+- Issue #1926: Add support for NNTP over SSL on port 563, as well as STARTTLS.
+  Patch by Andrew Vant.
 
 - Issue #10335: Add tokenize.open(), detect the file encoding using
   tokenize.detect_encoding() and open it in read only mode.
 
-- Issue #10321: Added support for binary data to smtplib.SMTP.sendmail,
-  and a new method send_message to send an email.message.Message object.
+- Issue #10321: Add support for binary data to smtplib.SMTP.sendmail, and a new
+  method send_message to send an email.message.Message object.
 
 - Issue #6011: sysconfig and distutils.sysconfig use the surrogateescape error
   handler to parse the Makefile file.  Avoid a UnicodeDecodeError if the source
@@ -115,60 +1111,59 @@
 - Issue #10180: Pickling file objects is now explicitly forbidden, since
   unpickling them produced nonsensical results.
 
-- Issue #10311: The signal module now restores errno before returning from
-  its low-level signal handler.  Patch by Hallvard B Furuseth.
+- Issue #10311: The signal module now restores errno before returning from its
+  low-level signal handler.  Patch by Hallvard B Furuseth.
 
 - Issue #10282: Add a ``nntp_implementation`` attribute to NNTP objects.
 
 - Issue #10283: Add a ``group_pattern`` argument to NNTP.list().
 
-- Issue #10155: Add IISCGIHandler to wsgiref.handlers to support IIS
-  CGI environment better, and to correct unicode environment values
-  for WSGI 1.0.1.
+- Issue #10155: Add IISCGIHandler to wsgiref.handlers to support IIS CGI
+  environment better, and to correct unicode environment values for WSGI 1.0.1.
 
 - Issue #10281: nntplib now returns None for absent fields in the OVER/XOVER
   response, instead of raising an exception.
 
 - wsgiref now implements and validates PEP 3333, rather than an experimental
   extension of PEP 333.  (Note: earlier versions of Python 3.x may have
-  incorrectly validated some non-compliant applications as WSGI compliant;
-  if your app validates with Python <3.2b1+, but not on this version, it is
-  likely the case that your app was not compliant.)
+  incorrectly validated some non-compliant applications as WSGI compliant; if
+  your app validates with Python <3.2b1+, but not on this version, it is likely
+  the case that your app was not compliant.)
 
-- Issue #10280: NNTP.nntp_version should reflect the highest version
-  advertised by the server.
+- Issue #10280: NNTP.nntp_version should reflect the highest version advertised
+  by the server.
 
 - Issue #10184: Touch directories only once when extracting a tarfile.
 
-- Issue #10199: New package, ``turtledemo`` now contains selected demo
-  scripts that were formerly found under Demo/turtle.
+- Issue #10199: New package, ``turtledemo`` now contains selected demo scripts
+  that were formerly found under Demo/turtle.
 
 - Issue #10265: Close file objects explicitly in sunau.  Patch by Brian Brazil.
 
-- Issue #10266: uu.decode didn't close in_file explicitly when it was given
-  as a filename.  Patch by Brian Brazil.
+- Issue #10266: uu.decode didn't close in_file explicitly when it was given as a
+  filename.  Patch by Brian Brazil.
 
-- Issue #10110: Queue objects didn't recognize full queues when the
-  maxsize parameter had been reduced.
+- Issue #10110: Queue objects didn't recognize full queues when the maxsize
+  parameter had been reduced.
 
 - Issue #10160: Speed up operator.attrgetter.  Patch by Christos Georgiou.
 
 - logging: Added style option to basicConfig() to allow %, {} or $-formatting.
 
-- Issue #5729:  json.dumps() now supports using a string such as '\t'
-  for pretty-printing multilevel objects.
+- Issue #5729: json.dumps() now supports using a string such as '\t' for
+  pretty-printing multilevel objects.
 
-- Issue #10253: FileIO leaks a file descriptor when trying to open a file
-  for append that isn't seekable.  Patch by Brian Brazil.
+- Issue #10253: FileIO leaks a file descriptor when trying to open a file for
+  append that isn't seekable.  Patch by Brian Brazil.
 
-- Support context manager protocol for file-like objects returned by
-  mailbox ``get_file()`` methods.
+- Support context manager protocol for file-like objects returned by mailbox
+  ``get_file()`` methods.
 
 - Issue #10246: uu.encode didn't close file objects explicitly when filenames
   were given to it.  Patch by Brian Brazil.
 
-- Issue #10198: fix duplicate header written to wave files when writeframes()
-  is called without data.
+- Issue #10198: fix duplicate header written to wave files when writeframes() is
+  called without data.
 
 - Close file objects in modulefinder in a timely manner.
 
@@ -178,20 +1173,20 @@
 
 - Close a file object in pkgutil in a timely manner.
 
-- Issue #10233: Close file objects in a timely manner in the tarfile module
-  and its test suite.
+- Issue #10233: Close file objects in a timely manner in the tarfile module and
+  its test suite.
 
 - Issue #10093: ResourceWarnings are now issued when files and sockets are
-  deallocated without explicit closing.  These warnings are silenced by
-  default, except in pydebug mode.
+  deallocated without explicit closing.  These warnings are silenced by default,
+  except in pydebug mode.
 
-- tarfile.py: Add support for all missing variants of the GNU sparse
-  extensions and create files with holes when extracting sparse members.
+- tarfile.py: Add support for all missing variants of the GNU sparse extensions
+  and create files with holes when extracting sparse members.
 
 - Issue #10218: Return timeout status from ``Condition.wait`` in threading.
 
-- Issue #7351: Add ``zipfile.BadZipFile`` spelling of the exception name
-  and deprecate the old name ``zipfile.BadZipfile``.
+- Issue #7351: Add ``zipfile.BadZipFile`` spelling of the exception name and
+  deprecate the old name ``zipfile.BadZipfile``.
 
 - Issue #5027: The standard ``xml`` namespace is now understood by
   xml.sax.saxutils.XMLGenerator as being bound to
@@ -203,21 +1198,19 @@
 
 - logging: Added style option to Formatter to allow %, {} or $-formatting.
 
-- Issue #5178: Added tempfile.TemporaryDirectory class that can be used
-  as a context manager.
+- Issue #5178: Added tempfile.TemporaryDirectory class that can be used as a
+  context manager.
 
 - Issue #1349106: Generator (and BytesGenerator) flatten method and Header
   encode method now support a 'linesep' argument.
 
-- Issue #5639: Add a *server_hostname* argument to ``SSLContext.wrap_socket``
-  in order to support the TLS SNI extension.  ``HTTPSConnection`` and
-  ``urlopen()`` also use this argument, so that HTTPS virtual hosts are now
-  supported.
+- Issue #5639: Add a *server_hostname* argument to ``SSLContext.wrap_socket`` in
+  order to support the TLS SNI extension.  ``HTTPSConnection`` and ``urlopen()``
+  also use this argument, so that HTTPS virtual hosts are now supported.
 
 - Issue #10166: Avoid recursion in pstats Stats.add() for many stats items.
 
-- Issue #10163: Skip unreadable registry keys during mimetypes
-  initialization.
+- Issue #10163: Skip unreadable registry keys during mimetypes initialization.
 
 - logging: Made StreamHandler terminator configurable.
 
@@ -230,9 +1223,9 @@
 - logging: Added _logRecordClass, getLogRecordClass, setLogRecordClass to
   increase flexibility of LogRecord creation.
 
-- Issue #5117: Case normalization was needed on ntpath.relpath(). And
-  fixed root directory issue on posixpath.relpath(). (Ported working fixes
-  from ntpath)
+- Issue #5117: Case normalization was needed on ntpath.relpath().  Also fixed
+  root directory issue on posixpath.relpath().  (Ported working fixes from
+  ntpath.)
 
 - Issue #1343: xml.sax.saxutils.XMLGenerator now has an option
   short_empty_elements to direct it to use self-closing tags when appropriate.
@@ -251,34 +1244,33 @@
 - Issue #9409: Fix the regex to match all kind of filenames, for interactive
   debugging in doctests.
 
-- Issue #9183: ``datetime.timezone(datetime.timedelta(0))`` will now
-  return the same instance as ``datetime.timezone.utc``.
+- Issue #9183: ``datetime.timezone(datetime.timedelta(0))`` will now return the
+  same instance as ``datetime.timezone.utc``.
 
-- Issue #7523: Add SOCK_CLOEXEC and SOCK_NONBLOCK to the socket module,
-  where supported by the system.  Patch by Nikita Vetoshkin.
+- Issue #7523: Add SOCK_CLOEXEC and SOCK_NONBLOCK to the socket module, where
+  supported by the system.  Patch by Nikita Vetoshkin.
 
 - Issue #10063: file:// scheme will stop accessing remote hosts via ftp
   protocol. file:// urls had fallback to access remote hosts via ftp. This was
-  not correct, change is made to raise a URLError when a remote host is tried
-  to access via file:// scheme.
+  not correct, change is made to raise a URLError when a remote host is tried to
+  access via file:// scheme.
 
 - Issue #1710703: Write structures for an empty ZIP archive when a ZipFile is
   created in modes 'a' or 'w' and then closed without adding any files. Raise
   BadZipfile (rather than IOError) when opening small non-ZIP files.
 
-- Issue #10041: The signature of optional arguments in socket.makefile()
-  didn't match that of io.open(), and they also didn't get forwarded
-  properly to TextIOWrapper in text mode.  Patch by Kai Zhu.
+- Issue #10041: The signature of optional arguments in socket.makefile() didn't
+  match that of io.open(), and they also didn't get forwarded properly to
+  TextIOWrapper in text mode.  Patch by Kai Zhu.
 
 - Issue #9003: http.client.HTTPSConnection, urllib.request.HTTPSHandler and
-  urllib.request.urlopen now take optional arguments to allow for
-  server certificate checking, as recommended in public uses of HTTPS.
+  urllib.request.urlopen now take optional arguments to allow for server
+  certificate checking, as recommended in public uses of HTTPS.
 
 - Issue #6612: Fix site and sysconfig to catch os.getcwd() error, eg. if the
   current directory was deleted. Patch written by W. Trevor King.
 
-- Issue #3873: Speed up unpickling from file objects which have a peek()
-  method.
+- Issue #3873: Speed up unpickling from file objects that have a peek() method.
 
 - Issue #10075: Add a session_stats() method to SSLContext objects.
 
@@ -287,6 +1279,9 @@
 Extension Modules
 -----------------
 
+- Issue #5109: array.array constructor will now use fast code when
+  initial data is provided in an array object with correct type.
+
 - Issue #6317: Now winsound.PlaySound only accepts unicode.
 
 - Issue #6317: Now winsound.PlaySound can accept non ascii filename.
@@ -299,12 +1294,12 @@
 
 - Issue #678250: Make mmap flush a noop on ACCESS_READ and ACCESS_COPY.
 
-- Issue #9054: Fix a crash occurring when using the pyexpat module
-  with expat version 2.0.1.
+- Issue #9054: Fix a crash occurring when using the pyexpat module with expat
+  version 2.0.1.
 
-- Issue #5355: Provide mappings from Expat error numbers to string
-  descriptions and backwards, in order to actually make it possible
-  to analyze error codes provided by ExpatError.
+- Issue #5355: Provide mappings from Expat error numbers to string descriptions
+  and backwards, in order to actually make it possible to analyze error codes
+  provided by ExpatError.
 
 - The Unicode database was updated to 6.0.0.
 
@@ -312,8 +1307,7 @@
 -----
 
 - Issue #10288: The deprecated family of "char"-handling macros
-  (ISLOWER()/ISUPPER()/etc) have now been removed: use Py_ISLOWER() etc
-  instead.
+  (ISLOWER()/ISUPPER()/etc) have now been removed: use Py_ISLOWER() etc instead.
 
 - Issue #9778: Hash values are now always the size of pointers. A new Py_hash_t
   type has been introduced.
@@ -321,22 +1315,22 @@
 Tools/Demos
 -----------
 
-- Issue #10117: Tools/scripts/reindent.py now accepts source files
-  that use encoding other than ASCII or UTF-8.  Source encoding is
-  preserved when reindented code is written to a file.
+- Issue #10117: Tools/scripts/reindent.py now accepts source files that use
+  encoding other than ASCII or UTF-8.  Source encoding is preserved when
+  reindented code is written to a file.
 
 - Issue #7287: Demo/imputil/knee.py was removed.
 
 Tests
 -----
 
-- Issue #3699: Fix test_bigaddrspace and extend it to test bytestrings
-  as well as unicode strings.  Initial patch by Sandro Tosi.
+- Issue #3699: Fix test_bigaddrspace and extend it to test bytestrings as well
+  as unicode strings.  Initial patch by Sandro Tosi.
 
 - Issue #10294: Remove dead code form test_unicode_file.
 
-- Issue #10123: Don't use non-ascii filenames in test_doctest tests. Add a
-  new test specific to unicode (non-ascii name and filename).
+- Issue #10123: Don't use non-ascii filenames in test_doctest tests. Add a new
+  test specific to unicode (non-ascii name and filename).
 
 Build
 -----
@@ -351,8 +1345,8 @@
 
 - Accept Oracle Berkeley DB 5.0 and 5.1 as backend for the dbm extension.
 
-- Issue #7473: avoid link errors when building a framework with a different
-  set of architectures than the one that is currently installed.
+- Issue #7473: avoid link errors when building a framework with a different set
+  of architectures than the one that is currently installed.
 
 
 What's New in Python 3.2 Alpha 3?
@@ -408,7 +1402,7 @@
 - Issue #9252: PyImport_Import no longer uses a fromlist hack to return the
   module that was imported, but instead gets the module from sys.modules.
 
-- Issue #9212: The range type_items now provides index() and count() methods, to
+- Issue #9213: The range type_items now provides index() and count() methods, to
   conform to the Sequence ABC.  Patch by Daniel Urban and Daniel Stutzbach.
 
 - Issue #7994: Issue a PendingDeprecationWarning if object.__format__ is called
@@ -836,6 +1830,12 @@
 Extension Modules
 -----------------
 
+- Issue #8013: time.asctime and time.ctime no longer call system
+  asctime and ctime functions.  The year range for time.asctime is now
+  1900 through maxint.  The range for time.ctime is the same as for
+  time.localtime.  The string produced by these functions is longer
+  than 24 characters when year is greater than 9999.
+
 - Issue #6608: time.asctime is now checking struct tm fields its input
   before passing it to the system asctime.  Patch by MunSic Jeong.
 
@@ -1091,8 +2091,8 @@
 
 - Issue #8230: Fix Lib/test/sortperf.py.
 
-- Issue #8620: when a Cmd is fed input that reaches EOF without a final newline,
-  it no longer truncates the last character of the last command line.
+- Issue #8620: when a cmd.Cmd() is fed input that reaches EOF without a final
+  newline, it no longer truncates the last character of the last command line.
 
 - Issue #5146: Handle UID THREAD command correctly in imaplib.
 
@@ -1816,7 +2816,7 @@
 - Issue #8897: Fix sunau module, use bytes to write the header. Patch written by
   Thomas Jollans.
 
-- Issue #8899: time.struct_time now has class and atribute docstrings.
+- Issue #8899: time.struct_time now has class and attribute docstrings.
 
 - Issue #6470: Drop UNC prefix in FixTk.
 

Deleted: python/branches/pep-3151/Misc/PURIFY.README
==============================================================================
--- python/branches/pep-3151/Misc/PURIFY.README	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,97 +0,0 @@
-Purify (tm) and Quantify (tm) are commercial software quality
-assurance tools available from IBM <http://www.ibm.com/software/rational/>.
-Purify is essentially a memory access
-verifier and leak detector; Quantify is a C level profiler.  The rest
-of this file assumes you generally know how to use Purify and
-Quantify, and that you have installed valid licenses for these
-products.  If you haven't installed such licenses, you can ignore the
-following since it won't help you a bit!
-
-You can easily build a Purify or Quantify instrumented version of the
-Python interpreter by passing the PURIFY variable to the make command
-at the top of the Python tree:
-
-    make PURIFY=purify
-
-This assumes that the `purify' program is on your $PATH.  Note that
-you cannot both Purify and Quantify the Python interpreter (or any
-program for that matter) at the same time.  If you want to build a
-Quantify'd interpreter, do this:
-
-    make PURIFY=quantify
-
-Starting with Python 2.3, pymalloc is enabled by default.  This
-will cause many supurious warnings.  Modify Objects/obmalloc.c
-and enable Py_USING_MEMORY_DEBUGGER by uncommenting it.
-README.valgrind has more details about why this is necessary.
-See below about setting up suppressions.  Some tests may not
-run well with Purify due to heavy memory or CPU usage.  These
-tests may include: test_largefile, test_import, and test_long.
-
-Please report any findings (problems or no warnings) to python-dev at python.org.
-It may be useful to submit a bug report for any problems.  
-
-When running the regression test (make test), I have found it useful
-to set my PURIFYOPTIONS environment variable using the following
-(bash) shell function.  Check out the Purify documentation for
-details:
-
-p() {
-  chainlen='-chain-length=12'
-  ignoresigs='-ignore-signals="SIGHUP,SIGINT,SIGQUIT,SIGILL,SIGTRAP,SIGAVRT,SIGEMT,SIGFPE,SIGKILL,SIGBUS,SIGSEGV,SIGPIPE,SIGTERM,SIGUSR1,SIGUSR2,SIGPOLL,SIGXCPU,SIGXFSZ,SIGFREEZE,SIGTHAW,SIGRTMIN,SIGRTMAX"'
-  followchild='-follow-child-processes=yes'
-  threads='-max-threads=50'
-  export PURIFYOPTIONS="$chainlen $ignoresigs $followchild $threads"
-  echo $PURIFYOPTIONS
-}
-
-Note that you may want to crank -chain-length up even further.  A
-value of 20 should get you the entire stack up into the Python C code
-in all situations.
-
-With the regression test on a fatly configured interpreter
-(i.e. including as many modules as possible in your Modules/Setup
-file), you'll probably get a gabillion UMR errors, and a few MLK
-errors.  I think most of these can be safely suppressed by putting the
-following in your .purify file:
-
-    suppress umr ...; "socketmodule.c"
-    suppress umr ...; time_strftime
-    suppress umr ...; "_dbmmodule.c"
-    suppress umr ...; "_gdbmmodule.c"
-    suppress umr ...; "grpmodule.c"
-    suppress umr ...; "nismodule.c"
-    suppress umr ...; "pwdmodule.c"
-
-Note: this list is very old and may not be accurate any longer.
-It's possible some of these no longer need to be suppressed.
-You will also need to suppress warnings (at least umr)
-from Py_ADDRESS_IN_RANGE.
-
-This will still leave you with just a few UMR, mostly in the readline
-library, which you can safely ignore.  A lot of work has gone into
-Python 1.5 to plug as many leaks as possible.
-
-Using Purify or Quantify in this way will give you coarse grained
-reports on the whole Python interpreter.  You can actually get more
-fine grained control over both by linking with the optional `pure'
-module, which exports (most of) the Purify and Quantify C API's into
-Python.  To link in this module (it must be statically linked), edit
-your Modules/Setup file for your site, and rebuild the interpreter.
-You might want to check out the comments in the Modules/puremodule.c
-file for some idiosyncrasies.
-
-Using this module, you can actually profile or leak test a small
-section of code, instead of the whole interpreter.  Using this in
-conjuction with pdb.py, dbx, or the profiler.py module really gives
-you quite a bit of introspective power.
-
-Naturally there are a couple of caveats.  This has only been tested
-with Purify 4.0.1 and Quantify 2.1-beta on Solaris 2.5.  Purify 4.0.1
-does not work with Solaris 2.6, but Purify 4.1 which reportedly will,
-is currently in beta test.  There are funky problems when Purify'ing a 
-Python interpreter build with threads.  I've had a lot of problems
-getting this to work, so I generally don't build with threads when I'm 
-Purify'ing.  If you get this to work, let us know!
-
--Barry Warsaw <bwarsaw at cnri.reston.va.us>

Modified: python/branches/pep-3151/Misc/README
==============================================================================
--- python/branches/pep-3151/Misc/README	(original)
+++ python/branches/pep-3151/Misc/README	Sat Feb 26 08:16:32 2011
@@ -8,32 +8,19 @@
 ----------------
 
 ACKS                    Acknowledgements
-AIX-NOTES               Notes for building Python on AIX
 build.sh                Script to build and test latest Python from the repository
-cheatsheet              Quick summary of Python by Ken Manheimer
-developers.txt          A history of who got developer permissions, and why
 gdbinit                 Handy stuff to put in your .gdbinit file, if you use gdb
 HISTORY                 News from previous releases -- oldest last
 indent.pro              GNU indent profile approximating my C style
-maintainers.rst         A list of maintainers for library modules
 NEWS                    News for this release (for some meaning of "this")
-NEWS.help               How to edit NEWS
 Porting                 Mini-FAQ on porting to new platforms
-PURIFY.README           Information for Purify users
-pymemcompat.h           Memory interface compatibility file.
 python-config.in        Python script template for python-config
 python.man              UNIX man page for the python interpreter
-python-mode.el          Emacs mode for editing Python programs
 python.pc.in            Package configuration info template for pkg-config
-python-wing.wpr         Wing IDE project file
+python-wing*.wpr        Wing IDE project file
 README                  The file you're reading now
-README.coverity         Information about running Coverity's Prevent on Python
-README.klocwork         Information about running Klocwork's K7 on Python
-README.OpenBSD          Help for building problems on OpenBSD
 README.valgrind         Information for Valgrind users, see valgrind-python.supp
-RFD                     Request For Discussion about a Python newsgroup
 RPM                     (Old) tools to build RPMs
-setuid-prog.c           C helper program for set-uid Python scripts
 SpecialBuilds.txt       Describes extra symbols you can set for debug builds
 TextMate                A TextMate bundle for Python development
 valgrind-python.supp    Valgrind suppression file, see README.valgrind

Deleted: python/branches/pep-3151/Misc/README.Emacs
==============================================================================
--- python/branches/pep-3151/Misc/README.Emacs	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,32 +0,0 @@
-=============
-Emacs support
-=============
-
-If you want to edit Python code in Emacs, you should download python-mode.el
-and install it somewhere on your load-path.  See the project page to download:
-
-    https://launchpad.net/python-mode
-
-While Emacs comes with a python.el file, it is not recommended.
-python-mode.el is maintained by core Python developers and is generally
-considered more Python programmer friendly.  For example, python-mode.el
-includes a killer feature called `pdbtrack` which allows you to set a pdb
-breakpoint in your code, run your program in an Emacs shell buffer, and do gud
-style debugging when the breakpoint is hit.
-
-python-mode.el is compatible with both GNU Emacs from the FSF, and XEmacs.
-
-For more information and bug reporting, see the above project page.  For help,
-development, or discussions, see the python-mode mailing list:
-
-    http://mail.python.org/mailman/listinfo/python-mode
-
-
-..
-   Local Variables:
-   mode: indented-text
-   indent-tabs-mode: nil
-   sentence-end-double-space: t
-   fill-column: 78
-   coding: utf-8
-   End:

Deleted: python/branches/pep-3151/Misc/README.OpenBSD
==============================================================================
--- python/branches/pep-3151/Misc/README.OpenBSD	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,38 +0,0 @@
-
-2005-01-08
-
-If you are have a problem building on OpenBSD and see output like this
-while running configure:
-
-checking curses.h presence... yes
-configure: WARNING: curses.h: present but cannot be compiled
-configure: WARNING: curses.h: check for missing prerequisite headers?
-configure: WARNING: curses.h: see the Autoconf documentation
-configure: WARNING: curses.h: section "Present But Cannot Be Compiled"
-configure: WARNING: curses.h: proceeding with the preprocessor's result
-configure: WARNING: curses.h: in the future, the compiler will take precedence
-
-there is likely a problem that will prevent building python.  
-If you see the messages above and are able to completely build python,
-please tell python-dev at python.org indicating your version of OpenBSD
-and any other relevant system configuration.
-
-The build error that occurs while making may look something like this:
-
-    /usr/include/sys/event.h:53: error: syntax error before "u_int"
-    /usr/include/sys/event.h:55: error: syntax error before "u_short"
-
-To fix this problem, you will probably need update Python's configure
-script to disable certain options.  Search for a line that looks like:
-
-    OpenBSD/2.* | OpenBSD/3.@<:@012345678@:>@)
-
-If your version is not in that list, e.g., 3.9, add the version
-number.  In this case, you would just need to add a 9 after the 8.
-If you modify configure.in, you will need to regenerate configure
-with autoconf.
-
-If your version is already in the list, this is not a known problem.
-Please submit a bug report here:
-
-    http://sourceforge.net/tracker/?group_id=5470&atid=105470

Deleted: python/branches/pep-3151/Misc/README.klocwork
==============================================================================
--- python/branches/pep-3151/Misc/README.klocwork	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,30 +0,0 @@
-
-Klocwork has a static analysis tool (K7) which is similar to Coverity.
-They will run their tool on the Python source code on demand.
-The results are available at:
-
-     https://opensource.klocwork.com/
-
-Currently, only Neal Norwitz has access to the analysis reports.  Other
-people can be added by request.
-
-K7 was first run on the Python 2.5 source code in mid-July 2006.
-This is after Coverity had been making their results available.
-There were originally 175 defects reported.  Most of these
-were false positives.  However, there were numerous real issues 
-also uncovered.
-
-Each warning has a unique id and comments that can be made on it.
-When checking in changes due to a K7 report, the unique id
-as reported by the tool was added to the SVN commit message.
-A comment was added to the K7 warning indicating the SVN revision
-in addition to any analysis.
-
-False positives were also annotated so that the comments can
-be reviewed and reversed if the analysis was incorrect.
-
-A second run was performed on 10-Aug-2006.  The tool was tuned to remove
-some false positives and perform some additional checks.  ~150 new
-warnings were produced, primarily related to dereferencing NULL pointers.
-
-Contact python-dev at python.org for more information.

Deleted: python/branches/pep-3151/Misc/RFD
==============================================================================
--- python/branches/pep-3151/Misc/RFD	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,114 +0,0 @@
-To:  python-list
-Subject: comp.lang.python RFD again
-From: Guido.van.Rossum at cwi.nl
-
-I've followed the recent discussion and trimmed the blurb RFD down a bit
-(and added the word "object-oriented" to the blurb).
-
-I don't think it's too early to *try* to create the newsgroup --
-whether we will succeed may depend on how many Python supporters there
-are outside the mailing list.
-
-I'm personally not worried about moderation, and anyway I haven't
-heard from any volunteers for moderation (and I won't volunteer
-myself) so I suggest that we'll continue to ask for one unmoderated
-newsgroup.
-
-My next action will be to post an updated FAQ (which will hint at the
-upcoming RFD) to comp.lang.misc; then finalize the 1.0.0 release and
-put it on the ftp site.  I'll also try to get it into
-comp.sources.unix or .misc.  And all this before the end of January!
-
---Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum at cwi.nl>
-URL:  <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>
-
-======================================================================
-
-These are the steps required (in case you don't know about the
-newsgroup creation process):
-
-First, we need to draw up an RFD (Request For Discussion).  This is a
-document that tells what the purpose of the group is, and gives a case
-for its creation.  We post this to relevant groups (comp.lang.misc,
-the mailing list, news.groups, etc.)  Discussion is held on
-news.groups.
-
-Then, after a few weeks, we run the official CFV (Call For Votes).
-The votes are then collected over a period of weeks.  We need 100 more
-yes votes than no votes, and a 2/3 majority, to get the group.
-
-There are some restrictions on the vote taker: [s]he cannot actively
-campaign for/against the group during the vote process.  So the main
-benefit to Steve instead of me running the vote is that I will be free
-to campaign for its creation!
-
-The following is our current draft for the RFD.
-
-======================================================================
-
-Request For Discussion: comp.lang.python
-
-
-Purpose
--------
-
-The newsgroup will be for discussion on the Python computer language.
-Possible topics include requests for information, general programming,
-development, and bug reports. The group will be unmoderated.
-
-
-What is Python?
----------------
-
-Python is a relatively new very-high-level language developed in
-Amsterdam.  Python is a simple, object-oriented procedural language,
-with features taken from ABC, Icon, Modula-3, and C/C++.
-
-Its central goal is to provide the best of both worlds: the dynamic
-nature of scripting languages like Perl/TCL/REXX, but also support for
-general programming found in the more traditional languages like Icon,
-C, Modula,...
-
-Python may be FTP'd from the following sites:
-
-	ftp.cwi.nl in directory /pub/python (its "home site", also has a FAQ)
-	ftp.uu.net in directory /languages/python
-	gatekeeper.dec.com in directory /pub/plan/python/cwi
-
-
-Rationale
----------
-
-Currently there is a mailing list with over 130 subscribers.
-The activity of this list is high, and to make handling the
-traffic more reasonable, a newsgroup is being proposed. We
-also feel that comp.lang.misc would not be a suitable forum
-for this volume of discussion on a particular language.
-
-
-Charter
--------
-
-Comp.lang.python is an unmoderated newsgroup which will serve
-as a forum for discussing the Python computer language. The
-group will serve both those who just program in Python and
-those who work on developing the language. Topics that
-may be discussed include:
-
-	- announcements of new versions of the language and
-	  applications written in Python.
-
-	- discussion on the internals of the Python language.
-
-	- general information about the language.
-
-	- discussion on programming in Python.
-
-
-Discussion
-----------
-
-Any objections to this RFD will be considered and, if determined
-to be appropriate, will be incorporated. The discussion period
-will be for a period of 21 days after which the first CFV will be
-issued.

Deleted: python/branches/pep-3151/Misc/RPM/python-3.2.spec
==============================================================================
--- python/branches/pep-3151/Misc/RPM/python-3.2.spec	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,390 +0,0 @@
-##########################
-#  User-modifiable configs
-##########################
-
-#  Is the resulting package and the installed binary named "python" or
-#  "python2"?
-#WARNING: Commenting out doesn't work.  Last line is what's used.
-%define config_binsuffix none
-%define config_binsuffix 2.6
-
-#  Build tkinter?  "auto" enables it if /usr/bin/wish exists.
-#WARNING: Commenting out doesn't work.  Last line is what's used.
-%define config_tkinter no
-%define config_tkinter yes
-%define config_tkinter auto
-
-#  Use pymalloc?  The last line (commented or not) determines wether
-#  pymalloc is used.
-#WARNING: Commenting out doesn't work.  Last line is what's used.
-%define config_pymalloc no
-%define config_pymalloc yes
-
-#  Enable IPV6?
-#WARNING: Commenting out doesn't work.  Last line is what's used.
-%define config_ipv6 yes
-%define config_ipv6 no
-
-#  Build shared libraries or .a library?
-#WARNING: Commenting out doesn't work.  Last line is what's used.
-%define config_sharedlib no
-%define config_sharedlib yes
-
-#  Location of the HTML directory.
-%define config_htmldir /var/www/html/python
-
-#################################
-#  End of user-modifiable configs
-#################################
-
-%define name python
-#--start constants--
-%define version 3.2a3
-%define libvers 3.2
-#--end constants--
-%define release 1pydotorg
-%define __prefix /usr
-
-#  kludge to get around rpm <percent>define weirdness
-%define ipv6 %(if [ "%{config_ipv6}" = yes ]; then echo --enable-ipv6; else echo --disable-ipv6; fi)
-%define pymalloc %(if [ "%{config_pymalloc}" = yes ]; then echo --with-pymalloc; else echo --without-pymalloc; fi)
-%define binsuffix %(if [ "%{config_binsuffix}" = none ]; then echo ; else echo "%{config_binsuffix}"; fi)
-%define include_tkinter %(if [ \\( "%{config_tkinter}" = auto -a -f /usr/bin/wish \\) -o "%{config_tkinter}" = yes ]; then echo 1; else echo 0; fi)
-%define libdirname %(( uname -m | egrep -q '_64$' && [ -d /usr/lib64 ] && echo lib64 ) || echo lib)
-%define sharedlib %(if [ "%{config_sharedlib}" = yes ]; then echo --enable-shared; else echo ; fi)
-%define include_sharedlib %(if [ "%{config_sharedlib}" = yes ]; then echo 1; else echo 0; fi)
-
-#  detect if documentation is available
-%define include_docs %(if [ -f "%{_sourcedir}/html-%{version}.tar.bz2" ]; then echo 1; else echo 0; fi)
-
-Summary: An interpreted, interactive, object-oriented programming language.
-Name: %{name}%{binsuffix}
-Version: %{version}
-Release: %{release}
-License: PSF
-Group: Development/Languages
-Source: Python-%{version}.tar.bz2
-%if %{include_docs}
-Source1: html-%{version}.tar.bz2
-%endif
-BuildRoot: %{_tmppath}/%{name}-%{version}-root
-BuildPrereq: expat-devel
-BuildPrereq: db4-devel
-BuildPrereq: gdbm-devel
-BuildPrereq: sqlite-devel
-Prefix: %{__prefix}
-Packager: Sean Reifschneider <jafo-rpms at tummy.com>
-
-%description
-Python is an interpreted, interactive, object-oriented programming
-language.  It incorporates modules, exceptions, dynamic typing, very high
-level dynamic data types, and classes. Python combines remarkable power
-with very clear syntax. It has interfaces to many system calls and
-libraries, as well as to various window systems, and is extensible in C or
-C++. It is also usable as an extension language for applications that need
-a programmable interface.  Finally, Python is portable: it runs on many
-brands of UNIX, on PCs under Windows, MS-DOS, and OS/2, and on the
-Mac.
-
-%package devel
-Summary: The libraries and header files needed for Python extension development.
-Prereq: python%{binsuffix} = %{PACKAGE_VERSION}
-Group: Development/Libraries
-
-%description devel
-The Python programming language's interpreter can be extended with
-dynamically loaded extensions and can be embedded in other programs.
-This package contains the header files and libraries needed to do
-these types of tasks.
-
-Install python-devel if you want to develop Python extensions.  The
-python package will also need to be installed.  You'll probably also
-want to install the python-docs package, which contains Python
-documentation.
-
-%if %{include_tkinter}
-%package tkinter
-Summary: A graphical user interface for the Python scripting language.
-Group: Development/Languages
-Prereq: python%{binsuffix} = %{PACKAGE_VERSION}-%{release}
-
-%description tkinter
-The Tkinter (Tk interface) program is an graphical user interface for
-the Python scripting language.
-
-You should install the tkinter package if you'd like to use a graphical
-user interface for Python programming.
-%endif
-
-%package tools
-Summary: A collection of development tools included with Python.
-Group: Development/Tools
-Prereq: python%{binsuffix} = %{PACKAGE_VERSION}-%{release}
-
-%description tools
-The Python package includes several development tools that are used
-to build python programs.  This package contains a selection of those
-tools, including the IDLE Python IDE.
-
-Install python-tools if you want to use these tools to develop
-Python programs.  You will also need to install the python and
-tkinter packages.
-
-%if %{include_docs}
-%package docs
-Summary: Python-related documentation.
-Group: Development/Documentation
-
-%description docs
-Documentation relating to the Python programming language in HTML and info
-formats.
-%endif
-
-%changelog
-* Mon Dec 20 2004 Sean Reifschneider <jafo-rpms at tummy.com> [2.4-2pydotorg]
-- Changing the idle wrapper so that it passes arguments to idle.
-
-* Tue Oct 19 2004 Sean Reifschneider <jafo-rpms at tummy.com> [2.4b1-1pydotorg]
-- Updating to 2.4.
-
-* Thu Jul 22 2004 Sean Reifschneider <jafo-rpms at tummy.com> [2.3.4-3pydotorg]
-- Paul Tiemann fixes for %{prefix}.
-- Adding permission changes for directory as suggested by reimeika.ca
-- Adding code to detect when it should be using lib64.
-- Adding a define for the location of /var/www/html for docs.
-
-* Thu May 27 2004 Sean Reifschneider <jafo-rpms at tummy.com> [2.3.4-2pydotorg]
-- Including changes from Ian Holsman to build under Red Hat 7.3.
-- Fixing some problems with the /usr/local path change.
-
-* Sat Mar 27 2004 Sean Reifschneider <jafo-rpms at tummy.com> [2.3.2-3pydotorg]
-- Being more agressive about finding the paths to fix for
-  #!/usr/local/bin/python.
-
-* Sat Feb 07 2004 Sean Reifschneider <jafo-rpms at tummy.com> [2.3.3-2pydotorg]
-- Adding code to remove "#!/usr/local/bin/python" from particular files and
-  causing the RPM build to terminate if there are any unexpected files
-  which have that line in them.
-
-* Mon Oct 13 2003 Sean Reifschneider <jafo-rpms at tummy.com> [2.3.2-1pydotorg]
-- Adding code to detect wether documentation is available to build.
-
-* Fri Sep 19 2003 Sean Reifschneider <jafo-rpms at tummy.com> [2.3.1-1pydotorg]
-- Updating to the 2.3.1 release.
-
-* Mon Feb 24 2003 Sean Reifschneider <jafo-rpms at tummy.com> [2.3b1-1pydotorg]
-- Updating to 2.3b1 release.
-
-* Mon Feb 17 2003 Sean Reifschneider <jafo-rpms at tummy.com> [2.3a1-1]
-- Updating to 2.3 release.
-
-* Sun Dec 23 2001 Sean Reifschneider <jafo-rpms at tummy.com>
-[Release 2.2-2]
-- Added -docs package.
-- Added "auto" config_tkinter setting which only enables tk if
-  /usr/bin/wish exists.
-
-* Sat Dec 22 2001 Sean Reifschneider <jafo-rpms at tummy.com>
-[Release 2.2-1]
-- Updated to 2.2.
-- Changed the extension to "2" from "2.2".
-
-* Tue Nov 18 2001 Sean Reifschneider <jafo-rpms at tummy.com>
-[Release 2.2c1-1]
-- Updated to 2.2c1.
-
-* Thu Nov  1 2001 Sean Reifschneider <jafo-rpms at tummy.com>
-[Release 2.2b1-3]
-- Changed the way the sed for fixing the #! in pydoc works.
-
-* Wed Oct  24 2001 Sean Reifschneider <jafo-rpms at tummy.com>
-[Release 2.2b1-2]
-- Fixed missing "email" package, thanks to anonymous report on sourceforge.
-- Fixed missing "compiler" package.
-
-* Mon Oct 22 2001 Sean Reifschneider <jafo-rpms at tummy.com>
-[Release 2.2b1-1]
-- Updated to 2.2b1.
-
-* Mon Oct  9 2001 Sean Reifschneider <jafo-rpms at tummy.com>
-[Release 2.2a4-4]
-- otto at balinor.mat.unimi.it mentioned that the license file is missing.
-
-* Sun Sep 30 2001 Sean Reifschneider <jafo-rpms at tummy.com>
-[Release 2.2a4-3]
-- Ignacio Vazquez-Abrams pointed out that I had a spruious double-quote in
-  the spec files.  Thanks.
-
-* Wed Jul 25 2001 Sean Reifschneider <jafo-rpms at tummy.com>
-[Release 2.2a1-1]
-- Updated to 2.2a1 release.
-- Changed idle and pydoc to use binsuffix macro
-
-#######
-#  PREP
-#######
-%prep
-%setup -n Python-%{version}
-
-########
-#  BUILD
-########
-%build
-echo "Setting for ipv6: %{ipv6}"
-echo "Setting for pymalloc: %{pymalloc}"
-echo "Setting for binsuffix: %{binsuffix}"
-echo "Setting for include_tkinter: %{include_tkinter}"
-echo "Setting for libdirname: %{libdirname}"
-echo "Setting for sharedlib: %{sharedlib}"
-echo "Setting for include_sharedlib: %{include_sharedlib}"
-./configure --enable-unicode=ucs4 %{sharedlib} %{ipv6} %{pymalloc} --prefix=%{__prefix}
-make
-
-##########
-#  INSTALL
-##########
-%install
-#  set the install path
-echo '[install_scripts]' >setup.cfg
-echo 'install_dir='"${RPM_BUILD_ROOT}%{__prefix}/bin" >>setup.cfg
-
-[ -d "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != "/" ] && rm -rf $RPM_BUILD_ROOT
-mkdir -p $RPM_BUILD_ROOT%{__prefix}/%{libdirname}/python%{libvers}/lib-dynload
-make prefix=$RPM_BUILD_ROOT%{__prefix} install
-
-#  REPLACE PATH IN PYDOC
-if [ ! -z "%{binsuffix}" ]
-then
-   (
-      cd $RPM_BUILD_ROOT%{__prefix}/bin
-      mv pydoc pydoc.old
-      sed 's|#!.*|#!%{__prefix}/bin/env python'%{binsuffix}'|' \
-            pydoc.old >pydoc
-      chmod 755 pydoc
-      rm -f pydoc.old
-   )
-fi
-
-#  add the binsuffix
-if [ ! -z "%{binsuffix}" ]
-then
-   rm -f $RPM_BUILD_ROOT%{__prefix}/bin/python[0-9a-zA-Z]*
-   ( cd $RPM_BUILD_ROOT%{__prefix}/bin; 
-      for file in *; do mv "$file" "$file"%{binsuffix}; done )
-   ( cd $RPM_BUILD_ROOT%{_mandir}/man1; mv python.1 python%{binsuffix}.1 )
-fi
-
-########
-#  Tools
-echo '#!%{__prefix}/bin/env python%{binsuffix}' >${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix}
-echo 'import os, sys' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix}
-echo 'os.execvp("%{__prefix}/bin/python%{binsuffix}", ["%{__prefix}/bin/python%{binsuffix}", "%{__prefix}/lib/python%{libvers}/idlelib/idle.py"] + sys.argv[1:])' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix}
-echo 'print "Failed to exec Idle"' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix}
-echo 'sys.exit(1)' >>${RPM_BUILD_ROOT}%{__prefix}/bin/idle%{binsuffix}
-chmod 755 $RPM_BUILD_ROOT%{__prefix}/bin/idle%{binsuffix}
-cp -a Tools $RPM_BUILD_ROOT%{__prefix}/%{libdirname}/python%{libvers}
-
-#  MAKE FILE LISTS
-rm -f mainpkg.files
-find "$RPM_BUILD_ROOT""%{__prefix}"/%{libdirname}/python%{libvers} -type f |
-	sed "s|^${RPM_BUILD_ROOT}|/|" |
-	grep -v -e '/python%{libvers}/config$' -e '_tkinter.so$' >mainpkg.files
-find "$RPM_BUILD_ROOT""%{__prefix}"/bin -type f -o -type l |
-	sed "s|^${RPM_BUILD_ROOT}|/|" |
-	grep -v -e '/bin/2to3%{binsuffix}$' |
-	grep -v -e '/bin/pydoc%{binsuffix}$' |
-	grep -v -e '/bin/smtpd.py%{binsuffix}$' |
-	grep -v -e '/bin/idle%{binsuffix}$' >>mainpkg.files
-
-rm -f tools.files
-find "$RPM_BUILD_ROOT""%{__prefix}"/%{libdirname}/python%{libvers}/idlelib \
-      "$RPM_BUILD_ROOT""%{__prefix}"/%{libdirname}/python%{libvers}/Tools -type f |
-      sed "s|^${RPM_BUILD_ROOT}|/|" >tools.files
-echo "%{__prefix}"/bin/2to3%{binsuffix} >>tools.files
-echo "%{__prefix}"/bin/pydoc%{binsuffix} >>tools.files
-echo "%{__prefix}"/bin/smtpd.py%{binsuffix} >>tools.files
-echo "%{__prefix}"/bin/idle%{binsuffix} >>tools.files
-
-######
-# Docs
-%if %{include_docs}
-mkdir -p "$RPM_BUILD_ROOT"%{config_htmldir}
-(
-   cd "$RPM_BUILD_ROOT"%{config_htmldir}
-   bunzip2 < %{SOURCE1} | tar x
-)
-%endif
-
-#  fix the #! line in installed files
-find "$RPM_BUILD_ROOT" -type f -print0 |
-      xargs -0 grep -l /usr/local/bin/python | while read file
-do
-   FIXFILE="$file"
-   sed 's|^#!.*python|#!%{__prefix}/bin/env python'"%{binsuffix}"'|' \
-         "$FIXFILE" >/tmp/fix-python-path.$$
-   cat /tmp/fix-python-path.$$ >"$FIXFILE"
-   rm -f /tmp/fix-python-path.$$
-done
-
-#  check to see if there are any straggling #! lines
-find "$RPM_BUILD_ROOT" -type f | xargs egrep -n '^#! */usr/local/bin/python' \
-      | grep ':1:#!' >/tmp/python-rpm-files.$$ || true
-if [ -s /tmp/python-rpm-files.$$ ]
-then
-   echo '*****************************************************'
-   cat /tmp/python-rpm-files.$$
-   cat <<@EOF
-   *****************************************************
-     There are still files referencing /usr/local/bin/python in the
-     install directory.  They are listed above.  Please fix the .spec
-     file and try again.  If you are an end-user, you probably want
-     to report this to jafo-rpms at tummy.com as well.
-   *****************************************************
- at EOF
-   rm -f /tmp/python-rpm-files.$$
-   exit 1
-fi
-rm -f /tmp/python-rpm-files.$$
-
-########
-#  CLEAN
-########
-%clean
-[ -n "$RPM_BUILD_ROOT" -a "$RPM_BUILD_ROOT" != / ] && rm -rf $RPM_BUILD_ROOT
-rm -f mainpkg.files tools.files
-
-########
-#  FILES
-########
-%files -f mainpkg.files
-%defattr(-,root,root)
-%doc Misc/README Misc/cheatsheet Misc/Porting
-%doc LICENSE Misc/ACKS Misc/HISTORY Misc/NEWS
-%{_mandir}/man1/python%{binsuffix}.1*
-
-%attr(755,root,root) %dir %{__prefix}/include/python%{libvers}
-%attr(755,root,root) %dir %{__prefix}/%{libdirname}/python%{libvers}/
-%if %{include_sharedlib}
-%{__prefix}/%{libdirname}/libpython*
-%endif
-
-%files devel
-%defattr(-,root,root)
-%{__prefix}/include/python%{libvers}/*.h
-%{__prefix}/%{libdirname}/python%{libvers}/config
-
-%files -f tools.files tools
-%defattr(-,root,root)
-
-%if %{include_tkinter}
-%files tkinter
-%defattr(-,root,root)
-%{__prefix}/%{libdirname}/python%{libvers}/tkinter
-%{__prefix}/%{libdirname}/python%{libvers}/lib-dynload/_tkinter.so*
-%endif
-
-%if %{include_docs}
-%files docs
-%defattr(-,root,root)
-%{config_htmldir}/*
-%endif

Modified: python/branches/pep-3151/Misc/SpecialBuilds.txt
==============================================================================
--- python/branches/pep-3151/Misc/SpecialBuilds.txt	(original)
+++ python/branches/pep-3151/Misc/SpecialBuilds.txt	Sat Feb 26 08:16:32 2011
@@ -1,17 +1,20 @@
-This file describes some special Python build types enabled via
-compile-time preprocessor defines.
+This file describes some special Python build types enabled via compile-time
+preprocessor defines.
 
-It is best to define these options in the EXTRA_CFLAGS make variable;
+IMPORTANT: if you want to build a debug-enabled Python, it is recommended that
+you use ``./configure --with-pydebug``, rather than the options listed here.
+
+However, if you wish to define some of these options individually, it is best
+to define them in the EXTRA_CFLAGS make variable;
 ``make EXTRA_CFLAGS="-DPy_REF_DEBUG"``.
 
----------------------------------------------------------------------------
-Py_REF_DEBUG                                              introduced in 1.4
-                                                 named REF_DEBUG before 1.4
-
-Turn on aggregate reference counting.  This arranges that extern
-_Py_RefTotal hold a count of all references, the sum of ob_refcnt across
-all objects.  In a debug-mode build, this is where the "8288" comes from
-in
+
+Py_REF_DEBUG
+------------
+
+Turn on aggregate reference counting.  This arranges that extern _Py_RefTotal
+hold a count of all references, the sum of ob_refcnt across all objects.  In a
+debug-mode build, this is where the "8288" comes from in
 
     >>> 23
     23
@@ -19,75 +22,72 @@
     >>>
 
 Note that if this count increases when you're not storing away new objects,
-there's probably a leak.  Remember, though, that in interactive mode the
-special name "_" holds a reference to the last result displayed!
+there's probably a leak.  Remember, though, that in interactive mode the special
+name "_" holds a reference to the last result displayed!
 
-Py_REF_DEBUG also checks after every decref to verify that the refcount
-hasn't gone negative, and causes an immediate fatal error if it has.
+Py_REF_DEBUG also checks after every decref to verify that the refcount hasn't
+gone negative, and causes an immediate fatal error if it has.
 
 Special gimmicks:
 
 sys.gettotalrefcount()
     Return current total of all refcounts.
-    Available under Py_REF_DEBUG in Python 2.3.
-    Before 2.3, Py_TRACE_REFS was required to enable this function.
----------------------------------------------------------------------------
-Py_TRACE_REFS                                             introduced in 1.4
-                                                named TRACE_REFS before 1.4
-
-Turn on heavy reference debugging.  This is major surgery.  Every PyObject
-grows two more pointers, to maintain a doubly-linked list of all live
-heap-allocated objects.  Most built-in type objects are not in this list,
-as they're statically allocated.  Starting in Python 2.3, if COUNT_ALLOCS
-(see below) is also defined, a static type object T does appear in this
-list if at least one object of type T has been created.
+
+
+Py_TRACE_REFS
+-------------
+
+Turn on heavy reference debugging.  This is major surgery.  Every PyObject grows
+two more pointers, to maintain a doubly-linked list of all live heap-allocated
+objects.  Most built-in type objects are not in this list, as they're statically
+allocated.  Starting in Python 2.3, if COUNT_ALLOCS (see below) is also defined,
+a static type object T does appear in this list if at least one object of type T
+has been created.
 
 Note that because the fundamental PyObject layout changes, Python modules
-compiled with Py_TRACE_REFS are incompatible with modules compiled without
-it.
+compiled with Py_TRACE_REFS are incompatible with modules compiled without it.
 
 Py_TRACE_REFS implies Py_REF_DEBUG.
 
 Special gimmicks:
 
 sys.getobjects(max[, type])
-    Return list of the (no more than) max most-recently allocated objects,
-    most recently allocated first in the list, least-recently allocated
-    last in the list.  max=0 means no limit on list length.
-    If an optional type object is passed, the list is also restricted to
-    objects of that type.
-    The return list itself, and some temp objects created just to call
-    sys.getobjects(), are excluded from the return list.  Note that the
-    list returned is just another object, though, so may appear in the
-    return list the next time you call getobjects(); note that every
-    object in the list is kept alive too, simply by virtue of being in
-    the list.
-
-envar PYTHONDUMPREFS
-    If this envar exists, Py_Finalize() arranges to print a list of
-    all still-live heap objects.  This is printed twice, in different
-    formats, before and after Py_Finalize has cleaned up everything it
-    can clean up.  The first output block produces the repr() of each
-    object so is more informative; however, a lot of stuff destined to
-    die is still alive then.  The second output block is much harder
-    to work with (repr() can't be invoked anymore -- the interpreter
-    has been torn down too far), but doesn't list any objects that will
-    die.  The tool script combinerefs.py can be run over this to combine
-    the info from both output blocks.  The second output block, and
+    Return list of the (no more than) max most-recently allocated objects, most
+    recently allocated first in the list, least-recently allocated last in the
+    list.  max=0 means no limit on list length.  If an optional type object is
+    passed, the list is also restricted to objects of that type.  The return
+    list itself, and some temp objects created just to call sys.getobjects(),
+    are excluded from the return list.  Note that the list returned is just
+    another object, though, so may appear in the return list the next time you
+    call getobjects(); note that every object in the list is kept alive too,
+    simply by virtue of being in the list.
+
+envvar PYTHONDUMPREFS
+    If this envvar exists, Py_Finalize() arranges to print a list of all
+    still-live heap objects.  This is printed twice, in different formats,
+    before and after Py_Finalize has cleaned up everything it can clean up.  The
+    first output block produces the repr() of each object so is more
+    informative; however, a lot of stuff destined to die is still alive then.
+    The second output block is much harder to work with (repr() can't be invoked
+    anymore -- the interpreter has been torn down too far), but doesn't list any
+    objects that will die.  The tool script combinerefs.py can be run over this
+    to combine the info from both output blocks.  The second output block, and
     combinerefs.py, were new in Python 2.3b1.
----------------------------------------------------------------------------
-PYMALLOC_DEBUG                                            introduced in 2.3
+
+
+PYMALLOC_DEBUG
+--------------
 
 When pymalloc is enabled (WITH_PYMALLOC is defined), calls to the PyObject_
-memory routines are handled by Python's own small-object allocator, while
-calls to the PyMem_ memory routines are directed to the system malloc/
-realloc/free.  If PYMALLOC_DEBUG is also defined, calls to both PyObject_
-and PyMem_ memory routines are directed to a special debugging mode of
-Python's small-object allocator.
-
-This mode fills dynamically allocated memory blocks with special,
-recognizable bit patterns, and adds debugging info on each end of
-dynamically allocated memory blocks.  The special bit patterns are:
+memory routines are handled by Python's own small-object allocator, while calls
+to the PyMem_ memory routines are directed to the system malloc/ realloc/free.
+If PYMALLOC_DEBUG is also defined, calls to both PyObject_ and PyMem_ memory
+routines are directed to a special debugging mode of Python's small-object
+allocator.
+
+This mode fills dynamically allocated memory blocks with special, recognizable
+bit patterns, and adds debugging info on each end of dynamically allocated
+memory blocks.  The special bit patterns are:
 
 #define CLEANBYTE     0xCB   /* clean (newly allocated) memory */
 #define DEADBYTE      0xDB   /* dead (newly freed) memory */
@@ -96,73 +96,70 @@
 Strings of these bytes are unlikely to be valid addresses, floats, or 7-bit
 ASCII strings.
 
-Let S = sizeof(size_t). 2*S bytes are added at each end of each block of N
-bytes requested.  The memory layout is like so, where p represents the
-address returned by a malloc-like or realloc-like function (p[i:j] means
-the slice of bytes from *(p+i) inclusive up to *(p+j) exclusive; note that
-the treatment of negative indices differs from a Python slice):
+Let S = sizeof(size_t). 2*S bytes are added at each end of each block of N bytes
+requested.  The memory layout is like so, where p represents the address
+returned by a malloc-like or realloc-like function (p[i:j] means the slice of
+bytes from *(p+i) inclusive up to *(p+j) exclusive; note that the treatment of
+negative indices differs from a Python slice):
 
 p[-2*S:-S]
-    Number of bytes originally asked for.  This is a size_t, big-endian
-    (easier to read in a memory dump).
+    Number of bytes originally asked for.  This is a size_t, big-endian (easier
+    to read in a memory dump).
 p[-S:0]
     Copies of FORBIDDENBYTE.  Used to catch under- writes and reads.
 p[0:N]
     The requested memory, filled with copies of CLEANBYTE, used to catch
-    reference to uninitialized memory.
-    When a realloc-like function is called requesting a larger memory
-    block, the new excess bytes are also filled with CLEANBYTE.
-    When a free-like function is called, these are overwritten with
-    DEADBYTE, to catch reference to freed memory.  When a realloc-
-    like function is called requesting a smaller memory block, the excess
-    old bytes are also filled with DEADBYTE.
+    reference to uninitialized memory.  When a realloc-like function is called
+    requesting a larger memory block, the new excess bytes are also filled with
+    CLEANBYTE.  When a free-like function is called, these are overwritten with
+    DEADBYTE, to catch reference to freed memory.  When a realloc- like function
+    is called requesting a smaller memory block, the excess old bytes are also
+    filled with DEADBYTE.
 p[N:N+S]
     Copies of FORBIDDENBYTE.  Used to catch over- writes and reads.
 p[N+S:N+2*S]
     A serial number, incremented by 1 on each call to a malloc-like or
-    realloc-like function.
-    Big-endian size_t.
-    If "bad memory" is detected later, the serial number gives an
-    excellent way to set a breakpoint on the next run, to capture the
-    instant at which this block was passed out.  The static function
-    bumpserialno() in obmalloc.c is the only place the serial number
-    is incremented, and exists so you can set such a breakpoint easily.
-
-A realloc-like or free-like function first checks that the FORBIDDENBYTEs
-at each end are intact.  If they've been altered, diagnostic output is
-written to stderr, and the program is aborted via Py_FatalError().  The
-other main failure mode is provoking a memory error when a program
-reads up one of the special bit patterns and tries to use it as an address.
-If you get in a debugger then and look at the object, you're likely
-to see that it's entirely filled with 0xDB (meaning freed memory is
-getting used) or 0xCB (meaning uninitialized memory is getting used).
+    realloc-like function.  Big-endian size_t.  If "bad memory" is detected
+    later, the serial number gives an excellent way to set a breakpoint on the
+    next run, to capture the instant at which this block was passed out.  The
+    static function bumpserialno() in obmalloc.c is the only place the serial
+    number is incremented, and exists so you can set such a breakpoint easily.
+
+A realloc-like or free-like function first checks that the FORBIDDENBYTEs at
+each end are intact.  If they've been altered, diagnostic output is written to
+stderr, and the program is aborted via Py_FatalError().  The other main failure
+mode is provoking a memory error when a program reads up one of the special bit
+patterns and tries to use it as an address.  If you get in a debugger then and
+look at the object, you're likely to see that it's entirely filled with 0xDB
+(meaning freed memory is getting used) or 0xCB (meaning uninitialized memory is
+getting used).
 
 Note that PYMALLOC_DEBUG requires WITH_PYMALLOC.
 
 Special gimmicks:
 
-envar PYTHONMALLOCSTATS
-    If this envar exists, a report of pymalloc summary statistics is
-    printed to stderr whenever a new arena is allocated, and also
-    by Py_Finalize().
+envvar PYTHONMALLOCSTATS
+    If this envvar exists, a report of pymalloc summary statistics is printed to
+    stderr whenever a new arena is allocated, and also by Py_Finalize().
 
 Changed in 2.5:  The number of extra bytes allocated is 4*sizeof(size_t).
 Before it was 16 on all boxes, reflecting that Python couldn't make use of
 allocations >= 2**32 bytes even on 64-bit boxes before 2.5.
----------------------------------------------------------------------------
-Py_DEBUG                                                  introduced in 1.5
-                                                     named DEBUG before 1.5
+
+
+Py_DEBUG
+--------
 
 This is what is generally meant by "a debug build" of Python.
 
-Py_DEBUG implies LLTRACE, Py_REF_DEBUG, Py_TRACE_REFS, and
-PYMALLOC_DEBUG (if WITH_PYMALLOC is enabled).  In addition, C
-assert()s are enabled (via the C way: by not defining NDEBUG), and
-some routines do additional sanity checks inside "#ifdef Py_DEBUG"
-blocks.
----------------------------------------------------------------------------
-COUNT_ALLOCS                                            introduced in 0.9.9
-                                             partly broken in 2.2 and 2.2.1
+Py_DEBUG implies LLTRACE, Py_REF_DEBUG, Py_TRACE_REFS, and PYMALLOC_DEBUG (if
+WITH_PYMALLOC is enabled).  In addition, C assert()s are enabled (via the C way:
+by not defining NDEBUG), and some routines do additional sanity checks inside
+"#ifdef Py_DEBUG" blocks.
+
+
+COUNT_ALLOCS
+------------
 
 Each type object grows three new members:
 
@@ -178,84 +175,85 @@
      */
     int tp_maxalloc;
 
-Allocation and deallocation code keeps these counts up to date.
-Py_Finalize() displays a summary of the info returned by sys.getcounts()
-(see below), along with assorted other special allocation counts (like
-the number of tuple allocations satisfied by a tuple free-list, the number
-of 1-character strings allocated, etc).
+Allocation and deallocation code keeps these counts up to date.  Py_Finalize()
+displays a summary of the info returned by sys.getcounts() (see below), along
+with assorted other special allocation counts (like the number of tuple
+allocations satisfied by a tuple free-list, the number of 1-character strings
+allocated, etc).
 
 Before Python 2.2, type objects were immortal, and the COUNT_ALLOCS
-implementation relies on that.  As of Python 2.2, heap-allocated type/
-class objects can go away.  COUNT_ALLOCS can blow up in 2.2 and 2.2.1
-because of this; this was fixed in 2.2.2.  Use of COUNT_ALLOCS makes
-all heap-allocated type objects immortal, except for those for which no
-object of that type is ever allocated.
+implementation relies on that.  As of Python 2.2, heap-allocated type/ class
+objects can go away.  COUNT_ALLOCS can blow up in 2.2 and 2.2.1 because of this;
+this was fixed in 2.2.2.  Use of COUNT_ALLOCS makes all heap-allocated type
+objects immortal, except for those for which no object of that type is ever
+allocated.
 
 Starting with Python 2.3, If Py_TRACE_REFS is also defined, COUNT_ALLOCS
-arranges to ensure that the type object for each allocated object
-appears in the doubly-linked list of all objects maintained by
-Py_TRACE_REFS.
+arranges to ensure that the type object for each allocated object appears in the
+doubly-linked list of all objects maintained by Py_TRACE_REFS.
 
 Special gimmicks:
 
 sys.getcounts()
-    Return a list of 4-tuples, one entry for each type object for which
-    at least one object of that type was allocated.  Each tuple is of
-    the form:
+    Return a list of 4-tuples, one entry for each type object for which at least
+    one object of that type was allocated.  Each tuple is of the form:
 
         (tp_name, tp_allocs, tp_frees, tp_maxalloc)
 
-    Each distinct type object gets a distinct entry in this list, even
-    if two or more type objects have the same tp_name (in which case
-    there's no way to distinguish them by looking at this list).  The
-    list is ordered by time of first object allocation:  the type object
-    for which the first allocation of an object of that type occurred
-    most recently is at the front of the list.
----------------------------------------------------------------------------
-LLTRACE                                          introduced well before 1.0
+    Each distinct type object gets a distinct entry in this list, even if two or
+    more type objects have the same tp_name (in which case there's no way to
+    distinguish them by looking at this list).  The list is ordered by time of
+    first object allocation: the type object for which the first allocation of
+    an object of that type occurred most recently is at the front of the list.
+
+
+LLTRACE
+-------
 
 Compile in support for Low Level TRACE-ing of the main interpreter loop.
 
-When this preprocessor symbol is defined, before PyEval_EvalFrame
-(eval_frame in 2.3 and 2.2, eval_code2 before that) executes a frame's code
-it checks the frame's global namespace for a variable "__lltrace__".  If
-such a variable is found, mounds of information about what the interpreter
-is doing are sprayed to stdout, such as every opcode and opcode argument
-and values pushed onto and popped off the value stack.
+When this preprocessor symbol is defined, before PyEval_EvalFrame (eval_frame in
+2.3 and 2.2, eval_code2 before that) executes a frame's code it checks the
+frame's global namespace for a variable "__lltrace__".  If such a variable is
+found, mounds of information about what the interpreter is doing are sprayed to
+stdout, such as every opcode and opcode argument and values pushed onto and
+popped off the value stack.
 
 Not useful very often, but very useful when needed.
 
----------------------------------------------------------------------------
-CALL_PROFILE                                      introduced for Python 2.3
+
+CALL_PROFILE
+------------
 
 Count the number of function calls executed.
 
-When this symbol is defined, the ceval mainloop and helper functions
-count the number of function calls made.  It keeps detailed statistics
-about what kind of object was called and whether the call hit any of
-the special fast paths in the code.
+When this symbol is defined, the ceval mainloop and helper functions count the
+number of function calls made.  It keeps detailed statistics about what kind of
+object was called and whether the call hit any of the special fast paths in the
+code.
+
 
----------------------------------------------------------------------------
-WITH_TSC                                          introduced for Python 2.4
+WITH_TSC
+--------
 
-Super-lowlevel profiling of the interpreter.  When enabled, the sys
-module grows a new function:
+Super-lowlevel profiling of the interpreter.  When enabled, the sys module grows
+a new function:
 
 settscdump(bool)
-    If true, tell the Python interpreter to dump VM measurements to
-    stderr.  If false, turn off dump.  The measurements are based on the
-    processor's time-stamp counter.
-
-This build option requires a small amount of platform specific code.
-Currently this code is present for linux/x86 and any PowerPC platform
-that uses GCC (i.e. OS X and linux/ppc).
-
-On the PowerPC the rate at which the time base register is incremented
-is not defined by the architecture specification, so you'll need to
-find the manual for your specific processor.  For the 750CX, 750CXe
-and 750FX (all sold as the G3) we find:
+    If true, tell the Python interpreter to dump VM measurements to stderr.  If
+    false, turn off dump.  The measurements are based on the processor's
+    time-stamp counter.
+
+This build option requires a small amount of platform specific code.  Currently
+this code is present for linux/x86 and any PowerPC platform that uses GCC
+(i.e. OS X and linux/ppc).
+
+On the PowerPC the rate at which the time base register is incremented is not
+defined by the architecture specification, so you'll need to find the manual for
+your specific processor.  For the 750CX, 750CXe and 750FX (all sold as the G3)
+we find:
 
-    The time base counter is clocked at a frequency that is
-    one-fourth that of the bus clock.
+    The time base counter is clocked at a frequency that is one-fourth that of
+    the bus clock.
 
 This build is enabled by the --with-tsc flag to configure.

Deleted: python/branches/pep-3151/Misc/cheatsheet
==============================================================================
--- python/branches/pep-3151/Misc/cheatsheet	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,2179 +0,0 @@
-                          Python 2.3 Quick Reference
-
-
- 25 Jan 2003  upgraded by Raymond Hettinger for Python 2.3
- 16 May 2001  upgraded by Richard Gruet and Simon Brunning for Python 2.0
- 2000/07/18  upgraded by Richard Gruet, rgruet at intraware.com for Python 1.5.2
-from V1.3 ref
-1995/10/30, by Chris Hoffmann, choffman at vicorp.com
-
-Based on:
-    Python Bestiary, Author: Ken Manheimer, ken.manheimer at nist.gov
-    Python manuals, Authors: Guido van Rossum and Fred Drake
-    What's new in Python 2.0, Authors: A.M. Kuchling and Moshe Zadka
-    python-mode.el, Author: Tim Peters, tim_one at email.msn.com
-
-    and the readers of comp.lang.python
-
-Python's nest: http://www.python.org     Developement: http://
-python.sourceforge.net/    ActivePython : http://www.ActiveState.com/ASPN/
-Python/
-newsgroup: comp.lang.python  Help desk: help at python.org
-Resources: http://starship.python.net/
-           http://www.vex.net/parnassus/
-           http://aspn.activestate.com/ASPN/Cookbook/Python
-FAQ:       http://www.python.org/cgi-bin/faqw.py
-Full documentation: http://www.python.org/doc/
-Excellent reference books:
-           Python Essential Reference by David Beazley (New Riders)
-           Python Pocket Reference by Mark Lutz (O'Reilly)
-
-
-Invocation Options
-
-python [-diOStuUvxX?] [-c command | script | - ] [args]
-
-                              Invocation Options
-Option                                  Effect
--c cmd  program passed in as string (terminates option list)
--d      Outputs parser debugging information (also PYTHONDEBUG=x)
--E      ignore environment variables (such as PYTHONPATH)
--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
--S      Don't perform 'import site' on initialization
--u      Unbuffered binary stdout and stderr (also PYTHONUNBUFFERED=x).
--v      Verbose (trace import statements) (also PYTHONVERBOSE=x)
--W arg : warning control (arg is action:message:category:module:lineno)
--x      Skip first line of source, allowing use of non-unix Forms of #!cmd
--?      Help!
--c      Specify the command to execute (see next section). This terminates the
-command option list (following options are passed as arguments to the command).
-        the name of a python file (.py) to execute read from stdin.
-script  Anything afterward is passed as options to python script or command,
-        not interpreted as an option to interpreter itself.
-args    passed to script or command (in sys.argv[1:])
-        If no script or command, Python enters interactive mode.
-
-  * Available IDEs in std distrib: IDLE (tkinter based, portable), Pythonwin
-    (Windows).
-
-
-
-Environment variables
-
-                             Environment variables
-    Variable                                 Effect
-PYTHONHOME       Alternate prefix directory (or prefix;exec_prefix). The
-                 default module search path uses prefix/lib
-                 Augments the default search path for module files. The format
-                 is the same as the shell's $PATH: one or more directory
-                 pathnames separated by ':' or ';' without spaces around
-                 (semi-)colons!
-PYTHONPATH       On Windows first search for Registry key HKEY_LOCAL_MACHINE\
-                 Software\Python\PythonCore\x.y\PythonPath (default value). You
-                 may also define a key named after your application with a
-                 default string value giving the root directory path of your
-                 app.
-                 If this is the name of a readable file, the Python commands in
-PYTHONSTARTUP    that file are executed before the first prompt is displayed in
-                 interactive mode (no default).
-PYTHONDEBUG      If non-empty, same as -d option
-PYTHONINSPECT    If non-empty, same as -i option
-PYTHONSUPPRESS   If non-empty, same as -s option
-PYTHONUNBUFFERED If non-empty, same as -u option
-PYTHONVERBOSE    If non-empty, same as -v option
-PYTHONCASEOK     If non-empty, ignore case in file/module names (imports)
-
-
-
-
-Notable lexical entities
-
-Keywords
-
-    and       del       for       is        raise
-    assert    elif      from      lambda    return
-    break     else      global    not       try
-    class     except    if        or        while
-    continue  exec      import    pass      yield
-    def       finally   in        print
-
-  * (list of keywords in std module: keyword)
-  * Illegitimate Tokens (only valid in strings): @ $ ?
-  * A statement must all be on a single line. To break a statement over
-    multiple lines use "\", as with the C preprocessor.
-    Exception: can always break when inside any (), [], or {} pair, or in
-    triple-quoted strings.
-  * More than one statement can appear on a line if they are separated with
-    semicolons (";").
-  * Comments start with "#" and continue to end of line.
-
-Identifiers
-
-        (letter | "_")  (letter | digit | "_")*
-
-  * Python identifiers keywords, attributes, etc. are case-sensitive.
-  * Special forms: _ident (not imported by 'from module import *'); __ident__
-    (system defined name);
-               __ident (class-private name mangling)
-
-Strings
-
-    "a string enclosed by double quotes"
-    'another string delimited by single quotes and with a " inside'
-    '''a string containing embedded newlines and quote (') marks, can be
-    delimited with triple quotes.'''
-    """ may also use 3- double quotes as delimiters """
-    u'a unicode string'   U"Another unicode string"
-    r'a raw string where \ are kept (literalized): handy for regular
-    expressions and windows paths!'
-    R"another raw string"    -- raw strings cannot end with a \
-    ur'a unicode raw string'   UR"another raw unicode"
-
-        Use \ at end of line to continue a string on next line.
-        adjacent strings are concatened, e.g. 'Monty' ' Python' is the same as
-        'Monty Python'.
-        u'hello' + ' world'  --> u'hello world'   (coerced to unicode)
-
-    String Literal Escapes
-
-     \newline  Ignored (escape newline)
-     \\ Backslash (\)        \e Escape (ESC)        \v Vertical Tab (VT)
-     \' Single quote (')     \f Formfeed (FF)       \OOO char with octal value OOO
-     \" Double quote (")     \n Linefeed (LF)
-     \a Bell (BEL)           \r Carriage Return (CR) \xHH  char with hex value HH
-     \b Backspace (BS)       \t Horizontal Tab (TAB)
-     \uHHHH  unicode char with hex value HHHH, can only be used in unicode string
-     \UHHHHHHHH  unicode char with hex value HHHHHHHH, can only be used in unicode string
-     \AnyOtherChar is left as-is
-
-  * NUL byte (\000) is NOT an end-of-string marker; NULs may be embedded in
-    strings.
-  * Strings (and tuples) are immutable: they cannot be modified.
-
-Numbers
-
-    Decimal integer: 1234, 1234567890546378940L        (or l)
-    Octal integer: 0177, 0177777777777777777 (begin with a 0)
-    Hex integer: 0xFF, 0XFFFFffffFFFFFFFFFF (begin with 0x or 0X)
-    Long integer (unlimited precision): 1234567890123456
-    Float (double precision): 3.14e-10, .001, 10., 1E3
-    Complex: 1J, 2+3J, 4+5j (ends with J or j, + separates (float) real and
-    imaginary parts)
-
-Sequences
-
-  * String of length 0, 1, 2 (see above)
-    '', '1', "12", 'hello\n'
-  * Tuple of length 0, 1, 2, etc:
-    () (1,) (1,2)     # parentheses are optional if len > 0
-  * List of length 0, 1, 2, etc:
-    [] [1] [1,2]
-
-Indexing is 0-based. Negative indices (usually) mean count backwards from end
-of sequence.
-
-Sequence slicing [starting-at-index : but-less-than-index]. Start defaults to
-'0'; End defaults to 'sequence-length'.
-
-a = (0,1,2,3,4,5,6,7)
-    a[3] ==> 3
-    a[-1] ==> 7
-    a[2:4] ==> (2, 3)
-    a[1:] ==> (1, 2, 3, 4, 5, 6, 7)
-    a[:3] ==> (0, 1, 2)
-    a[:] ==> (0,1,2,3,4,5,6,7)  # makes a copy of the sequence.
-
-Dictionaries (Mappings)
-
-    {}                              # Zero length empty dictionary
-    {1 : 'first'}                   # Dictionary with one (key, value) pair
-    {1 : 'first',  'next': 'second'}
-    dict([('one',1),('two',2)])     # Construct a dict from an item list
-    dict('one'=1, 'two'=2)          # Construct a dict using keyword args
-    dict.fromkeys(['one', 'keys'])  # Construct a dict from a sequence
-
-Operators and their evaluation order
-
-                     Operators and their evaluation order
-Highest             Operator                             Comment
-        (...) [...] {...} `...`           Tuple, list & dict. creation; string
-                                          conv.
-        s[i]  s[i:j]  s.attr f(...)       indexing & slicing; attributes, fct
-                                          calls
-        +x, -x, ~x                        Unary operators
-        x**y                              Power
-        x*y  x/y  x%y x//y                mult, division, modulo, floor division
-        x+y  x-y                          addition, subtraction
-        x<<y   x>>y                       Bit shifting
-        x&y                               Bitwise and
-        x^y                               Bitwise exclusive or
-        x|y                               Bitwise or
-        x<y  x<=y  x>y  x>=y  x==y x!=y   Comparison,
-        x is y   x is not y               membership
-        x in s   x not in s
-        not x                             boolean negation
-        x and y                           boolean and
-        x or y                            boolean or
-Lowest  lambda args: expr                 anonymous function
-
-Alternate names are defined in module operator (e.g. __add__ and add for +)
-Most operators are overridable.
-
-Many binary operators also support augmented assignment:
-        x += 1                            # Same as x = x + 1
-
-
-Basic Types and Their Operations
-
-Comparisons (defined between *any* types)
-
-               Comparisons
-Comparison         Meaning          Notes
-<          strictly less than        (1)
-<=         less than or equal to
->          strictly greater than
->=         greater than or equal to
-==         equal to
-!=         not equal to
-is         object identity           (2)
-is not     negated object identity   (2)
-
-Notes :
-    Comparison behavior can be overridden for a given class by defining special
-method __cmp__.
-    The above comparisons return True or False which are of type bool
-(a subclass of int) and behave exactly as 1 or 0 except for their type and
-that they print as True or False instead of 1 or 0.
-    (1) X < Y < Z < W has expected meaning, unlike C
-    (2) Compare object identities (i.e. id(object)), not object values.
-
-Boolean values and operators
-
-                         Boolean values and operators
-              Value or Operator                         Returns           Notes
-None, numeric zeros, empty sequences and      False
-mappings
-all other values                              True
-not x                                         True if x is False, else
-                                              True
-x or y                                        if x is False then y, else   (1)
-                                              x
-x and y                                       if x is False then x, else   (1)
-                                              y
-
-Notes :
-    Truth testing behavior can be overridden for a given class by defining
-special method __bool__.
-    (1) Evaluate second arg only if necessary to determine outcome.
-
-None
-
-    None is used as default return value on functions. Built-in single object
-    with type NoneType.
-    Input that evaluates to None does not print when running Python
-    interactively.
-
-Numeric types
-
-Floats and integers.
-
-    Floats are implemented with C doubles.
-    Integers have unlimited size (only limit is system resources)
-
-Operators on all numeric types
-
-           Operators on all numeric types
- Operation                    Result
-abs(x)       the absolute value of x
-int(x)       x converted to integer
-float(x)     x converted to floating point
--x           x negated
-+x           x unchanged
-x + y        the sum of x and y
-x - y        difference of x and y
-x * y        product of x and y
-x / y        quotient of x and y
-x % y        remainder of x / y
-divmod(x, y) the tuple (x/y, x%y)
-x ** y       x to the power y (the same as pow(x, y))
-
-Bit operators on integers
-
-              Bit operators
-Operation             >Result
-~x        the bits of x inverted
-x ^ y     bitwise exclusive or of x and y
-x & y     bitwise and of x and y
-x | y     bitwise or of x and y
-x << n    x shifted left by n bits
-x >> n    x shifted right by n bits
-
-Complex Numbers
-
-  * represented as a pair of machine-level double precision floating point
-    numbers.
-  * The real and imaginary value of a complex number z can be retrieved through
-    the attributes z.real and z.imag.
-
-Numeric exceptions
-
-TypeError
-    raised on application of arithmetic operation to non-number
-OverflowError
-     numeric bounds exceeded
-ZeroDivisionError
-     raised when zero second argument of div or modulo op
-FloatingPointError
-     raised when a floating point operation fails
-
-Operations on all sequence types (lists, tuples, strings)
-
-                Operations on all sequence types
-Operation                     Result                     Notes
-x in s     True if an item of s is equal to x, else False
-x not in s False if an item of s is equal to x, else True
-for x in s: loops over the sequence
-s + t      the concatenation of s and t
-s * n, n*s n copies of s concatenated
-s[i]       i'th item of s, origin 0                       (1)
-s[i:j]     slice of s from i (included) to j (excluded) (1), (2)
-len(s)     length of s
-min(s)     smallest item of s
-max(s)     largest item of (s)
-iter(s)    returns an iterator over s.  iterators define __iter__ and next()
-
-Notes :
-    (1) if i or j is negative, the index is relative to the end of the string,
-ie len(s)+ i or len(s)+j is
-         substituted. But note that -0 is still 0.
-    (2) The slice of s from i to j is defined as the sequence of items with
-index k such that i <= k < j.
-          If i or j is greater than len(s), use len(s). If i is omitted, use
-len(s). If i is greater than or
-          equal to j, the slice is empty.
-
-Operations on mutable (=modifiable) sequences (lists)
-
-                 Operations on mutable sequences
-   Operation                      Result                   Notes
-s[i] =x          item i of s is replaced by x
-s[i:j] = t       slice of s from i to j is replaced by t
-del s[i:j]       same as s[i:j] = []
-s.append(x)      same as s[len(s) : len(s)] = [x]
-s.count(x)       return number of i's for which s[i] == x
-s.extend(x)      same as s[len(s):len(s)]= x
-s.index(x)       return smallest i such that s[i] == x      (1)
-s.insert(i, x)   same as s[i:i] = [x] if i >= 0
-s.pop([i])       same as x = s[i]; del s[i]; return x       (4)
-s.remove(x)      same as del s[s.index(x)]                  (1)
-s.reverse()      reverse the items of s in place            (3)
-s.sort([cmpFct]) sort the items of s in place             (2), (3)
-
-Notes :
-    (1) raise a ValueError exception when x is not found in s (i.e. out of
-range).
-     (2) The sort() method takes an optional argument specifying a comparison
-fct of 2 arguments (list items) which should
-          return -1, 0, or 1 depending on whether the 1st argument is
-considered smaller than, equal to, or larger than the 2nd
-          argument. Note that this slows the sorting process down considerably.
-     (3) The sort() and reverse() methods modify the list in place for economy
-of space when sorting or reversing a large list.
-           They don't return the sorted or reversed list to remind you of this
-side effect.
-     (4) [New 1.5.2] The optional  argument i defaults to -1, so that by default the last
-item is removed and returned.
-
-
-
-Operations on mappings (dictionaries)
-
-                         Operations on mappings
-        Operation                          Result                  Notes
-len(d)                     the number of items in d
-d[k]                       the item of d with key k                 (1)
-d[k] = x                   set d[k] to x
-del d[k]                   remove d[k] from d                       (1)
-d.clear()                  remove all items from d
-d.copy()                   a shallow copy of d
-d.get(k,defaultval)        the item of d with key k                 (4)
-d.has_key(k)               True if d has key k, else False
-d.items()                  a copy of d's list of (key, item) pairs  (2)
-d.iteritems()              an iterator over (key, value) pairs      (7)
-d.iterkeys()               an iterator over the keys of d           (7)
-d.itervalues()             an iterator over the values of d         (7)
-d.keys()                   a copy of d's list of keys               (2)
-d1.update(d2)              for k, v in d2.items(): d1[k] = v        (3)
-d.values()                 a copy of d's list of values             (2)
-d.pop(k)                   remove d[k] and return its value
-d.popitem()                remove and return an arbitrary           (6)
-                           (key, item) pair
-d.setdefault(k,defaultval) the item of d with key k                 (5)
-
-    Notes :
-      TypeError is raised if key is not acceptable
-      (1) KeyError is raised if key k is not in the map
-      (2) Keys and values are listed in random order
-      (3) d2 must be of the same type as d1
-      (4) Never raises an exception if k is not in the map, instead it returns
-    defaultVal.
-          defaultVal is optional, when not provided and k is not in the map,
-    None is returned.
-      (5) Never raises an exception if k is not in the map, instead it returns
-    defaultVal, and adds k to map with value defaultVal. defaultVal is
-    optional. When not provided and k is not in the map, None is returned and
-    added to map.
-      (6) Raises a KeyError if the dictionary is emtpy.
-      (7) While iterating over a dictionary, the values may be updated but
-          the keys cannot be changed.
-
-Operations on strings
-
-Note that these string methods largely (but not completely) supersede the
-functions available in the string module.
-
-
-                             Operations on strings
-    Operation                             Result                          Notes
-s.capitalize()    return a copy of s with only its first character
-                  capitalized.
-s.center(width)   return a copy of s centered in a string of length width  (1)
-                  .
-s.count(sub[      return the number of occurrences of substring sub in     (2)
-,start[,end]])    string s.
-s.decode(([       return a decoded version of s.                           (3)
-  encoding
-  [,errors]])
-s.encode([        return an encoded version of s. Default encoding is the
-  encoding        current default string encoding.                         (3)
-  [,errors]])
-s.endswith(suffix return true if s ends with the specified suffix,         (2)
-  [,start[,end]]) otherwise return False.
-s.expandtabs([    return a copy of s where all tab characters are          (4)
-tabsize])         expanded using spaces.
-s.find(sub[,start return the lowest index in s where substring sub is      (2)
-[,end]])          found. Return -1 if sub is not found.
-s.index(sub[      like find(), but raise ValueError when the substring is  (2)
-,start[,end]])    not found.
-s.isalnum()       return True if all characters in s are alphanumeric,     (5)
-                  False otherwise.
-s.isalpha()       return True if all characters in s are alphabetic,       (5)
-                  False otherwise.
-s.isdigit()       return True if all characters in s are digit             (5)
-                  characters, False otherwise.
-s.islower()       return True if all characters in s are lowercase, False  (6)
-                  otherwise.
-s.isspace()       return True if all characters in s are whitespace        (5)
-                  characters, False otherwise.
-s.istitle()       return True if string s is a titlecased string, False    (7)
-                  otherwise.
-s.isupper()       return True if all characters in s are uppercase, False  (6)
-                  otherwise.
-s.join(seq)       return a concatenation of the strings in the sequence
-                  seq, separated by 's's.
-s.ljust(width)    return s left justified in a string of length width.    (1),
-                                                                           (8)
-s.lower()         return a copy of s converted to lowercase.
-s.lstrip()        return a copy of s with leading whitespace removed.
-s.replace(old,    return a copy of s with all occurrences of substring     (9)
-new[, maxsplit])  old replaced by new.
-s.rfind(sub[      return the highest index in s where substring sub is     (2)
-,start[,end]])    found. Return -1 if sub is not found.
-s.rindex(sub[     like rfind(), but raise ValueError when the substring    (2)
-,start[,end]])    is not found.
-s.rjust(width)    return s right justified in a string of length width.   (1),
-                                                                           (8)
-s.rstrip()        return a copy of s with trailing whitespace removed.
-s.split([sep[     return a list of the words in s, using sep as the       (10)
-,maxsplit]])      delimiter string.
-s.splitlines([    return a list of the lines in s, breaking at line       (11)
-keepends])        boundaries.
-s.startswith      return true if s starts with the specified prefix,
-(prefix[,start[   otherwise return false.                                  (2)
-,end]])
-s.strip()         return a copy of s with leading and trailing whitespace
-                  removed.
-s.swapcase()      return a copy of s with uppercase characters converted
-                  to lowercase and vice versa.
-                  return a titlecased copy of s, i.e. words start with
-s.title()         uppercase characters, all remaining cased characters
-                  are lowercase.
-s.translate(table return a copy of s mapped through translation table     (12)
-[,deletechars])   table.
-s.upper()         return a copy of s converted to uppercase.
-s.zfill(width)    return a string padded with zeroes on the left side and
-                  sliding a minus sign left if necessary.  never truncates.
-
-Notes :
-    (1) Padding is done using spaces.
-    (2) If optional argument start is supplied, substring s[start:] is
-processed. If optional arguments start and end are supplied, substring s[start:
-end] is processed.
-    (3) Optional argument errors may be given to set a different error handling
-scheme. The default for errors is 'strict', meaning that encoding errors raise
-a ValueError. Other possible values are 'ignore' and 'replace'.
-    (4) If optional argument tabsize is not given, a tab size of 8 characters
-is assumed.
-    (5) Returns false if string s does not contain at least one character.
-    (6) Returns false if string s does not contain at least one cased
-character.
-    (7) A titlecased string is a string in which uppercase characters may only
-follow uncased characters and lowercase characters only cased ones.
-    (8) s is returned if width is less than len(s).
-    (9) If the optional argument maxsplit is given, only the first maxsplit
-occurrences are replaced.
-    (10) If sep is not specified or None, any whitespace string is a separator.
-If maxsplit is given, at most maxsplit splits are done.
-    (11) Line breaks are not included in the resulting list unless keepends is
-given and true.
-    (12) table must be a string of length 256. All characters occurring in the
-optional argument deletechars are removed prior to translation.
-
-String formatting with the % operator
-
-formatString % args--> evaluates to a string
-
-  * formatString uses C printf format codes : %, c, s, i, d, u, o, x, X, e, E,
-    f, g, G, r (details below).
-  * Width and precision may be a * to specify that an integer argument gives
-    the actual width or precision.
-  * The flag characters -, +, blank, # and 0 are understood. (details below)
-  * %s will convert any type argument to string (uses str() function)
-  * args may be a single arg or a tuple of args
-
-        '%s has %03d quote types.' % ('Python', 2)  # => 'Python has 002 quote types.'
-
-  * Right-hand-side can also be a mapping:
-
-        a = '%(lang)s has %(c)03d quote types.' % {'c':2, 'lang':'Python}
-(vars() function very handy to use on right-hand-side.)
-
-                                 Format codes
-Conversion                               Meaning
-d          Signed integer decimal.
-i          Signed integer decimal.
-o          Unsigned octal.
-u          Unsigned decimal.
-x          Unsigned hexadecimal (lowercase).
-X          Unsigned hexadecimal (uppercase).
-e          Floating point exponential format (lowercase).
-E          Floating point exponential format (uppercase).
-f          Floating point decimal format.
-F          Floating point decimal format.
-g          Same as "e" if exponent is greater than -4 or less than precision,
-           "f" otherwise.
-G          Same as "E" if exponent is greater than -4 or less than precision,
-           "F" otherwise.
-c          Single character (accepts integer or single character string).
-r          String (converts any python object using repr()).
-s          String (converts any python object using str()).
-%          No argument is converted, results in a "%" character in the result.
-           (The complete specification is %%.)
-
-                          Conversion flag characters
-Flag                                  Meaning
-#    The value conversion will use the ``alternate form''.
-0    The conversion will be zero padded.
--    The converted value is left adjusted (overrides "-").
-     (a space) A blank should be left before a positive number (or empty
-     string) produced by a signed conversion.
-+    A sign character ("+" or "-") will precede the conversion (overrides a
-     "space" flag).
-
-File Objects
-
-Created with built-in function open; may be created by other modules' functions
-as well.
-
-Operators on file objects
-
-                                File operations
-    Operation                                Result
-f.close()         Close file f.
-f.fileno()        Get fileno (fd) for file f.
-f.flush()         Flush file f's internal buffer.
-f.isatty()        True if file f is connected to a tty-like dev, else False.
-f.read([size])    Read at most size bytes from file f and return as a string
-                  object. If size omitted, read to EOF.
-f.readline()      Read one entire line from file f.
-f.readlines()     Read until EOF with readline() and return list of lines read.
-                  Set file f's position, like "stdio's fseek()".
-f.seek(offset[,   whence == 0 then use absolute indexing.
-whence=0])        whence == 1 then offset relative to current pos.
-                  whence == 2 then offset relative to file end.
-f.tell()          Return file f's current position (byte offset).
-f.write(str)      Write string to file f.
-f.writelines(list Write list of strings to file f.
-)
-
-File Exceptions
-
-  EOFError
-     End-of-file hit when reading (may be raised many times, e.g. if f is a
-    tty).
-  IOError
-     Other I/O-related I/O operation failure.
-  OSError
-     OS system call failed.
-
-
-    Advanced Types
-
-    -See manuals for more details -
-      + Module objects
-      + Class objects
-      + Class instance objects
-      + Type objects (see module: types)
-      + File objects (see above)
-      + Slice objects
-      + XRange objects
-      + Callable types:
-          o User-defined (written in Python):
-              # User-defined Function objects
-              # User-defined Method objects
-          o Built-in (written in C):
-              # Built-in Function objects
-              # Built-in Method objects
-      + Internal Types:
-          o Code objects (byte-compile executable Python code: bytecode)
-          o Frame objects (execution frames)
-          o Traceback objects (stack trace of an exception)
-
-
-    Statements
-
-    pass            -- Null statement
-    del name[,name]* -- Unbind name(s) from object. Object will be indirectly
-                        (and automatically) deleted only if no longer referenced.
-    print [>> fileobject,] [s1 [, s2 ]* [,]
-                    -- Writes to sys.stdout, or to fileobject if supplied.
-                       Puts spaces between arguments. Puts newline at end
-                       unless statement ends with comma.
-                       Print is not required when running interactively,
-                       simply typing an expression will print its value,
-                       unless the value is None.
-    exec x [in globals [,locals]]
-                    -- Executes x in namespaces provided. Defaults
-                       to current namespaces. x can be a string, file
-                       object or a function object.
-    callable(value,... [id=value], [*args], [**kw])
-                    -- Call function callable with parameters. Parameters can
-                       be passed by name or be omitted if function
-                       defines default values. E.g. if callable is defined as
-                       "def callable(p1=1, p2=2)"
-                       "callable()"       <=>  "callable(1, 2)"
-                       "callable(10)"     <=>  "callable(10, 2)"
-                       "callable(p2=99)"  <=>  "callable(1, 99)"
-                       *args is a tuple of positional arguments.
-                       **kw is a dictionary of keyword arguments.
-
-    Assignment operators
-
-                              Caption
-    Operator                    Result                     Notes
-    a = b    Basic assignment - assign object b to label a  (1)
-    a += b   Roughly equivalent to a = a + b                (2)
-    a -= b   Roughly equivalent to a = a - b                (2)
-    a *= b   Roughly equivalent to a = a * b                (2)
-    a /= b   Roughly equivalent to a = a / b                (2)
-    a %= b   Roughly equivalent to a = a % b                (2)
-    a **= b  Roughly equivalent to a = a ** b               (2)
-    a &= b   Roughly equivalent to a = a & b                (2)
-    a |= b   Roughly equivalent to a = a | b                (2)
-    a ^= b   Roughly equivalent to a = a ^ b                (2)
-    a >>= b  Roughly equivalent to a = a >> b               (2)
-    a <<= b  Roughly equivalent to a = a << b               (2)
-
-    Notes :
-        (1) Can unpack tuples, lists, and strings.
-           first, second = a[0:2]; [f, s] = range(2); c1,c2,c3='abc'
-           Tip: x,y = y,x swaps x and y.
-        (2) Not exactly equivalent - a is evaluated only once. Also, where
-    possible, operation performed in-place - a is modified rather than
-    replaced.
-
-    Control Flow
-
-    if condition: suite
-    [elif condition: suite]*
-    [else: suite]   -- usual if/else_if/else statement
-    while condition: suite
-    [else: suite]
-                    -- usual while statement. "else" suite is executed
-                       after loop exits, unless the loop is exited with
-                       "break"
-    for element in sequence: suite
-    [else: suite]
-                    -- iterates over sequence, assigning each element to element.
-                       Use built-in range function to iterate a number of times.
-                       "else" suite executed at end unless loop exited
-                       with "break"
-    break           -- immediately exits "for" or "while" loop
-    continue        -- immediately does next iteration of "for" or "while" loop
-    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__(),
-                       resumes execution at the frozen point with all of the local variables
-                       still intact.
-
-    Exception Statements
-
-    assert expr[, message]
-                    -- expr is evaluated. if false, raises exception AssertionError
-                       with message. Inhibited if __debug__ is 0.
-    try: suite1
-    [except [exception [, value]: suite2]+
-    [else: suite3]
-                    -- statements in suite1 are executed. If an exception occurs, look
-                       in "except" clauses for matching <exception>. If matches or bare
-                       "except" execute suite of that clause. If no exception happens
-                       suite in "else" clause is executed after suite1.
-                       If exception has a value, it is put in value.
-                       exception can also be tuple of exceptions, e.g.
-                       "except (KeyError, NameError), val: print val"
-    try: suite1
-    finally: suite2
-                    -- statements in suite1 are executed. If no
-                       exception, execute suite2 (even if suite1 is
-                       exited with a "return", "break" or "continue"
-                       statement). If exception did occur, executes
-                       suite2 and then immediately reraises exception.
-    raise exception [,value [, traceback]]
-                    -- raises exception with optional value
-                       value. Arg traceback specifies a traceback object to
-                       use when printing the exception's backtrace.
-    raise           -- a raise statement without arguments re-raises
-                       the last exception raised in the current function
-An exception is either a string (object) or a class instance.
-  Can create a new one simply by creating a new string:
-
-              my_exception = 'You did something wrong'
-      try:
-                   if bad:
-              raise my_exception, bad
-      except my_exception, value:
-                    print 'Oops', value
-
-Exception classes must be derived from the predefined class: Exception, e.g.:
-            class text_exception(Exception): pass
-            try:
-                if bad:
-                    raise text_exception()
-                    # This is a shorthand for the form
-                    # "raise <class>, <instance>"
-             except Exception:
-                 print 'Oops'
-                 # This will be printed because
-                 # text_exception is a subclass of Exception
-When an error message is printed for an unhandled exception which is a
-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 Exception, itself
-derived from BaseException.
-
-Name Space Statements
-
-[1.51: On Mac & Windows, the case of module file names must now match the case
-as used
-  in the import statement]
-Packages (>1.5): a package is a name space which maps to a directory including
-                module(s) and the special initialization module '__init__.py'
-                (possibly empty). Packages/dirs can be nested. You address a
-                module's symbol via '[package.[package...]module.symbol's.
-import module1 [as name1] [, module2]*
-                -- imports modules. Members of module must be
-                   referred to by qualifying with [package.]module name:
-                   "import sys; print sys.argv:"
-                   "import package1.subpackage.module; package1.subpackage.module.foo()"
-                   module1 renamed as name1, if supplied.
-from module import name1 [as othername1] [, name2]*
-                -- imports names from module module in current namespace.
-                   "from sys import argv; print argv"
-                   "from package1 import module; module.foo()"
-                   "from package1.module import foo; foo()"
-                   name1 renamed as othername1, if supplied.
-from module import *
-                -- imports all names in module, except those starting with "_";
-                   *to be used sparsely, beware of name clashes* :
-                   "from sys import *; print argv"
-                   "from package.module import *; print x'
-                    NB: "from package import *" only imports the symbols defined
-                    in the package's __init__.py file, not those in the
-                    template modules!
-global name1 [, name2]*
-                -- names are from global scope (usually meaning from module)
-                   rather than local (usually meaning only in function).
-                -- E.g. in fct without "global" statements, assuming
-                   "a" is name that hasn't been used in fct or module
-                   so far:
-                   -Try to read from "a" -> NameError
-                   -Try to write to "a" -> creates "a" local to fcn
-                   -If "a" not defined in fct, but is in module, then
-                       -Try to read from "a", gets value from module
-                       -Try to write to "a", creates "a" local to fct
-                   But note "a[0]=3" starts with search for "a",
-                   will use to global "a" if no local "a".
-
-Function Definition
-
-def func_id ([param_list]): suite
-                -- Creates a function object & binds it to name func_id.
-
-    param_list ::= [id [, id]*]
-    id ::= value | id = value | *id | **id
-    [Args are passed by value.Thus only args representing a mutable object
-    can be modified (are inout parameters). Use a tuple to return more than
-    one value]
-
-Example:
-        def test (p1, p2 = 1+1, *rest, **keywords):
-            -- Parameters with "=" have default value (v is
-               evaluated when function defined).
-               If list has "*id" then id is assigned a tuple of
-               all remaining args passed to function (like C vararg)
-               If list has "**id" then id is assigned a dictionary of
-               all extra arguments passed as keywords.
-
-Class Definition
-
-class <class_id> [(<super_class1> [,<super_class2>]*)]: <suite>
-        -- Creates a class object and assigns it name <class_id>
-           <suite> may contain local "defs" of class methods and
-           assignments to class attributes.
-Example:
-       class my_class (class1, class_list[3]): ...
-                  Creates a class object inheriting from both "class1" and whatever
-                  class object "class_list[3]" evaluates to. Assigns new
-                  class object to name "my_class".
-        - First arg to class methods is always instance object, called 'self'
-          by convention.
-        - Special method __init__() is called when instance is created.
-        - Special method __del__() called when no more reference to object.
-        - Create instance by "calling" class object, possibly with arg
-          (thus instance=apply(aClassObject, args...) creates an instance!)
-        - In current implementation, can't subclass off built-in
-          classes. But can "wrap" them, see UserDict & UserList modules,
-          and see __getattr__() below.
-Example:
-        class c (c_parent):
-           def __init__(self, name): self.name = name
-           def print_name(self): print "I'm", self.name
-           def call_parent(self): c_parent.print_name(self)
-           instance = c('tom')
-           print instance.name
-           'tom'
-           instance.print_name()
-           "I'm tom"
-        Call parent's super class by accessing parent's method
-        directly and passing "self" explicitly (see "call_parent"
-        in example above).
-        Many other special methods available for implementing
-        arithmetic operators, sequence, mapping indexing, etc.
-
-Documentation Strings
-
-Modules, classes and functions may be documented by placing a string literal by
-itself as the first statement in the suite. The documentation can be retrieved
-by getting the '__doc__' attribute from the module, class or function.
-Example:
-        class C:
-            "A description of C"
-            def __init__(self):
-                "A description of the constructor"
-                # etc.
-Then c.__doc__ == "A description of C".
-Then c.__init__.__doc__ == "A description of the constructor".
-
-Others
-
-lambda [param_list]: returnedExpr
-                -- Creates an anonymous function. returnedExpr must be
-                   an expression, not a statement (e.g., not "if xx:...",
-                   "print xxx", etc.) and thus can't contain newlines.
-                   Used mostly for filter(), map() functions, and GUI callbacks..
-List comprehensions
-result = [expression for item1 in sequence1  [if condition1]
-                        [for item2 in sequence2 ... for itemN in sequenceN]
-                      ]
-is equivalent to:
-result = []
-for item1 in sequence1:
-    for item2 in sequence2:
-    ...
-        for itemN in sequenceN:
-             if (condition1) and furthur conditions:
-                  result.append(expression)
-
-
-
-Built-In Functions
-
-                              Built-In Functions
-     Function                                 Result
-__import__(name[,   Imports module within the given context (see lib ref for
-globals[, locals[,  more details)
-fromlist]]])
-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.
-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.
-cmp(x,y)            Returns negative, 0, positive if x <, ==, > to y
-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
-                    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])       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]), ...
-eval(s[, globals[,  Eval string s in (optional) globals, locals contexts.s must
-locals]])           have no NUL's or newlines. s can also be acode object.
-                    Example: x = 1; incr_x = eval('x + 1')
-filter(function,    Constructs a list from those elements of sequence for which
-sequence)           function returns true. function takes one parameter.
-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,
-                    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)
-hash(object)        Returns the hash value of the object (if it has one)
-help(f)             Display documentation on object f.
-hex(x)              Converts a number x to a hexadecimal string.
-id(object)          Returns a unique 'identity' integer for an object.
-int(x[, base])      base paramenter specifies base from which to convert string
-                    values.
-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)
-                    Returns the length (the number of items) of an object
-iter(collection)    Returns an iterator over the collection.
-len(obj)            (sequence, dictionary, or instance of class implementing
-                    __len__).
-list(sequence)      Converts sequence into a list. If already a list,returns a
-                    copy of it.
-locals()            Returns a dictionary containing current local variables.
-                    Applies function to every item of list and returns a listof
-map(function, list, the results. If additional arguments are passed,function
-...)                must take that many arguments and it is givento function on
-                    each call.
-max(seq)            Returns the largest item of the non-empty sequence seq.
-min(seq)            Returns the smallest item of a non-empty sequence seq.
-oct(x)              Converts a number to an octal string.
-open(filename [,    Returns a new file object. First two args are same asthose
-mode='r', [bufsize= for C's "stdio open" function. bufsize is 0for unbuffered,
-implementation      1 for line-buffered, negative forsys-default, all else, of
-dependent]])        (about) given size.
-ord(c)              Returns integer ASCII value of c (a string of len 1). Works
-                    with Unicode char.
-object()            Create a base type.  Used as a superclass for new-style objects.
-open(name           Open a file.
-  [, mode
-  [, 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-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 = 3. Creates attribute if it doesn't exist!
-slice([start,] stop Returns a slice object representing a range, with R/
-[, 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)         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.
-sum(sequence,       Add the values in the sequence and return the sum.
-    [start]) 
-tuple(sequence)     Creates a tuple with same elements as sequence. If already
-                    a tuple, return itself (not a copy).
-                    Returns a type object [see module types] representing
-                    thetype of obj. Example: import typesif type(x) ==
-type(obj)           types.StringType: print 'It is a string'NB: it is
-                    recommanded to use the following form:if isinstance(x,
-                    types.StringType): etc...
-unichr(code)        code.
-unicode(string[,    Creates a Unicode string from a 8-bit string, using
-encoding[, error    thegiven encoding name and error treatment ('strict',
-]]])                'ignore',or 'replace'}.
-                    Without arguments, returns a dictionary correspondingto the
-                    current local symbol table. With a module,class or class
-vars([object])      instance object as argumentreturns a dictionary
-                    corresponding to the object'ssymbol table. Useful with "%"
-                    formatting operator.
-zip(seq1[, seq2,    Returns an iterator of tuples where each tuple contains
-...])               the nth element of each of the argument sequences.
-
-
-
-Built-In Exceptions
-
-Exception>
-         Root class for all exceptions
-    SystemExit
-         On 'sys.exit()'
-    StopIteration
-         Signal the end from iterator.__next__()
-        ArithmeticError
-                 Base class for OverflowError, ZeroDivisionError,
-    FloatingPointError
-            FloatingPointError
-                       When a floating point operation fails.
-            OverflowError
-                            On excessively large arithmetic operation
-            ZeroDivisionError
-                  On division or modulo operation with 0 as 2nd arg
-            AssertionError
-                When an assert statement fails.
-        AttributeError
-                    On attribute reference or assignment failure
-        EnvironmentError    [new in 1.5.2]
-                On error outside Python; error arg tuple is (errno, errMsg...)
-            IOError    [changed in 1.5.2]
-               I/O-related operation failure
-            OSError    [new in 1.5.2]
-               used by the os module's os.error exception.
-        EOFError
-                    Immediate end-of-file hit by input() or raw_input()
-        ImportError
-         On failure of `import' to find module or name
-        KeyboardInterrupt
-         On user entry of the interrupt key (often `Control-C')
-        LookupError
-                base class for IndexError, KeyError
-            IndexError
-                 On out-of-range sequence subscript
-            KeyError
-                 On reference to a non-existent mapping (dict) key
-        MemoryError
-         On recoverable memory exhaustion
-        NameError
-         On failure to find a local or global (unqualified) name
-        RuntimeError
-         Obsolete catch-all; define a suitable error instead
-          NotImplementedError   [new in 1.5.2]
-                On method not implemented
-        SyntaxError
-         On parser encountering a syntax error
-       IndentationError
-           On parser encountering an indentation syntax error
-       TabError
-           On parser encountering an indentation syntax error
-        SystemError
-         On non-fatal interpreter error - bug - report it
-        TypeError
-         On passing inappropriate type to built-in op or func
-        ValueError
-         On arg error not covered by TypeError or more precise
-    Warning
-              UserWarning
-              DeprecationWarning
-              PendingDeprecationWarning
-              SyntaxWarning
-              RuntimeWarning
-              FutureWarning
-
-
-
-Standard methods & operators redefinition in classes
-
-Standard methods & operators map to special '__methods__' and thus may be
- redefined (mostly in user-defined classes), e.g.:
-    class x:
-         def __init__(self, v): self.value = v
-         def __add__(self, r): return self.value + r
-    a = x(3) # sort of like calling x.__init__(a, 3)
-    a + 4    # is equivalent to a.__add__(4)
-
-Special methods for any class
-
-(s: self, o: other)
-        __init__(s, args) instance initialization (on construction)
-        __del__(s)        called on object demise (refcount becomes 0)
-        __repr__(s)       repr() and `...` conversions
-        __str__(s)        str() and 'print' statement
-        __cmp__(s, o)     Compares s to o and returns <0, 0, or >0.
-                          Implements >, <, == etc...
-        __hash__(s)       Compute a 32 bit hash code; hash() and dictionary ops
-        __bool__(s)    Returns False or True for truth value testing
-        __getattr__(s, name)  called when attr lookup doesn't find <name>
-        __setattr__(s, name, val) called when setting an attr
-                                  (inside, don't use "self.name = value"
-                                   use "self.__dict__[name] = val")
-        __delattr__(s, name)  called to delete attr <name>
-        __call__(self, *args) called when an instance is called as function.
-
-Operators
-
-    See list in the operator module. Operator function names are provided with
-    2 variants, with or without
-    ading & trailing '__' (eg. __add__ or add).
-
-    Numeric operations special methods
-    (s: self, o: other)
-
-        s+o       =  __add__(s,o)         s-o        =  __sub__(s,o)
-        s*o       =  __mul__(s,o)         s/o        =  __div__(s,o)
-        s%o       =  __mod__(s,o)         divmod(s,o) = __divmod__(s,o)
-        s**o      =  __pow__(s,o)
-        s&o       =  __and__(s,o)
-        s^o       =  __xor__(s,o)         s|o        =  __or__(s,o)
-        s<<o      =  __lshift__(s,o)      s>>o       =  __rshift__(s,o)
-        bool(s) = __bool__(s) (used in boolean testing)
-        -s        =  __neg__(s)           +s         =  __pos__(s)
-        abs(s)    =  __abs__(s)           ~s         =  __invert__(s)  (bitwise)
-        s+=o      =  __iadd__(s,o)        s-=o       =  __isub__(s,o)
-        s*=o      =  __imul__(s,o)        s/=o       =  __idiv__(s,o)
-        s%=o      =  __imod__(s,o)
-        s**=o     =  __ipow__(s,o)
-        s&=o      =  __iand__(s,o)
-        s^=o      =  __ixor__(s,o)        s|=o       =  __ior__(s,o)
-        s<<=o     =  __ilshift__(s,o)     s>>=o      =  __irshift__(s,o)
-        Conversions
-        int(s)    =  __int__(s)
-        float(s)  =  __float__(s)         complex(s)    =  __complex__(s)
-        oct(s)    =  __oct__(s)           hex(s)     =  __hex__(s)
-        Right-hand-side equivalents for all binary operators exist;
-        are called when class instance is on r-h-s of operator:
-        a + 3  calls __add__(a, 3)
-        3 + a  calls __radd__(a, 3)
-
-    All seqs and maps, general operations plus:
-    (s: self, i: index or key)
-
-        len(s)    = __len__(s)        length of object, >= 0.  Length 0 == false
-        s[i]      = __getitem__(s,i)  Element at index/key i, origin 0
-
-    Sequences, general methods, plus:
-      s[i]=v           = __setitem__(s,i,v)
-      del s[i]         = __delitem__(s,i)
-      s[i:j]           = __getslice__(s,i,j)
-      s[i:j]=seq       = __setslice__(s,i,j,seq)
-      del s[i:j]       = __delslice__(s,i,j)   == s[i:j] = []
-      seq * n          = __repeat__(seq, n)
-      s1 + s2          = __concat__(s1, s2)
-      i in s           = __contains__(s, i)
-    Mappings, general methods, plus
-      hash(s)          = __hash__(s) - hash value for dictionary references
-      s[k]=v           = __setitem__(s,k,v)
-      del s[k]         = __delitem__(s,k)
-
-Special informative state attributes for some types:
-
-    Modules:
-        __doc__ (string/None, R/O): doc string (<=> __dict__['__doc__'])
-        __name__(string, R/O): module name (also in __dict__['__name__'])
-        __dict__ (dict, R/O): module's name space
-        __file__(string/undefined, R/O): pathname of .pyc, .pyo or .pyd (undef for
-                 modules statically linked to the interpreter)
-
-    Classes:    [in bold: writable since 1.5.2]
-        __doc__ (string/None, R/W): doc string (<=> __dict__['__doc__'])
-        __module__ is the module name in which the class was defined
-        __name__(string, R/W): class name (also in __dict__['__name__'])
-        __bases__ (tuple, R/W): parent classes
-        __dict__ (dict, R/W): attributes (class name space)
-
-    Instances:
-        __class__ (class, R/W): instance's class
-        __dict__ (dict, R/W): attributes
-
-    User-defined functions: [bold: writable since 1.5.2]
-        __doc__ (string/None, R/W): doc string
-        __name__(string, R/O): function name
-        func_doc (R/W): same as __doc__
-        func_name (R/O): same as __name__
-        func_defaults (tuple/None, R/W): default args values if any
-        func_code (code, R/W): code object representing the compiled function body
-        func_globals (dict, R/O): ref to dictionary of func global variables
-        func_dict (dict, R/W):  same as __dict__ contains the namespace supporting
-            arbitrary function attributes
-        func_closure (R/O): None or a tuple of cells that contain bindings
-            for the function's free variables.
-
-
-    User-defined Methods:
-        __doc__ (string/None, R/O): doc string
-        __name__(string, R/O): method name (same as im_func.__name__)
-        im_class (class, R/O): class defining the method (may be a base class)
-        im_self (instance/None, R/O): target instance object (None if unbound)
-        im_func (function, R/O): function object
-
-    Built-in Functions & methods:
-        __doc__ (string/None, R/O): doc string
-        __name__ (string, R/O): function name
-        __self__ : [methods only] target object
-
-    Codes:
-        co_name (string, R/O): function name
-        co_argcount (int, R/0): number of positional args
-        co_nlocals (int, R/O): number of local vars (including args)
-        co_varnames (tuple, R/O): names of local vars (starting with args)
-        co_cellvars (tuple, R/O)) the names of local variables referenced by
-            nested functions
-        co_freevars (tuple, R/O)) names of free variables
-        co_code (string, R/O): sequence of bytecode instructions
-        co_consts (tuple, R/O): litterals used by the bytecode, 1st one is
-                                fct doc (or None)
-        co_names (tuple, R/O): names used by the bytecode
-        co_filename (string, R/O): filename from which the code was compiled
-        co_firstlineno (int, R/O): first line number of the function
-        co_lnotab (string, R/O): string encoding bytecode offsets to line numbers.
-        co_stacksize (int, R/O): required stack size (including local vars)
-        co_flags (int, R/O): flags for the interpreter
-                           bit 2 set if fct uses "*arg" syntax
-                           bit 3 set if fct uses '**keywords' syntax
-    Frames:
-        f_back (frame/None, R/O): previous stack frame (toward the caller)
-        f_code (code, R/O): code object being executed in this frame
-        f_locals (dict, R/O): local vars
-        f_globals (dict, R/O): global vars
-        f_builtins (dict, R/O): built-in (intrinsic) names
-        f_restricted (int, R/O): flag indicating whether fct is executed in
-                                 restricted mode
-        f_lineno (int, R/O): current line number
-        f_lasti (int, R/O): precise instruction (index into bytecode)
-        f_trace (function/None, R/W): debug hook called at start of each source line
-    Tracebacks:
-        tb_next (frame/None, R/O): next level in stack trace (toward the frame where
-                                  the exception occurred)
-        tb_frame (frame, R/O): execution frame of the current level
-        tb_lineno (int, R/O): line number where the exception occurred
-        tb_lasti (int, R/O): precise instruction (index into bytecode)
-
-    Slices:
-        start (any/None, R/O): lowerbound
-        stop (any/None, R/O): upperbound
-        step (any/None, R/O): step value
-
-    Complex numbers:
-        real (float, R/O): real part
-        imag (float, R/O): imaginary part
-
-
-Important Modules
-
-                                      sys
-
-                              Some sys variables
-      Variable                                Content
-argv                 The list of command line arguments passed to aPython
-                     script. sys.argv[0] is the script name.
-builtin_module_names A list of strings giving the names of all moduleswritten
-                     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)
-last_type,           Set only when an exception not handled andinterpreter
-last_value,          prints an error. Used by debuggers.
-last_traceback
-maxint               maximum positive value for integers
-modules              Dictionary of modules that have already been loaded.
-path                 Search path for external modules. Can be modifiedby
-                     program. sys.path[0] == dir of script executing
-platform             The current platform, e.g. "sunos5", "win32"
-ps1, ps2             prompts to use in interactive mode.
-                     File objects used for I/O. One can redirect byassigning a
-stdin, stdout,       new file object to them (or any object:.with a method
-stderr               write(string) for stdout/stderr,.with a method readline()
-                     for stdin)
-version              string containing version info about Python interpreter.
-                     (and also: copyright, dllhandle, exec_prefix, prefix)
-version_info         tuple containing Python version info - (major, minor,
-                     micro, level, serial).
-
-                              Some sys functions
-     Function                                 Result
-exit(n)            Exits with status n. Raises SystemExit exception.(Hence can
-                   be caught and ignored by program)
-getrefcount(object Returns the reference count of the object. Generally one
-)                  higher than you might expect, because of object arg temp
-                   reference.
-setcheckinterval(  Sets the interpreter's thread switching interval (in number
-interval)          of virtual code instructions, default:100).
-settrace(func)     Sets a trace function: called before each line ofcode is
-                   exited.
-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 local variable in a
-                   function handling an exception will cause a circular
-                   reference.
-getrecursionlimit  Retrieve maximum recursion depth.
-()
-setrecursionlimit  Set maximum recursion depth. (Defaults to 1000.)
-()
-
-
-
-                                      os
-"synonym" for whatever O/S-specific module is proper for current environment.
-this module uses posix whenever possible.
-(see also M.A. Lemburg's utility http://www.lemburg.com/files/python/
-platform.py)
-
-                               Some os variables
-     Variable                                 Meaning
-name                name of O/S-specific module (e.g. "posix", "mac", "nt")
-path                O/S-specific module for path manipulations.
-                    On Unix, os.path.split() <=> posixpath.split()
-curdir              string used to represent current directory ('.')
-pardir              string used to represent parent directory ('..')
-sep                 string used to separate directories ('/' or '\'). Tip: use
-                    os.path.join() to build portable paths.
-altsep              Alternate sep
-if applicable (None
-otherwise)
-pathsep             character used to separate search path components (as in
-                    $PATH), eg. ';' for windows.
-linesep             line separator as used in binary files, ie '\n' on Unix, '\
-                    r\n' on Dos/Win, '\r'
-
-                               Some os functions
-     Function                                 Result
-makedirs(path[,     Recursive directory creation (create required intermediary
-mode=0777])         dirs); os.error if fails.
-removedirs(path)    Recursive directory delete (delete intermediary empty
-                    dirs); if fails.
-renames(old, new)   Recursive directory or file renaming; os.error if fails.
-
-
-
-                                     posix
-don't import this module directly, import os instead !
-(see also module: shutil for file copy & remove fcts)
-
-                            posix Variables
-Variable                             Meaning
-environ  dictionary of environment variables, e.g.posix.environ['HOME'].
-error    exception raised on POSIX-related error.
-         Corresponding value is tuple of errno code and perror() string.
-
-                             Some posix functions
-   Function                                 Result
-chdir(path)     Changes current directory to path.
-chmod(path,     Changes the mode of path to the numeric mode
-mode)
-close(fd)       Closes file descriptor fd opened with posix.open.
-_exit(n)        Immediate exit, with no cleanups, no SystemExit,etc. Should use
-                this to exit a child process.
-execv(p, args)  "Become" executable p with args args
-getcwd()        Returns a string representing the current working directory
-getpid()        Returns the current process id
-fork()          Like C's fork(). Returns 0 to child, child pid to parent.[Not
-                on Windows]
-kill(pid,       Like C's kill [Not on Windows]
-signal)
-listdir(path)   Lists (base)names of entries in directory path, excluding '.'
-                and '..'
-lseek(fd, pos,  Sets current position in file fd to position pos, expressedas
-how)            an offset relative to beginning of file (how=0), tocurrent
-                position (how=1), or to end of file (how=2)
-mkdir(path[,    Creates a directory named path with numeric mode (default 0777)
-mode])
-open(file,      Like C's open(). Returns file descriptor. Use file object
-flags, mode)    fctsrather than this low level ones.
-pipe()          Creates a pipe. Returns pair of file descriptors (r, w) [Not on
-                Windows].
-popen(command,  Opens a pipe to or from command. Result is a file object to
-mode='r',       read to orwrite from, as indicated by mode being 'r' or 'w'.
-bufSize=0)      Use it to catch acommand output ('r' mode) or to feed it ('w'
-                mode).
-remove(path)    See unlink.
-rename(src, dst Renames/moves the file or directory src to dst. [error iftarget
-)               name already exists]
-rmdir(path)     Removes the empty directory path
-read(fd, n)     Reads n bytes from file descriptor fd and return as string.
-                Returns st_mode, st_ino, st_dev, st_nlink, st_uid,st_gid,
-stat(path)      st_size, st_atime, st_mtime, st_ctime.[st_ino, st_uid, st_gid
-                are dummy on Windows]
-system(command) Executes string command in a subshell. Returns exitstatus of
-                subshell (usually 0 means OK).
-                Returns accumulated CPU times in sec (user, system, children's
-times()         user,children's sys, elapsed real time). [3 last not on
-                Windows]
-unlink(path)    Unlinks ("deletes") the file (not dir!) path. same as: remove
-utime(path, (   Sets the access & modified time of the file to the given tuple
-aTime, mTime))  of values.
-wait()          Waits for child process completion. Returns tuple ofpid,
-                exit_status [Not on Windows]
-waitpid(pid,    Waits for process pid to complete. Returns tuple ofpid,
-options)        exit_status [Not on Windows]
-write(fd, str)  Writes str to file fd. Returns nb of bytes written.
-
-
-
-                                   posixpath
-Do not import this module directly, import os instead and refer to this module
-as os.path. (e.g. os.path.exists(p)) !
-
-                           Some posixpath functions
- Function                                 Result
-abspath(p) Returns absolute path for path p, taking current working dir in
-           account.
-dirname/
-basename(p directory and name parts of the path p. See also split.
-)
-exists(p)  True if string p is an existing path (file or directory)
-expanduser Returns string that is (a copy of) p with "~" expansion done.
-(p)
-expandvars Returns string that is (a copy of) p with environment vars expanded.
-(p)        [Windows: case significant; must use Unix: $var notation, not %var%]
-getsize(   return the size in bytes of filename. raise os.error.
-filename)
-getmtime(  return last modification time of filename (integer nb of seconds
-filename)  since epoch).
-getatime(  return last access time of filename (integer nb of seconds since
-filename)  epoch).
-isabs(p)   True if string p is an absolute path.
-isdir(p)   True if string p is a directory.
-islink(p)  True if string p is a symbolic link.
-ismount(p) True if string p is a mount point [true for all dirs on Windows].
-join(p[,q  Joins one or more path components intelligently.
-[,...]])
-           Splits p into (head, tail) where tail is lastpathname component and
-split(p)   <head> is everything leadingup to that. <=> (dirname(p), basename
-           (p))
-splitdrive Splits path p in a pair ('drive:', tail) [Windows]
-(p)
-splitext(p Splits into (root, ext) where last comp of root contains no periods
-)          and ext is empty or startswith a period.
-           Calls the function visit with arguments(arg, dirname, names) for
-           each directory recursively inthe directory tree rooted at p
-walk(p,    (including p itself if it's a dir)The argument dirname specifies the
-visit, arg visited directory, the argumentnames lists the files in the
-)          directory. The visit function maymodify names to influence the set
-           of directories visited belowdirname, e.g., to avoid visiting certain
-           parts of the tree.
-
-
-
-                                    shutil
-high-level file operations (copying, deleting).
-
-                             Main shutil functions
-     Function                                 Result
-copy(src, dst)     Copies the contents of file src to file dst, retaining file
-                   permissions.
-copytree(src, dst  Recursively copies an entire directory tree rooted at src
-[, symlinks])      into dst (which should not already exist). If symlinks is
-                   true, links insrc are kept as such in dst.
-rmtree(path[,      Deletes an entire directory tree, ignoring errors if
-ignore_errors[,    ignore_errors true,or calling onerror(func, path,
-onerror]])         sys.exc_info()) if supplied with
-
-(and also: copyfile, copymode, copystat, copy2)
-
-time
-
-                                  Variables
-Variable                               Meaning
-altzone  signed offset of local DST timezone in sec west of the 0th meridian.
-daylight nonzero if a DST timezone is specified
-
-                                   Functions
-  Function                                 Result
-time()        return a float representing UTC time in seconds since the epoch.
-gmtime(secs), return a tuple representing time : (year aaaa, month(1-12),day
-localtime(    (1-31), hour(0-23), minute(0-59), second(0-59), weekday(0-6, 0 is
-secs)         monday), Julian day(1-366), daylight flag(-1,0 or 1))
-asctime(
-timeTuple),
-strftime(
-format,       return a formatted string representing time.
-timeTuple)
-mktime(tuple) inverse of localtime(). Return a float.
-strptime(     parse a formatted string representing time, return tuple as in
-string[,      gmtime().
-format])
-sleep(secs)   Suspend execution for <secs> seconds. <secs> can be a float.
-
-and also: clock, ctime.
-
-                                    string
-
-As of Python 2.0, much (though not all) of the functionality provided by the
-string module have been superseded by built-in string methods - see Operations
-on strings for details.
-
-                             Some string variables
-              Variable                                Meaning
-digits                               The string '0123456789'
-hexdigits, octdigits                 legal hexadecimal & octal digits
-letters, uppercase, lowercase,       Strings containing the appropriate
-whitespace                           characters
-index_error                          Exception raised by index() if substr not
-                                     found.
-
-                             Some string functions
-     Function                                 Result
-expandtabs(s,      returns a copy of string <s> with tabs expanded.
-tabSize)
-find/rfind(s, sub  Return the lowest/highest index in <s> where the substring
-[, start=0[, end=  <sub> is found such that <sub> is wholly contained ins
-0])                [start:end]. Return -1 if <sub> not found.
-ljust/rjust/center Return a copy of string <s> left/right justified/centerd in
-(s, width)         afield of given width, padded with spaces. <s> is
-                   nevertruncated.
-lower/upper(s)     Return a string that is (a copy of) <s> in lowercase/
-                   uppercase
-split(s[, sep=     Return a list containing the words of the string <s>,using
-whitespace[,       the string <sep> as a separator.
-maxsplit=0]])
-join(words[, sep=' Concatenate a list or tuple of words with
-'])                interveningseparators; inverse of split.
-replace(s, old,    Returns a copy of string <s> with all occurrences of
-new[, maxsplit=0]  substring<old> replaced by <new>. Limits to <maxsplit>
-                   firstsubstitutions if specified.
-strip(s)           Return a string that is (a copy of) <s> without leadingand
-                   trailing whitespace. see also lstrip, rstrip.
-
-
-
-                                   re (sre)
-
-Handles Unicode strings. Implemented in new module sre, re now a mere front-end
-for compatibility.
-Patterns are specified as strings. Tip: Use raw strings (e.g. r'\w*') to
-litteralize backslashes.
-
-
-                           Regular expression syntax
-   Form                                Description
-.          matches any character (including newline if DOTALL flag specified)
-^          matches start of the string (of every line in MULTILINE mode)
-$          matches end of the string (of every line in MULTILINE mode)
-*          0 or more of preceding regular expression (as many as possible)
-+          1 or more of preceding regular expression (as many as possible)
-?          0 or 1 occurrence of preceding regular expression
-*?, +?, ?? Same as *, + and ? but matches as few characters as possible
-{m,n}      matches from m to n repetitions of preceding RE
-{m,n}?     idem, attempting to match as few repetitions as possible
-[ ]        defines character set: e.g. '[a-zA-Z]' to match all letters(see also
-           \w \S)
-[^ ]       defines complemented character set: matches if char is NOT in set
-           escapes special chars '*?+&$|()' and introduces special sequences
-\          (see below). Due to Python string rules, write as '\\' orr'\' in the
-           pattern string.
-\\         matches a litteral '\'; due to Python string rules, write as '\\\\
-           'in pattern string, or better using raw string: r'\\'.
-|          specifies alternative: 'foo|bar' matches 'foo' or 'bar'
-(...)      matches any RE inside (), and delimits a group.
-(?:...)    idem but doesn't delimit a group.
-           matches if ... matches next, but doesn't consume any of the string
-(?=...)    e.g. 'Isaac (?=Asimov)' matches 'Isaac' only if followed by
-           'Asimov'.
-(?!...)    matches if ... doesn't match next. Negative of (?=...)
-(?P<name   matches any RE inside (), and delimits a named group. (e.g. r'(?P
->...)      <id>[a-zA-Z_]\w*)' defines a group named id)
-(?P=name)  matches whatever text was matched by the earlier group named name.
-(?#...)    A comment; ignored.
-(?letter)  letter is one of 'i','L', 'm', 's', 'x'. Set the corresponding flags
-           (re.I, re.L, re.M, re.S, re.X) for the entire RE.
-
-                               Special sequences
-Sequence                              Description
-number   matches content of the group of the same number; groups are numbered
-         starting from 1
-\A       matches only at the start of the string
-\b       empty str at beg or end of word: '\bis\b' matches 'is', but not 'his'
-\B       empty str NOT at beginning or end of word
-\d       any decimal digit (<=> [0-9])
-\D       any non-decimal digit char (<=> [^O-9])
-\s       any whitespace char (<=> [ \t\n\r\f\v])
-\S       any non-whitespace char (<=> [^ \t\n\r\f\v])
-\w       any alphaNumeric char (depends on LOCALE flag)
-\W       any non-alphaNumeric char (depends on LOCALE flag)
-\Z       matches only at the end of the string
-
-                         Variables
-Variable                       Meaning
-error    Exception when pattern string isn't a valid regexp.
-
-                                   Functions
-   Function                                 Result
-               Compile a RE pattern string into a regular expression object.
-               Flags (combinable by |):
-
-               I or IGNORECASE or (?i)
-                   case insensitive matching
-compile(       L or LOCALE or (?L)
-pattern[,          make \w, \W, \b, \B dependent on thecurrent locale
-flags=0])      M or MULTILINE or (?m)
-                   matches every new line and not onlystart/end of the whole
-                   string
-               S or DOTALL or (?s)
-                   '.' matches ALL chars, including newline
-               X or VERBOSE or (?x)
-                   Ignores whitespace outside character sets
-escape(string) return (a copy of) string with all non-alphanumerics
-               backslashed.
-match(pattern, if 0 or more chars at beginning of <string> match the RE pattern
-string[, flags string,return a corresponding MatchObject instance, or None if
-])             no match.
-search(pattern scan thru <string> for a location matching <pattern>, return
-, string[,     acorresponding MatchObject instance, or None if no match.
-flags])
-split(pattern, split <string> by occurrences of <pattern>. If capturing () are
-string[,       used inpattern, then occurrences of patterns or subpatterns are
-maxsplit=0])   also returned.
-findall(       return a list of non-overlapping matches in <pattern>, either a
-pattern,       list ofgroups or a list of tuples if the pattern has more than 1
-string)        group.
-               return string obtained by replacing the (<count> first) lefmost
-sub(pattern,   non-overlapping occurrences of <pattern> (a string or a RE
-repl, string[, object) in <string>by <repl>; <repl> can be a string or a fct
-count=0])      called with a single MatchObj arg, which must return the
-               replacement string.
-subn(pattern,
-repl, string[, same as sub(), but returns a tuple (newString, numberOfSubsMade)
-count=0])
-
-Regular Expression Objects
-
-
-(RE objects are returned by the compile fct)
-
-                          re object attributes
-Attribute                            Descrition
-flags      flags arg used when RE obj was compiled, or 0 if none provided
-groupindex dictionary of {group name: group number} in pattern
-pattern    pattern string from which RE obj was compiled
-
-                               re object methods
-  Method                                  Result
-            If zero or more characters at the beginning of string match this
-            regular expression, return a corresponding MatchObject instance.
-            Return None if the string does not match the pattern; note that
-            this is different from a zero-length match.
-            The optional second parameter pos gives an index in the string
-match(      where the search is to start; it defaults to 0. This is not
-string[,    completely equivalent to slicing the string; the '' pattern
-pos][,      character matches at the real beginning of the string and at
-endpos])    positions just after a newline, but not necessarily at the index
-            where the search is to start.
-            The optional parameter endpos limits how far the string will be
-            searched; it will be as if the string is endpos characters long, so
-            only the characters from pos to endpos will be searched for a
-            match.
-            Scan through string looking for a location where this regular
-search(     expression produces a match, and return a corresponding MatchObject
-string[,    instance. Return None if no position in the string matches the
-pos][,      pattern; note that this is different from finding a zero-length
-endpos])    match at some point in the string.
-            The optional pos and endpos parameters have the same meaning as for
-            the match() method.
-split(
-string[,    Identical to the split() function, using the compiled pattern.
-maxsplit=
-0])
-findall(    Identical to the findall() function, using the compiled pattern.
-string)
-sub(repl,
-string[,    Identical to the sub() function, using the compiled pattern.
-count=0])
-subn(repl,
-string[,    Identical to the subn() function, using the compiled pattern.
-count=0])
-
-Match Objects
-
-
-(Match objects are returned by the match & search functions)
-
-                            Match object attributes
-Attribute                              Description
-pos       value of pos passed to search or match functions; index intostring at
-          which RE engine started search.
-endpos    value of endpos passed to search or match functions; index intostring
-          beyond which RE engine won't go.
-re        RE object whose match or search fct produced this MatchObj instance
-string    string passed to match() or search()
-
-                            Match object functions
-Function                                 Result
-          returns one or more groups of the match. If one arg, result is a
-group([g1 string;if multiple args, result is a tuple with one item per arg. If
-, g2,     gi is 0,return value is entire matching string; if 1 <= gi <= 99,
-...])     returnstring matching group #gi (or None if no such group); gi may
-          also bea group name.
-          returns a tuple of all groups of the match; groups not
-groups()  participatingto the match have a value of None. Returns a string
-          instead of tupleif len(tuple)=1
-start(
-group),   returns indices of start & end of substring matched by group (or
-end(group Noneif group exists but doesn't contribute to the match)
-)
-span(     returns the 2-tuple (start(group), end(group)); can be (None, None)if
-group)    group didn't contibute to the match.
-
-
-
-                                     math
-
-Variables:
-pi
-e
-Functions (see ordinary C man pages for info):
-acos(x)
-asin(x)
-atan(x)
-atan2(x, y)
-ceil(x)
-cos(x)
-cosh(x)
-degrees(x)
-exp(x)
-fabs(x)
-floor(x)
-fmod(x, y)
-frexp(x)        -- Unlike C: (float, int) = frexp(float)
-ldexp(x, y)
-log(x [,base])
-log10(x)
-modf(x)         -- Unlike C: (float, float) = modf(float)
-pow(x, y)
-radians(x)
-sin(x)
-sinh(x)
-sqrt(x)
-tan(x)
-tanh(x)
-
-                                    getopt
-
-Functions:
-getopt(list, optstr)    -- Similar to C. <optstr> is option
-                           letters to look for. Put ':' after letter
-                           if option takes arg. E.g.
-    # invocation was "python test.py -c hi -a arg1 arg2"
-       opts, args =  getopt.getopt(sys.argv[1:], 'ab:c:')
-    # opts would be
-       [('-c', 'hi'), ('-a', '')]
-    # args would be
-       ['arg1', 'arg2']
-
-
-List of modules and packages in base distribution
-
-(built-ins and content of python Lib directory)
-(Python NT distribution, may be slightly different in other distributions)
-
-                           Standard library modules
-   Operation                                 Result
-aifc             Stuff to parse AIFF-C and AIFF files.
-asynchat         Support for 'chat' style protocols
-asyncore         Asynchronous File I/O (in select style)
-atexit           Register functions to be called at exit of Python interpreter.
-base64           Conversions to/from base64 RFC-MIME transport encoding .
-bdb              A generic Python debugger base class.
-binhex           Macintosh binhex compression/decompression.
-bisect           List bisection algorithms.
-bz2              Support for bz2 compression/decompression.
-calendar         Calendar printing functions.
-cgi              Wraps the WWW Forms Common Gateway Interface (CGI).
-cgitb            Utility for handling CGI tracebacks.
-cmd              A generic class to build line-oriented command interpreters.
-datetime         Basic date and time types.
-code             Utilities needed to emulate Python's interactive interpreter
-codecs           Lookup existing Unicode encodings and register new ones.
-colorsys         Conversion functions between RGB and other color systems.
-compileall       Force "compilation" of all .py files in a directory.
-configparser     Configuration file parser (much like windows .ini files)
-copy             Generic shallow and deep copying operations.
-copyreg          Helper to provide extensibility for pickle/cPickle.
-csv              Read and write files with comma separated values.
-dbm              Generic interface to all dbm clones (dbm.bsd, dbm.gnu,
-                 dbm.ndbm, dbm.dumb).
-dircache         Sorted list of files in a dir, using a cache.
-difflib          Tool for creating delta between sequences.
-dis              Bytecode disassembler.
-distutils        Package installation system.
-doctest          Tool for running and verifying tests inside doc strings.
-dospath          Common operations on DOS pathnames.
-email            Comprehensive support for internet email.
-filecmp          File comparison.
-fileinput        Helper class to quickly write a loop over all standard input
-                 files.
-fnmatch          Filename matching with shell patterns.
-formatter        A test formatter.
-fpformat         General floating point formatting functions.
-ftplib           An FTP client class. Based on RFC 959.
-gc               Perform garbacge collection, obtain GC debug stats, and tune
-                 GC parameters.
-getopt           Standard command line processing. See also ftp://
-                 www.pauahtun.org/pub/getargspy.zip
-getpass          Utilities to get a password and/or the current user name.
-glob             filename globbing.
-gzip             Read & write gzipped files.
-heapq            Priority queue implemented using lists organized as heaps.
-hmac             Keyed-Hashing for Message Authentication -- RFC 2104.
-html.entities    HTML entity definitions.
-html.parser      A parser for HTML and XHTML.
-http.client      HTTP client class.
-http.server      HTTP server services.
-ihooks           Hooks into the "import" mechanism.
-imaplib          IMAP4 client.Based on RFC 2060.
-imghdr           Recognizing image files based on their first few bytes.
-imputil          Privides a way of writing customised import hooks.
-inspect          Tool for probing live Python objects.
-keyword          List of Python keywords.
-linecache        Cache lines from files.
-locale           Support for number formatting using the current locale
-                 settings.
-logging          Python logging facility.
-macpath          Pathname (or related) operations for the Macintosh.
-macurl2path      Mac specific module for conversion between pathnames and URLs.
-mailbox          A class to handle a unix-style or mmdf-style mailbox.
-mailcap          Mailcap file handling (RFC 1524).
-mhlib            MH (mailbox) interface.
-mimetypes        Guess the MIME type of a file.
-mmap             Interface to memory-mapped files - they behave like mutable
-                 strings./font>
-multifile        Class to make multi-file messages easier to handle.
-mutex            Mutual exclusion -- for use with module sched.
-netrc
-nntplib          An NNTP client class. Based on RFC 977.
-ntpath           Common operations on DOS pathnames.
-nturl2path       Mac specific module for conversion between pathnames and URLs.
-optparse         A comprehensive tool for processing command line options.
-os               Either mac, dos or posix depending system.
-pdb              A Python debugger.
-pickle           Pickling (save and restore) of Python objects (a faster
-                 Cimplementation exists in built-in module: cPickle).
-pipes            Conversion pipeline templates.
-pkgunil          Utilities for working with Python packages.
-poplib           A POP3 client class. Based on the J. Myers POP3 draft.
-posixpath        Common operations on POSIX pathnames.
-pprint           Support to pretty-print lists, tuples, & dictionaries
-                 recursively.
-profile          Class for profiling python code.
-pstats           Class for printing reports on profiled python code.
-pydoc            Utility for generating documentation from source files.
-pty              Pseudo terminal utilities.
-pyexpat          Interface to the Expay XML parser.
-py_compile       Routine to "compile" a .py file to a .pyc file.
-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.
-random           Random variable generators
-re               Regular Expressions.
-reprlib          Redo repr() but with limits on most sizes.
-rlcompleter      Word completion for GNU readline 2.0.
-sched            A generally useful event scheduler class.
-shelve           Manage shelves of pickled objects.
-shlex            Lexical analyzer class for simple shell-like syntaxes.
-shutil           Utility functions usable in a shell-like program.
-site             Append module search paths for third-party packages to
-                 sys.path.
-smtplib          SMTP Client class (RFC 821)
-sndhdr           Several routines that help recognizing sound.
-socketserver     Generic socket server classes.
-stat             Constants and functions for interpreting stat/lstat struct.
-statvfs          Constants for interpreting statvfs struct as returned by
-                 os.statvfs()and os.fstatvfs() (if they exist).
-string           A collection of string operations.
-sunau            Stuff to parse Sun and NeXT audio files.
-sunaudio         Interpret sun audio headers.
-symbol           Non-terminal symbols of Python grammar (from "graminit.h").
-tabnanny         Check Python source for ambiguous indentation.
-tarfile          Facility for reading and writing to the *nix tarfile format.
-telnetlib        TELNET client class. Based on RFC 854.
-tempfile         Temporary file name allocation.
-textwrap         Object for wrapping and filling text.
-threading        Proposed new higher-level threading interfaces
-token            Tokens (from "token.h").
-tokenize         Compiles a regular expression that recognizes Python tokens.
-traceback        Format and print Python stack traces.
-tty              Terminal utilities.
-turtle           LogoMation-like turtle graphics
-types            Define names for all type symbols in the std interpreter.
-tzparse          Parse a timezone specification.
-unicodedata      Interface to unicode properties.
-urllib.parse     Parse URLs according to latest draft of standard.
-urllib.request   Open an arbitrary URL.
-urllib.robotparser  Parse robots.txt files, useful for web spiders.
-user             Hook to allow user-specified customization code to run.
-uu               UUencode/UUdecode.
-unittest         Utilities for implementing unit testing.
-wave             Stuff to parse WAVE files.
-weakref          Tools for creating and managing weakly referenced objects.
-webbrowser       Platform independent URL launcher.
-xdrlib           Implements (a subset of) Sun XDR (eXternal Data
-                 Representation).
-xml.dom          Classes for processing XML using the Document Object Model.
-xml.sax          Classes for processing XML using the SAX API.
-xmlrpc.client    Support for remote procedure calls using XML.
-xmlrpc.server    Create XMLRPC servers.
-zipfile          Read & write PK zipped files.
-
-
-
-* Built-ins *
-
-            sys                 Interpreter state vars and functions
-            __built-in__        Access to all built-in python identifiers
-            __main__            Scope of the interpreters main program, script or stdin
-            array               Obj efficiently representing arrays of basic values
-            math                Math functions of C standard
-            time                Time-related functions (also the newer datetime module)
-            marshal             Read and write some python values in binary format
-            struct              Convert between python values and C structs
-
-* Standard *
-
-            getopt              Parse cmd line args in sys.argv.  A la UNIX 'getopt'.
-            os                  A more portable interface to OS dependent functionality
-            re                  Functions useful for working with regular expressions
-            string              Useful string and characters functions and exceptions
-            random              Mersenne Twister pseudo-random number generator
-            _thread             Low-level primitives for working with process threads
-            threading           idem, new recommended interface.
-
-* Unix/Posix *
-
-            dbm                 Interface to Unix dbm databases
-            grp                 Interface to Unix group database
-            posix               OS functionality standardized by C and POSIX standards
-            posixpath           POSIX pathname functions
-            pwd                 Access to the Unix password database
-            select              Access to Unix select multiplex file synchronization
-            socket              Access to BSD socket interface
-
-* Tk User-interface Toolkit *
-
-            tkinter             Main interface to Tk
-
-* Multimedia *
-
-            audioop             Useful operations on sound fragments
-            imageop             Useful operations on images
-            jpeg                Access to jpeg image compressor and decompressor
-            rgbimg              Access SGI imglib image files
-
-* Cryptographic Extensions *
-
-            md5         Interface to RSA's MD5 message digest algorithm
-            sha         Interface to the SHA message digest algorithm
-            HMAC        Keyed-Hashing for Message Authentication -- RFC 2104.
-
-* SGI IRIX * (4 & 5)
-
-            al          SGI audio facilities
-            AL          al constants
-            fl          Interface to FORMS library
-            FL          fl constants
-            flp Functions for form designer
-            fm          Access to font manager library
-            gl          Access to graphics library
-            GL          Constants for gl
-            DEVICE      More constants for gl
-            imgfile     Imglib image file interface
-
-
-Workspace exploration and idiom hints
-
-        dir(<module>)   list functions, variables in <module>
-        dir()           get object keys, defaults to local name space
-        if __name__ == '__main__': main()            invoke main if running as script
-        map(None, lst1, lst2, ...)                   merge lists
-        b = a[:]                                     create copy of seq structure
-        _                       in interactive mode, is last value printed
-
-
-
-
-
-
-
-Python Mode for Emacs
-
-(Not revised, possibly not up to date)
-Type C-c ? when in python-mode for extensive help.
-INDENTATION
-Primarily for entering new code:
-        TAB      indent line appropriately
-        LFD      insert newline, then indent
-        DEL      reduce indentation, or delete single character
-Primarily for reindenting existing code:
-        C-c :    guess py-indent-offset from file content; change locally
-        C-u C-c :        ditto, but change globally
-        C-c TAB  reindent region to match its context
-        C-c <    shift region left by py-indent-offset
-        C-c >    shift region right by py-indent-offset
-MARKING & MANIPULATING REGIONS OF CODE
-C-c C-b         mark block of lines
-M-C-h           mark smallest enclosing def
-C-u M-C-h       mark smallest enclosing class
-C-c #           comment out region of code
-C-u C-c #       uncomment region of code
-MOVING POINT
-C-c C-p         move to statement preceding point
-C-c C-n         move to statement following point
-C-c C-u         move up to start of current block
-M-C-a           move to start of def
-C-u M-C-a       move to start of class
-M-C-e           move to end of def
-C-u M-C-e       move to end of class
-EXECUTING PYTHON CODE
-C-c C-c sends the entire buffer to the Python interpreter
-C-c |   sends the current region
-C-c !   starts a Python interpreter window; this will be used by
-        subsequent C-c C-c or C-c | commands
-C-c C-w runs PyChecker
-
-VARIABLES
-py-indent-offset        indentation increment
-py-block-comment-prefix comment string used by py-comment-region
-py-python-command       shell command to invoke Python interpreter
-py-scroll-process-buffer        t means always scroll Python process buffer
-py-temp-directory       directory used for temp files (if needed)
-py-beep-if-tab-change   ring the bell if tab-width is changed
-
-
-The Python Debugger
-
-(Not revised, possibly not up to date, see 1.5.2 Library Ref section 9.1; in 1.5.2, you may also use debugger integrated in IDLE)
-
-Accessing
-
-import pdb      (it's a module written in Python)
-        -- defines functions :
-           run(statement[,globals[, locals]])
-                        -- execute statement string under debugger control, with optional
-                           global & local environment.
-           runeval(expression[,globals[, locals]])
-                        -- same as run, but evaluate expression and return value.
-           runcall(function[, argument, ...])
-                        -- run function object with given arg(s)
-           pm()         -- run postmortem on last exception (like debugging a core file)
-           post_mortem(t)
-                        -- run postmortem on traceback object <t>
-
-        -- defines class Pdb :
-           use Pdb to create reusable debugger objects. Object
-           preserves state (i.e. break points) between calls.
-
-        runs until a breakpoint hit, exception, or end of program
-        If exception, variable '__exception__' holds (exception,value).
-
-Commands
-
-h, help
-        brief reminder of commands
-b, break [<arg>]
-        if <arg> numeric, break at line <arg> in current file
-        if <arg> is function object, break on entry to fcn <arg>
-        if no arg, list breakpoints
-cl, clear [<arg>]
-        if <arg> numeric, clear breakpoint at <arg> in current file
-        if no arg, clear all breakpoints after confirmation
-w, where
-        print current call stack
-u, up
-        move up one stack frame (to top-level caller)
-d, down
-        move down one stack frame
-s, step
-        advance one line in the program, stepping into calls
-n, next
-        advance one line, stepping over calls
-r, return
-        continue execution until current function returns
-        (return value is saved in variable "__return__", which
-        can be printed or manipulated from debugger)
-c, continue
-        continue until next breakpoint
-j, jump lineno
-        Set the next line that will be executed
-a, args
-        print args to current function
-rv, retval
-        prints return value from last function that returned
-p, print <arg>
-        prints value of <arg> in current stack frame
-l, list [<first> [, <last>]]
-               List source code for the current file.
-               Without arguments, list 11 lines around the current line
-               or continue the previous listing.
-               With one argument, list 11 lines starting at that line.
-               With two arguments, list the given range;
-               if the second argument is less than the first, it is a count.
-whatis <arg>
-        prints type of <arg>
-!
-        executes rest of line as a Python statement in the current stack frame
-q quit
-        immediately stop execution and leave debugger
-<return>
-        executes last command again
-Any input debugger doesn't recognize as a command is assumed to be a
-Python statement to execute in the current stack frame, the same way
-the exclamation mark ("!") command does.
-
-Example
-
-(1394) python
-Python 1.0.3 (Sep 26 1994)
-Copyright 1991-1994 Stichting Mathematisch Centrum, Amsterdam
->>> import rm
->>> rm.run()
-Traceback (innermost last):
-         File "<stdin>", line 1
-         File "./rm.py", line 7
-           x = div(3)
-         File "./rm.py", line 2
-           return a / r
-ZeroDivisionError: integer division or modulo
->>> import pdb
->>> pdb.pm()
-> ./rm.py(2)div: return a / r
-(Pdb) list
-         1     def div(a):
-         2  ->     return a / r
-         3
-         4     def run():
-         5         global r
-         6         r = 0
-         7         x = div(3)
-         8         print x
-[EOF]
-(Pdb) print r
-0
-(Pdb) q
->>> pdb.runcall(rm.run)
-etc.
-
-Quirks
-
-Breakpoints are stored as filename, line number tuples. If a module is reloaded
-after editing, any remembered breakpoints are likely to be wrong.
-
-Always single-steps through top-most stack frame. That is, "c" acts like "n".

Deleted: python/branches/pep-3151/Misc/developers.txt
==============================================================================
--- python/branches/pep-3151/Misc/developers.txt	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,346 +0,0 @@
-Developer Log
-=============
-
-This file is a running log of developers given permissions on SourceForge.
-
-The purpose is to provide some institutional memory of who was given access
-and why.
-
-The first entry starts in April 2005.  In keeping with the style of
-Misc/NEWS, newer entries should be added to the top.  Any markup should
-be in the form of ReST.  Entries should include the initials of the
-project admin who made the change or granted access.  Feel free to revise
-the format to accommodate documentation needs as they arise.
-
-Note, when giving new commit permissions, be sure to get a contributor
-agreement from the committer.  See http://www.python.org/psf/contrib/
-for details.  When the agreement is signed, please note it in this log.
-
-This file is encoded in UTF-8.  If the usual form for a name is not in
-a Latin or extended Latin alphabet, make sure to include an ASCII
-transliteration too.
-
-Permissions History
--------------------
-
-- David Malcolm was given commit access on Oct 27 2010 by GFB,
-  at recommendation by Antoine Pitrou and Raymond Hettinger.
-
-- Tal Einat was given commit access on Oct 4 2010 by MvL,
-  for improving IDLE.
-
-- Łukasz Langa was given commit access on Sep 08 2010 by GFB,
-  at suggestion of Antoine Pitrou, for general bug fixing.
-
-- Daniel Stutzbach was given commit access on Aug 22 2010 by MvL,
-  for general bug fixing.
-
-- Ask Solem was given commit access on Aug 17 2010 by MvL,
-  on recommendation by Jesse Noller, for work on the multiprocessing
-  library.
-
-- George Boutsioukis was given commit access on Aug 10 2010
-  by MvL, for work on 2to3.
-
-- Éric Araujo was given commit access on Aug 10 2010 by BAC,
-  at suggestion of Tarek Ziadé.
-
-- Terry Reedy was given commit access on Aug 04 2010 by MvL,
-  at suggestion of Nick Coghlan.
-
-- Brian Quinlan was given commit access on Jul 26 2010 by GFB,
-  for work related to PEP 3148.
-
-- Reid Kleckner was given commit access on Jul 11 2010 by GFB,
-  for work on the py3k-jit branch, at suggestion of the Unladen
-  Swallow team.
-
-- Alexander Belopolsky was given commit access on May 25 2010
-  by MvL at suggestion of Mark Dickinson.
-
-- Tim Golden was given commit access on April 21 2010 by MvL,
-  at suggestion of Michael Foord.
-
-- Giampaolo Rodolà was given commit access on April 17 2010 by
-  MvL, at suggestion of R. David Murray.
-
-- Jean-Paul Calderone was given commit access on April 6 2010 by
-  GFB, at suggestion of Michael Foord and others.
-
-- Brian Curtin was given commit access on March 24 2010 by MvL.
-
-- Florent Xicluna was given commit access on February 25 2010 by
-  MvL, based on Antoine Pitrou's recommendation.
-
-- Dino Viehland was given SVN access on February 23 2010 by Brett
-  Cannon, for backporting tests from IronPython.
-
-- Larry Hastings was given SVN access on February 22 2010 by
-  Andrew Kuchling, based on Brett Cannon's recommendation.
-
-- Victor Stinner was given SVN access on January 30 2010 by MvL,
-  at recommendation by Mark Dickinson and Amaury Forgeot d'Arc.
-
-- Stefan Krah was given SVN access on January 5 2010 by GFB, at
-  suggestion of Mark Dickinson, for work on the decimal module.
-
-- Doug Hellmann was given SVN access on September 19 2009 by GFB, at
-  suggestion of Jesse Noller, for documentation work.
-
-- Ezio Melotti was given SVN access on June 7 2009 by GFB, for work on and
-  fixes to the documentation.
-
-- Paul Kippes was given commit privileges at PyCon 2009 by BAC to work on 3to2.
-
-- Ron DuPlain was given commit privileges at PyCon 2009 by BAC to work on 3to2.
-
-- Several developers of alternative Python implementations where
-  given access for test suite and library adaptions by MvL:
-  Allison Randal (Parrot), Michael Foord (IronPython),
-  Jim Baker, Philip Jenvey, and Frank Wierzbicki (all Jython).
-
-- R. David Murray was given SVN access on March 30 2009 by MvL, after
-  recommendation by BAC.
-
-- Chris Withers was given SVN access on March 8 2009 by MvL,
-  after recommendation by GvR.
-
-- Tarek Ziadé was given SVN access on December 21 2008 by NCN,
-  for maintenance of distutils.
-
-- Hirokazu Yamamoto was given SVN access on August 12 2008 by MvL,
-  for contributions to the Windows build.
-
-- Antoine Pitrou was given SVN access on July 16 2008, by recommendation
-  from GvR, for general contributions to Python.
-
-- Jesse Noller was given SVN access on 16 June 2008 by GFB,
-  for work on the multiprocessing module.
-
-- Gregor Lingl was given SVN access on 10 June 2008 by MvL,
-  for work on the turtle module.
-
-- Robert Schuppenies was given SVN access on 21 May 2008 by MvL,
-  for GSoC contributions.
-
-- Rodrigo Bernardo Pimentel was given SVN access on 29 April 2008 by MvL,
-  for GSoC contributions.
-
-- Heiko Weinen was given SVN access on 29 April 2008 by MvL,
-  for GSoC contributions.
-
-- Jesus Cea was given SVN access on 24 April 2008 by MvL,
-  for maintenance of bsddb.
-
-- Guilherme Polo was given SVN access on 24 April 2008 by MvL,
-  for GSoC contributions.
-
-- Thomas Lee was given SVN access on 21 April 2008 by NCN,
-  for work on branches (ast/optimizer related).
-
-- Jeroen Ruigrok van der Werven was given SVN access on 12 April 2008
-  by GFB, for documentation work.
-
-- Josiah Carlson was given SVN access on 26 March 2008 by GFB,
-  for work on asyncore/asynchat.
-
-- Benjamin Peterson was given SVN access on 25 March 2008 by GFB,
-  for bug triage work.
-
-- Jerry Seutter was given SVN access on 20 March 2008 by BAC, for
-  general contributions to Python.
-
-- Jeff Rush was given SVN access on 18 March 2008 by AMK, for Distutils work.
-
-- David Wolever was given SVN access on 17 March 2008 by MvL,
-  for 2to3 work.
-
-- Trent Nelson was given SVN access on 17 March 2008 by MvL,
-  for general contributions to Python.
-
-- Mark Dickinson was given SVN access on 6 January 2008 by Facundo
-  Batista for his work on mathemathics and number related issues.
-
-- Amaury Forgeot d'Arc was given SVN access on 9 November 2007 by MvL,
-  for general contributions to Python.
-
-- Christian Heimes was given SVN access on 31 October 2007 by MvL,
-  for general contributions to Python.
-
-- Chris Monson was given SVN access on 20 October 2007 by NCN,
-  for his work on editing PEPs.
-
-- Bill Janssen was given SVN access on 28 August 2007 by NCN,
-  for his work on the SSL module and other things related to (SSL) sockets.
-
-- Jeffrey Yasskin was given SVN access on 9 August 2007 by NCN,
-  for his work on PEPs and other general patches.
-
-- Mark Summerfield was given SVN access on 1 August 2007 by GFB,
-  for work on documentation.
-
-- Armin Ronacher was given SVN access on 23 July 2007 by GFB,
-  for work on the documentation toolset.  He now maintains the
-  ast module.
-
-- Senthil Kumaran was given SVN access on 16 June 2007 by MvL,
-  for his Summer-of-Code project, mentored by Skip Montanaro.
-
-- Alexandre Vassalotti was given SVN access on 21 May 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.
-
-- Collin Winter was given SVN access on 05 Jan 2007 by NCN, for PEP
-  update access.
-
-- Lars Gustaebel was given SVN access on 20 Dec 2006 by NCN, for tarfile.py
-  related work.
-
-- 2006 Summer of Code entries: SoC developers are expected to work
-  primarily in nondist/sandbox or on a branch of their own, and will
-  have their work reviewed before changes are accepted into the trunk.
-
-  - Matt Fleming was added on 25 May 2006 by AMK; he'll be working on
-    enhancing the Python debugger.
-
-  - Jackilyn Hoxworth was added on 25 May 2006 by AMK; she'll be adding logging
-    to the standard library.
-
-  - Mateusz Rukowicz was added on 30 May 2006 by AMK; he'll be
-    translating the decimal module into C.
-
-- SVN access granted to the "Need for Speed" Iceland sprint attendees,
-  between May 17 and 21, 2006, by Tim Peters.  All work is to be done
-  in new sandbox projects or on new branches, with merging to the
-  trunk as approved:
-
-  Andrew Dalke
-  Christian Tismer
-  Jack Diederich
-  John Benediktsson
-  Kristján V. Jónsson
-  Martin Blais
-  Richard Emslie
-  Richard Jones
-  Runar Petursson
-  Steve Holden
-  Richard M. Tew
-
-- Steven Bethard was given SVN access on 27 Apr 2006 by DJG, for PEP
-  update access.
-
-- Talin was given SVN access on 27 Apr 2006 by DJG, for PEP update
-  access.
-
-- George Yoshida (SF name "quiver") added to the SourceForge Python
-  project 14 Apr 2006, by Tim Peters, as a tracker admin.  See
-  contemporaneous python-checkins thread with the unlikely Subject:
-
-      r45329 - python/trunk/Doc/whatsnew/whatsnew25.tex
-
-- Ronald Oussoren was given SVN access on 3 Mar 2006 by NCN, for Mac
-  related work.
-
-- Bob Ippolito was given SVN access on 2 Mar 2006 by NCN, for Mac
-  related work.
-
-- Nick Coghlan requested CVS access so he could update his PEP directly.
-  Granted by GvR on 16 Oct 2005.
-
-- Added two new developers for the Summer of Code project. 8 July 2005
-  by RDH.  Andrew Kuchling will be mentoring Gregory K Johnson for a
-  project to enhance mailbox.  Brett Cannon requested access for Flovis
-  Bruynooghe (sirolf) to work on pstats, profile, and hotshot.  Both users
-  are expected to work primarily in nondist/sandbox and have their work
-  reviewed before making updates to active code.
-
-- Georg Brandl was given SF tracker permissions on 28 May 2005
-  by RDH.  Since the beginning of 2005, he has been active in discussions
-  on python-dev and has submitted a dozen patch reviews.  The permissions
-  add the ability to change tracker status and to attach patches.  On
-  3 June 2005, this was expanded by RDH to include checkin permissions.
-
-- Terry Reedy was given SF tracker permissions on 7 Apr 2005 by RDH.
-
-- Nick Coghlan was given SF tracker permissions on 5 Apr 2005 by RDH.
-  For several months, he has been active in reviewing and contributing
-  patches.  The added permissions give him greater flexibility in
-  working with the tracker.
-
-- Eric Price was made a developer on 2 May 2003 by TGP.  This was
-  specifically to work on the new ``decimal`` package, which lived in
-  ``nondist/sandbox/decimal/`` at the time.
-
-- Eric S. Raymond was made a developer on 2 Jul 2000 by TGP, for general
-  library work.  His request is archived here:
-
-      http://mail.python.org/pipermail/python-dev/2000-July/005314.html
-
-
-Permissions Dropped on Request
-------------------------------
-
-- Roy Smith, Matt Fleming and Richard Emslie sent drop requests.
-  4 Aug 2008 GFB
-
-- Per note from Andrew Kuchling, the permissions for Gregory K Johnson
-  and the Summer Of Code project are no longer needed.  4 Aug 2008 GFB
-
-- Per note from Andrew Kuchling, the permissions for Gregory K Johnson
-  and the Summer Of Code project are no longer needed.  AMK will make
-  any future checkins directly.  16 Oct 2005 RDH
-
-- Johannes Gijsbers sent a drop request.  27 July 2005 RDH
-
-- Flovis Bruynooghe sent a drop request.  14 July 2005 RDH
-
-- Paul Prescod sent a drop request.  30 Apr 2005 RDH
-
-- Finn Bock sent a drop request.  13 Apr 2005 RDH
-
-- Eric Price sent a drop request.  10 Apr 2005 RDH
-
-- Irmen de Jong requested dropping CVS access while keeping tracker
-  access.  10 Apr 2005 RDH
-
-- Moshe Zadka and Ken Manheimer sent drop requests.  8 Apr 2005 by RDH
-
-- Steve Holden, Gerhard Haring, and David Cole sent email stating that
-  they no longer use their access.   7 Apr 2005 RDH
-
-
-Permissions Dropped after Loss of Contact
------------------------------------------
-
-- Several unsuccessful efforts were made to contact Charles G Waldman.
-  Removed on 8 Apr 2005 by RDH.
-
-
-Initials of Project Admins
---------------------------
-
-TGP:  Tim Peters
-GFB:  Georg Brandl
-BAC:  Brett Cannon
-NCN:  Neal Norwitz
-DJG:  David Goodger
-MvL:  Martin v. Loewis
-GvR:  Guido van Rossum
-RDH:  Raymond Hettinger

Modified: python/branches/pep-3151/Misc/indent.pro
==============================================================================
--- python/branches/pep-3151/Misc/indent.pro	(original)
+++ python/branches/pep-3151/Misc/indent.pro	Sat Feb 26 08:16:32 2011
@@ -1,15 +1,24 @@
--sob
--nbad
--bap
--br
--nce
--ncs
--npcs
--i8
--ip8
--c25
+--blank-lines-after-declarations
+--blank-lines-after-procedures
+--braces-after-func-def-line
+--braces-on-if-line
+--braces-on-struct-decl-line
+--break-after-boolean-operator
+--comment-indentation25
+--comment-line-length79
+--continue-at-parentheses
+--dont-cuddle-do-while
+--dont-cuddle-else
+--indent-level4
+--line-length79
+--no-space-after-casts
+--no-space-after-function-call-names
+--no-space-after-parentheses
+--no-tabs
+--procnames-start-lines
+--space-after-for
+--space-after-if
+--space-after-while
+--swallow-optional-blank-lines
+-T PyCFunction
 -T PyObject
-
-
-
-

Deleted: python/branches/pep-3151/Misc/maintainers.rst
==============================================================================
--- python/branches/pep-3151/Misc/maintainers.rst	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,309 +0,0 @@
-Maintainers Index
-=================
-
-This document has tables that list Python Modules, Tools, Platforms and
-Interest Areas and names for each item that indicate a maintainer or an
-expert in the field.  This list is intended to be used by issue submitters,
-issue triage people, and other issue participants to find people to add to
-the nosy list or to contact directly by email for help and decisions on
-feature requests and bug fixes.  People on this list may be asked to render
-final judgement on a feature or bug.  If no active maintainer is listed for
-a given module, then questionable changes should go to python-dev, while
-any other issues can and should be decided by any committer.
-
-Unless a name is followed by a '*', you should never assign an issue to
-that person, only make them nosy.  Names followed by a '*' may be assigned
-issues involving the module or topic for which the name has a '*'.
-
-The Platform and Interest Area tables list broader fields in which various
-people have expertise.  These people can also be contacted for help,
-opinions, and decisions when issues involve their areas.
-
-If a listed maintainer does not respond to requests for comment for an
-extended period (three weeks or more), they should be marked as inactive
-in this list by placing the word 'inactive' in parenthesis behind their
-tracker id.  They are of course free to remove that inactive mark at
-any time.
-
-Committers should update these tables as their areas of expertise widen.
-New topics may be added to the Interest Area table at will.
-
-The existence of this list is not meant to indicate that these people
-*must* be contacted for decisions; it is, rather, a resource to be used
-by non-committers to find responsible parties, and by committers who do
-not feel qualified to make a decision in a particular context.
-
-See also `PEP 291`_ and `PEP 360`_ for information about certain modules
-with special rules.
-
-.. _`PEP 291`: http://www.python.org/dev/peps/pep-0291/
-.. _`PEP 360`: http://www.python.org/dev/peps/pep-0360/
-
-
-==================  ===========
-Module              Maintainers
-==================  ===========
-__future__
-__main__            gvanrossum
-_dummy_thread       brett.cannon
-_thread             pitrou
-abc
-aifc                r.david.murray
-argparse            bethard
-array
-ast
-asynchat            josiahcarlson, giampaolo.rodola, stutzbach
-asyncore            josiahcarlson, giampaolo.rodola, stutzbach
-atexit
-audioop
-base64
-bdb
-binascii
-binhex
-bisect              rhettinger
-builtins
-bz2
-calendar
-cgi
-cgitb
-chunk
-cmath               mark.dickinson
-cmd
-code
-codecs              lemburg, doerwalter
-codeop
-collections         rhettinger, stutzbach
-colorsys
-compileall
-concurrent.futures  brian.quinlan
-configparser        lukasz.langa
-contextlib
-copy                alexandre.vassalotti
-copyreg             alexandre.vassalotti
-cProfile
-crypt
-csv
-ctypes              theller
-curses              akuchling
-datetime            alexander.belopolsky
-dbm
-decimal             facundobatista, rhettinger, mark.dickinson
-difflib             tim_one
-dis
-distutils           tarek*, eric.araujo*
-doctest             tim_one (inactive)
-dummy_threading     brett.cannon
-email               barry, r.david.murray*
-encodings           lemburg, loewis
-errno
-exceptions
-fcntl
-filecmp
-fileinput
-fnmatch
-formatter
-fpectl
-fractions           mark.dickinson, rhettinger
-ftplib              giampaolo.rodola
-functools
-gc                  pitrou
-getopt
-getpass
-gettext             loewis
-glob
-grp
-gzip
-hashlib
-heapq               rhettinger, stutzbach
-hmac
-html
-http
-idlelib             kbk
-imaplib
-imghdr
-imp
-importlib           brett.cannon
-inspect
-io                  pitrou, benjamin.peterson, stutzbach
-itertools           rhettinger
-json                bob.ippolito (inactive)
-keyword
-lib2to3             benjamin.peterson
-linecache
-locale              loewis, lemburg
-logging             vinay.sajip
-macpath
-mailbox             akuchling
-mailcap
-marshal
-math                mark.dickinson, rhettinger, stutzbach
-mimetypes
-mmap
-modulefinder        theller, jvr
-msilib              loewis
-msvcrt
-multiprocessing     jnoller
-netrc
-nis
-nntplib
-numbers
-operator
-optparse            aronacher
-os                  loewis
-ossaudiodev
-parser
-pdb                 georg.brandl*
-pickle              alexandre.vassalotti, pitrou
-pickletools         alexandre.vassalotti
-pipes
-pkgutil
-platform            lemburg
-plistlib
-poplib
-posix
-pprint              fdrake
-profile             georg.brandl
-pstats              georg.brandl
-pty
-pwd
-py_compile
-pybench             lemburg, pitrou
-pyclbr
-pydoc
-queue               rhettinger
-quopri
-random              rhettinger
-re                  effbot (inactive), pitrou, ezio.melotti
-readline
-reprlib
-resource
-rlcompleter
-runpy               ncoghlan
-sched
-select
-shelve
-shlex
-shutil              tarek
-signal
-site
-smtpd
-smtplib
-sndhdr
-socket
-socketserver
-spwd
-sqlite3             ghaering
-ssl                 janssen, pitrou, giampaolo.rodola
-stat
-string              georg.brandl*
-stringprep
-struct              mark.dickinson
-subprocess          astrand (inactive)
-sunau
-symbol
-symtable            benjamin.peterson
-sys
-sysconfig           tarek
-syslog              jafo
-tabnanny            tim_one
-tarfile             lars.gustaebel
-telnetlib
-tempfile            georg.brandl
-termios
-test
-textwrap            georg.brandl
-threading           pitrou
-time                alexander.belopolsky
-timeit              georg.brandl
-tkinter             gpolo
-token               georg.brandl
-tokenize
-trace               alexander.belopolsky
-traceback           georg.brandl*
-tty
-turtle              gregorlingl
-types
-unicodedata         loewis, lemburg, ezio.melotti
-unittest            michael.foord
-urllib              orsenthil
-uu
-uuid
-warnings            brett.cannon
-wave
-weakref             fdrake, pitrou
-webbrowser          georg.brandl
-winreg              brian.curtin*, stutzbach
-winsound            effbot (inactive)
-wsgiref             pje
-xdrlib
-xml.dom
-xml.dom.minidom
-xml.dom.pulldom
-xml.etree           effbot (inactive)
-xml.parsers.expat
-xml.sax
-xml.sax.handler
-xml.sax.saxutils
-xml.sax.xmlreader
-xmlrpc              loewis
-zipfile             alanmcintyre
-zipimport
-zlib
-==================  ===========
-
-
-==================  ===========
-Tool                Maintainers
-------------------  -----------
-pybench             lemburg
-==================  ===========
-
-
-==================  ===========
-Platform            Maintainers
-------------------  -----------
-AIX
-Cygwin              jlt63, stutzbach
-FreeBSD
-HP-UX
-Linux
-Mac                 ronaldoussoren
-NetBSD1
-OS2/EMX             aimacintyre
-Solaris
-Windows             tim.golden, brian.curtin
-==================  ===========
-
-
-==================  ===========
-Interest Area       Maintainers
-------------------  -----------
-algorithms
-ast/compiler        ncoghlan, benjamin.peterson, brett.cannon, georg.brandl
-autoconf/makefiles
-bsd
-bug tracker         ezio.melotti
-buildbots
-bytecode            pitrou
-data formats        mark.dickinson, georg.brandl
-database            lemburg
-documentation       georg.brandl, ezio.melotti
-GUI
-i18n                lemburg
-import machinery    brett.cannon, ncoghlan
-io                  pitrou, benjamin.peterson, stutzbach
-locale              lemburg, loewis
-mathematics         mark.dickinson, eric.smith, lemburg, stutzbach
-memory management   tim_one, lemburg
-networking          giampaolo.rodola
-packaging           tarek, lemburg
-py3 transition      benjamin.peterson
-release management  tarek, lemburg, benjamin.peterson, barry, loewis,
-                    gvanrossum, anthonybaxter
-str.format          eric.smith
-testing             michael.foord, pitrou, giampaolo.rodola
-threads             pitrou
-time and dates      lemburg
-unicode             lemburg, ezio.melotti, haypo
-version control
-==================  ===========

Deleted: python/branches/pep-3151/Misc/pymemcompat.h
==============================================================================
--- python/branches/pep-3151/Misc/pymemcompat.h	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,85 +0,0 @@
-/* The idea of this file is that you bundle it with your extension,
-   #include it, program to Python 2.3's memory API and have your
-   extension build with any version of Python from 1.5.2 through to
-   2.3 (and hopefully beyond). */
-
-#ifndef Py_PYMEMCOMPAT_H
-#define Py_PYMEMCOMPAT_H
-
-#include "Python.h"
-
-/* There are three "families" of memory API: the "raw memory", "object
-   memory" and "object" families.  (This is ignoring the matter of the
-   cycle collector, about which more is said below).
-
-   Raw Memory:
-
-       PyMem_Malloc, PyMem_Realloc, PyMem_Free
-
-   Object Memory:
-
-       PyObject_Malloc, PyObject_Realloc, PyObject_Free
-
-   Object:
-
-       PyObject_New, PyObject_NewVar, PyObject_Del
-
-   The raw memory and object memory allocators both mimic the
-   malloc/realloc/free interface from ANSI C, but the object memory
-   allocator can (and, since 2.3, does by default) use a different
-   allocation strategy biased towards lots of "small" allocations.
-
-   The object family is used for allocating Python objects, and the
-   initializers take care of some basic initialization (setting the
-   refcount to 1 and filling out the ob_type field) as well as having
-   a somewhat different interface.
-
-   Do not mix the families!  E.g. do not allocate memory with
-   PyMem_Malloc and free it with PyObject_Free.  You may get away with
-   it quite a lot of the time, but there *are* scenarios where this
-   will break.  You Have Been Warned. 
-
-   Also, in many versions of Python there are an insane amount of
-   memory interfaces to choose from.  Use the ones described above. */
-
-#if PY_VERSION_HEX < 0x01060000
-/* raw memory interface already present */
-
-/* there is no object memory interface in 1.5.2 */
-#define PyObject_Malloc		PyMem_Malloc
-#define PyObject_Realloc	PyMem_Realloc
-#define PyObject_Free		PyMem_Free
-
-/* the object interface is there, but the names have changed */
-#define PyObject_New		PyObject_NEW
-#define PyObject_NewVar		PyObject_NEW_VAR
-#define PyObject_Del		PyMem_Free
-#endif
-
-/* If your object is a container you probably want to support the
-   cycle collector, which was new in Python 2.0.
-
-   Unfortunately, the interface to the collector that was present in
-   Python 2.0 and 2.1 proved to be tricky to use, and so changed in
-   2.2 -- in a way that can't easily be papered over with macros.
-
-   This file contains macros that let you program to the 2.2 GC API.
-   Your module will compile against any Python since version 1.5.2,
-   but the type will only participate in the GC in versions 2.2 and
-   up.  Some work is still necessary on your part to only fill out the
-   tp_traverse and tp_clear fields when they exist and set tp_flags
-   appropriately.
-
-   It is possible to support both the 2.0 and 2.2 GC APIs, but it's
-   not pretty and this comment block is too narrow to contain a
-   description of what's required... */
-
-#if PY_VERSION_HEX < 0x020200B1
-#define PyObject_GC_New         PyObject_New
-#define PyObject_GC_NewVar      PyObject_NewVar
-#define PyObject_GC_Del         PyObject_Del
-#define PyObject_GC_Track(op)
-#define PyObject_GC_UnTrack(op)
-#endif
-
-#endif /* !Py_PYMEMCOMPAT_H */

Modified: python/branches/pep-3151/Misc/python-wing4.wpr
==============================================================================
--- python/branches/pep-3151/Misc/python-wing4.wpr	(original)
+++ python/branches/pep-3151/Misc/python-wing4.wpr	Sat Feb 26 08:16:32 2011
@@ -5,7 +5,11 @@
 ##################################################################
 [project attributes]
 proj.directory-list = [{'dirloc': loc('..'),
-                        'excludes': [u'Lib/__pycache__'],
+                        'excludes': [u'Lib/unittest/test/__pycache__',
+                                     u'Lib/__pycache__',
+                                     u'Doc/build',
+                                     u'Lib/unittest/__pycache__',
+                                     u'build'],
                         'filter': '*',
                         'include_hidden': False,
                         'recursive': True,

Modified: python/branches/pep-3151/Misc/python.man
==============================================================================
--- python/branches/pep-3151/Misc/python.man	(original)
+++ python/branches/pep-3151/Misc/python.man	Sat Feb 26 08:16:32 2011
@@ -26,6 +26,9 @@
 .B \-m 
 .I module-name
 ]
+[
+.B \-q
+]
 .br
        [
 .B \-O
@@ -145,6 +148,10 @@
 .B \-O0
 Discard docstrings in addition to the \fB-O\fP optimizations.
 .TP
+.B \-q
+Do not print the version and copyright messages. These messages are 
+also suppressed in non-interactive mode.
+.TP
 .BI "\-Q " argument
 Division control; see PEP 238.  The argument must be one of "old" (the
 default, int/int and long/long return an int or long), "new" (new

Modified: python/branches/pep-3151/Misc/python.pc.in
==============================================================================
--- python/branches/pep-3151/Misc/python.pc.in	(original)
+++ python/branches/pep-3151/Misc/python.pc.in	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,4 @@
+# See: man pkg-config
 prefix=@prefix@
 exec_prefix=@exec_prefix@
 libdir=@libdir@
@@ -9,5 +10,4 @@
 Version: @VERSION@
 Libs.private: @LIBS@
 Libs: -L${libdir} -lpython at VERSION@@ABIFLAGS@
-Cflags: -I${includedir}/python at VERSION@ 
-
+Cflags: -I${includedir}/python at VERSION@@ABIFLAGS@

Deleted: python/branches/pep-3151/Misc/setuid-prog.c
==============================================================================
--- python/branches/pep-3151/Misc/setuid-prog.c	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,176 +0,0 @@
-/*
-   Template for a setuid program that calls a script.
-
-   The script should be in an unwritable directory and should itself
-   be unwritable.  In fact all parent directories up to the root
-   should be unwritable.  The script must not be setuid, that's what
-   this program is for.
-
-   This is a template program.  You need to fill in the name of the
-   script that must be executed.  This is done by changing the
-   definition of FULL_PATH below.
-
-   There are also some rules that should be adhered to when writing
-   the script itself.
-
-   The first and most important rule is to never, ever trust that the
-   user of the program will behave properly.  Program defensively.
-   Check your arguments for reasonableness.  If the user is allowed to
-   create files, check the names of the files.  If the program depends
-   on argv[0] for the action it should perform, check it.
-
-   Assuming the script is a Bourne shell script, the first line of the
-   script should be
-    #!/bin/sh -
-   The - is important, don't omit it.  If you're using esh, the first
-   line should be
-    #!/usr/local/bin/esh -f
-   and for ksh, the first line should be
-    #!/usr/local/bin/ksh -p
-   The script should then set the variable IFS to the string
-   consisting of <space>, <tab>, and <newline>.  After this (*not*
-   before!), the PATH variable should be set to a reasonable value and
-   exported.  Do not expect the PATH to have a reasonable value, so do
-   not trust the old value of PATH.  You should then set the umask of
-   the program by calling
-    umask 077 # or 022 if you want the files to be readable
-   If you plan to change directories, you should either unset CDPATH
-   or set it to a good value.  Setting CDPATH to just ``.'' (dot) is a
-   good idea.
-   If, for some reason, you want to use csh, the first line should be
-    #!/bin/csh -fb
-   You should then set the path variable to something reasonable,
-   without trusting the inherited path.  Here too, you should set the
-   umask using the command
-    umask 077 # or 022 if you want the files to be readable
-*/
-
-#include <unistd.h>
-#include <stdlib.h>
-#include <stdio.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <string.h>
-
-/* CONFIGURATION SECTION */
-
-#ifndef FULL_PATH       /* so that this can be specified from the Makefile */
-/* Uncomment the following line:
-#define FULL_PATH       "/full/path/of/script"
-* Then comment out the #error line. */
-#error "You must define FULL_PATH somewhere"
-#endif
-#ifndef UMASK
-#define UMASK           077
-#endif
-
-/* END OF CONFIGURATION SECTION */
-
-#if defined(__STDC__) && defined(__sgi)
-#define environ _environ
-#endif
-
-/* don't change def_IFS */
-char def_IFS[] = "IFS= \t\n";
-/* you may want to change def_PATH, but you should really change it in */
-/* your script */
-#ifdef __sgi
-char def_PATH[] = "PATH=/usr/bsd:/usr/bin:/bin:/usr/local/bin:/usr/sbin";
-#else
-char def_PATH[] = "PATH=/usr/ucb:/usr/bin:/bin:/usr/local/bin";
-#endif
-/* don't change def_CDPATH */
-char def_CDPATH[] = "CDPATH=.";
-/* don't change def_ENV */
-char def_ENV[] = "ENV=:";
-
-/*
-   This function changes all environment variables that start with LD_
-   into variables that start with XD_.  This is important since we
-   don't want the script that is executed to use any funny shared
-   libraries.
-
-   The other changes to the environment are, strictly speaking, not
-   needed here.  They can safely be done in the script.  They are done
-   here because we don't trust the script writer (just like the script
-   writer shouldn't trust the user of the script).
-   If IFS is set in the environment, set it to space,tab,newline.
-   If CDPATH is set in the environment, set it to ``.''.
-   Set PATH to a reasonable default.
-*/
-void
-clean_environ(void)
-{
-    char **p;
-    extern char **environ;
-
-    for (p = environ; *p; p++) {
-        if (strncmp(*p, "LD_", 3) == 0)
-            **p = 'X';
-        else if (strncmp(*p, "_RLD", 4) == 0)
-            **p = 'X';
-        else if (strncmp(*p, "PYTHON", 6) == 0)
-            **p = 'X';
-        else if (strncmp(*p, "IFS=", 4) == 0)
-            *p = def_IFS;
-        else if (strncmp(*p, "CDPATH=", 7) == 0)
-            *p = def_CDPATH;
-        else if (strncmp(*p, "ENV=", 4) == 0)
-            *p = def_ENV;
-    }
-    putenv(def_PATH);
-}
-
-int
-main(int argc, char **argv)
-{
-    struct stat statb;
-    gid_t egid = getegid();
-    uid_t euid = geteuid();
-
-    /*
-       Sanity check #1.
-       This check should be made compile-time, but that's not possible.
-       If you're sure that you specified a full path name for FULL_PATH,
-       you can omit this check.
-    */
-    if (FULL_PATH[0] != '/') {
-        fprintf(stderr, "%s: %s is not a full path name\n", argv[0],
-            FULL_PATH);
-        fprintf(stderr, "You can only use this wrapper if you\n");
-        fprintf(stderr, "compile it with an absolute path.\n");
-        exit(1);
-    }
-
-    /*
-       Sanity check #2.
-       Check that the owner of the script is equal to either the
-       effective uid or the super user.
-    */
-    if (stat(FULL_PATH, &statb) < 0) {
-        perror("stat");
-        exit(1);
-    }
-    if (statb.st_uid != 0 && statb.st_uid != euid) {
-        fprintf(stderr, "%s: %s has the wrong owner\n", argv[0],
-            FULL_PATH);
-        fprintf(stderr, "The script should be owned by root,\n");
-        fprintf(stderr, "and shouldn't be writable by anyone.\n");
-        exit(1);
-    }
-
-    if (setregid(egid, egid) < 0)
-        perror("setregid");
-    if (setreuid(euid, euid) < 0)
-        perror("setreuid");
-
-    clean_environ();
-
-    umask(UMASK);
-
-    while (**argv == '-')       /* don't let argv[0] start with '-' */
-        (*argv)++;
-    execv(FULL_PATH, argv);
-    fprintf(stderr, "%s: could not execute the script\n", argv[0]);
-    exit(1);
-}

Modified: python/branches/pep-3151/Modules/Setup.dist
==============================================================================
--- python/branches/pep-3151/Modules/Setup.dist	(original)
+++ python/branches/pep-3151/Modules/Setup.dist	Sat Feb 26 08:16:32 2011
@@ -207,7 +207,7 @@
 #
 # First, look at Setup.config; configure may have set this for you.
 
-#crypt cryptmodule.c # -lcrypt	# crypt(3); needs -lcrypt on some systems
+#_crypt _cryptmodule.c # -lcrypt	# crypt(3); needs -lcrypt on some systems
 
 
 # Some more UNIX dependent modules -- off by default, since these

Modified: python/branches/pep-3151/Modules/_collectionsmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/_collectionsmodule.c	(original)
+++ python/branches/pep-3151/Modules/_collectionsmodule.c	Sat Feb 26 08:16:32 2011
@@ -485,7 +485,8 @@
         /* Advance left block/index pair */
         leftindex++;
         if (leftindex == BLOCKLEN) {
-            assert (leftblock->rightlink != NULL);
+            if (leftblock->rightlink == NULL)
+                break;
             leftblock = leftblock->rightlink;
             leftindex = 0;
         }
@@ -493,7 +494,8 @@
         /* Step backwards with the right block/index pair */
         rightindex--;
         if (rightindex == -1) {
-            assert (rightblock->leftlink != NULL);
+            if (rightblock->leftlink == NULL)
+                break;
             rightblock = rightblock->leftlink;
             rightindex = BLOCKLEN - 1;
         }
@@ -509,7 +511,7 @@
 {
     block *leftblock = deque->leftblock;
     Py_ssize_t leftindex = deque->leftindex;
-    Py_ssize_t n = (deque->len);
+    Py_ssize_t n = deque->len;
     Py_ssize_t i;
     Py_ssize_t count = 0;
     PyObject *item;
@@ -533,7 +535,8 @@
         /* Advance left block/index pair */
         leftindex++;
         if (leftindex == BLOCKLEN) {
-            assert (leftblock->rightlink != NULL);
+            if (leftblock->rightlink == NULL)  /* can occur when i==n-1 */
+                break;
             leftblock = leftblock->rightlink;
             leftindex = 0;
         }
@@ -1518,6 +1521,95 @@
     PyObject_GC_Del,                    /* tp_free */
 };
 
+/* helper function for Counter  *********************************************/
+
+PyDoc_STRVAR(_count_elements_doc,
+"_count_elements(mapping, iterable) -> None\n\
+\n\
+Count elements in the iterable, updating the mappping");
+
+static PyObject *
+_count_elements(PyObject *self, PyObject *args)
+{
+    PyObject *it, *iterable, *mapping, *oldval;
+    PyObject *newval = NULL;
+    PyObject *key = NULL;
+    PyObject *one = NULL;
+
+    if (!PyArg_UnpackTuple(args, "_count_elements", 2, 2, &mapping, &iterable))
+        return NULL;
+
+    it = PyObject_GetIter(iterable);
+    if (it == NULL)
+        return NULL;
+
+    one = PyLong_FromLong(1);
+    if (one == NULL) {
+        Py_DECREF(it);
+        return NULL;
+    }
+
+    if (PyDict_CheckExact(mapping)) {
+        while (1) {
+            key = PyIter_Next(it);
+            if (key == NULL) {
+                if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_StopIteration))
+                    PyErr_Clear();
+                else
+                    break;
+            }
+            oldval = PyDict_GetItem(mapping, key);
+            if (oldval == NULL) {
+                if (PyDict_SetItem(mapping, key, one) == -1)
+                    break;
+            } else {
+                newval = PyNumber_Add(oldval, one);
+                if (newval == NULL)
+                    break;
+                if (PyDict_SetItem(mapping, key, newval) == -1)
+                    break;
+                Py_CLEAR(newval);
+            }
+            Py_DECREF(key);
+        }
+    } else {
+        while (1) {
+            key = PyIter_Next(it);
+            if (key == NULL) {
+                if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_StopIteration))
+                    PyErr_Clear();
+                else
+                    break;
+            }
+            oldval = PyObject_GetItem(mapping, key);
+            if (oldval == NULL) {
+                if (!PyErr_Occurred() || !PyErr_ExceptionMatches(PyExc_KeyError))
+                    break;
+                PyErr_Clear();
+                Py_INCREF(one);
+                newval = one;
+            } else {
+                newval = PyNumber_Add(oldval, one);
+                Py_DECREF(oldval);
+                if (newval == NULL)
+                    break;
+            }
+            if (PyObject_SetItem(mapping, key, newval) == -1)
+                break;
+            Py_CLEAR(newval);
+            Py_DECREF(key);
+        }
+    }
+
+    Py_DECREF(it);
+    Py_XDECREF(key);
+    Py_XDECREF(newval);
+    Py_DECREF(one);
+    if (PyErr_Occurred())
+        return NULL;
+    Py_RETURN_NONE;
+}
+
 /* module level code ********************************************************/
 
 PyDoc_STRVAR(module_doc,
@@ -1526,13 +1618,17 @@
 - defaultdict:  dict subclass with a default value factory\n\
 ");
 
+static struct PyMethodDef module_functions[] = {
+    {"_count_elements", _count_elements,    METH_VARARGS,   _count_elements_doc},
+    {NULL,       NULL}          /* sentinel */
+};
 
 static struct PyModuleDef _collectionsmodule = {
     PyModuleDef_HEAD_INIT,
     "_collections",
     module_doc,
     -1,
-    NULL,
+    module_functions,
     NULL,
     NULL,
     NULL,

Modified: python/branches/pep-3151/Modules/_ctypes/_ctypes.c
==============================================================================
--- python/branches/pep-3151/Modules/_ctypes/_ctypes.c	(original)
+++ python/branches/pep-3151/Modules/_ctypes/_ctypes.c	Sat Feb 26 08:16:32 2011
@@ -1155,7 +1155,7 @@
         result = -1;
         goto done;
     }
-    result = PyUnicode_AsWideChar((PyUnicodeObject *)value,
+    result = PyUnicode_AsWideChar(value,
                                   (wchar_t *)self->b_ptr,
                                   self->b_size/sizeof(wchar_t));
     if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t))
@@ -3925,14 +3925,14 @@
 
   Returns -1 on error, or the index of next argument on success.
  */
-static int
+static Py_ssize_t
 _init_pos_args(PyObject *self, PyTypeObject *type,
                PyObject *args, PyObject *kwds,
-               int index)
+               Py_ssize_t index)
 {
     StgDictObject *dict;
     PyObject *fields;
-    int i;
+    Py_ssize_t i;
 
     if (PyType_stgdict((PyObject *)type->tp_base)) {
         index = _init_pos_args(self, type->tp_base,
@@ -4174,7 +4174,7 @@
         PyObject *np;
         Py_ssize_t start, stop, step, slicelen, cur, i;
 
-        if (PySlice_GetIndicesEx((PySliceObject *)item,
+        if (PySlice_GetIndicesEx(item,
                                  self->b_length, &start, &stop,
                                  &step, &slicelen) < 0) {
             return NULL;
@@ -4308,7 +4308,7 @@
     else if (PySlice_Check(item)) {
         Py_ssize_t start, stop, step, slicelen, otherlen, i, cur;
 
-        if (PySlice_GetIndicesEx((PySliceObject *)item,
+        if (PySlice_GetIndicesEx(item,
                                  self->b_length, &start, &stop,
                                  &step, &slicelen) < 0) {
             return -1;

Modified: python/branches/pep-3151/Modules/_ctypes/_ctypes_test.c
==============================================================================
--- python/branches/pep-3151/Modules/_ctypes/_ctypes_test.c	(original)
+++ python/branches/pep-3151/Modules/_ctypes/_ctypes_test.c	Sat Feb 26 08:16:32 2011
@@ -12,6 +12,20 @@
 
 /* some functions handy for testing */
 
+EXPORT(int)
+_testfunc_cbk_reg_int(int a, int b, int c, int d, int e,
+                      int (*func)(int, int, int, int, int))
+{
+    return func(a*a, b*b, c*c, d*d, e*e);
+}
+
+EXPORT(double)
+_testfunc_cbk_reg_double(double a, double b, double c, double d, double e,
+                         double (*func)(double, double, double, double, double))
+{
+    return func(a*a, b*b, c*c, d*d, e*e);
+}
+
 EXPORT(void)testfunc_array(int values[4])
 {
     printf("testfunc_array %d %d %d %d\n",

Modified: python/branches/pep-3151/Modules/_ctypes/cfield.c
==============================================================================
--- python/branches/pep-3151/Modules/_ctypes/cfield.c	(original)
+++ python/branches/pep-3151/Modules/_ctypes/cfield.c	Sat Feb 26 08:16:32 2011
@@ -52,7 +52,7 @@
 {
     CFieldObject *self;
     PyObject *proto;
-    Py_ssize_t size, align, length;
+    Py_ssize_t size, align;
     SETFUNC setfunc = NULL;
     GETFUNC getfunc = NULL;
     StgDictObject *dict;
@@ -106,7 +106,6 @@
     }
 
     size = dict->size;
-    length = dict->length;
     proto = desc;
 
     /*  Field descriptors for 'c_char * n' are be scpecial cased to
@@ -1214,7 +1213,7 @@
     } else
         Py_INCREF(value);
 
-    len = PyUnicode_AsWideChar((PyUnicodeObject *)value, chars, 2);
+    len = PyUnicode_AsWideChar(value, chars, 2);
     if (len != 1) {
         Py_DECREF(value);
         PyErr_SetString(PyExc_TypeError,
@@ -1292,7 +1291,7 @@
     } else if (size < length-1)
         /* copy terminating NUL character if there is space */
         size += 1;
-    PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size);
+    PyUnicode_AsWideChar(value, (wchar_t *)ptr, size);
     return value;
 }
 

Modified: python/branches/pep-3151/Modules/_ctypes/libffi_msvc/ffi.c
==============================================================================
--- python/branches/pep-3151/Modules/_ctypes/libffi_msvc/ffi.c	(original)
+++ python/branches/pep-3151/Modules/_ctypes/libffi_msvc/ffi.c	Sat Feb 26 08:16:32 2011
@@ -380,7 +380,7 @@
   short bytes;
   char *tramp;
 #ifdef _WIN64
-  int mask;
+  int mask = 0;
 #endif
   FFI_ASSERT (cif->abi == FFI_SYSV);
   

Modified: python/branches/pep-3151/Modules/_datetimemodule.c
==============================================================================
--- python/branches/pep-3151/Modules/_datetimemodule.c	(original)
+++ python/branches/pep-3151/Modules/_datetimemodule.c	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,6 @@
  */
 
 #include "Python.h"
-#include "modsupport.h"
 #include "structmember.h"
 
 #include <time.h>
@@ -1167,10 +1166,10 @@
     if (!pin)
         return NULL;
 
-    /* Give up if the year is before 1900.
+    /* Give up if the year is before 1000.
      * Python strftime() plays games with the year, and different
      * games depending on whether envar PYTHON2K is set.  This makes
-     * years before 1900 a nightmare, even if the platform strftime
+     * years before 1000 a nightmare, even if the platform strftime
      * supports them (and not all do).
      * We could get a lot farther here by avoiding Python's strftime
      * wrapper and calling the C strftime() directly, but that isn't
@@ -1183,10 +1182,10 @@
         assert(PyLong_Check(pyyear));
         year = PyLong_AsLong(pyyear);
         Py_DECREF(pyyear);
-        if (year < 1900) {
+        if (year < 1000) {
             PyErr_Format(PyExc_ValueError, "year=%ld is before "
-                         "1900; the datetime strftime() "
-                         "methods require year >= 1900",
+                         "1000; the datetime strftime() "
+                         "methods require year >= 1000",
                          year);
             return NULL;
         }
@@ -1258,7 +1257,8 @@
             assert(PyUnicode_Check(Zreplacement));
             ptoappend = _PyUnicode_AsStringAndSize(Zreplacement,
                                                   &ntoappend);
-            ntoappend = Py_SIZE(Zreplacement);
+            if (ptoappend == NULL)
+                goto Done;
         }
         else if (ch == 'f') {
             /* format microseconds */
@@ -1461,7 +1461,7 @@
         goto Done;
     Py_DECREF(x1);
     Py_DECREF(x2);
-    x1 = x2 = NULL;
+    /* x1 = */ x2 = NULL;
 
     /* x3 has days+seconds in seconds */
     x1 = PyNumber_Multiply(x3, us_per_second);          /* us */
@@ -3663,7 +3663,7 @@
 
     /* Python's strftime does insane things with the year part of the
      * timetuple.  The year is forced to (the otherwise nonsensical)
-     * 1900 to worm around that.
+     * 1900 to work around that.
      */
     tuple = Py_BuildValue("iiiiiiiii",
                           1900, 1, 1, /* year, month, day */

Modified: python/branches/pep-3151/Modules/_elementtree.c
==============================================================================
--- python/branches/pep-3151/Modules/_elementtree.c	(original)
+++ python/branches/pep-3151/Modules/_elementtree.c	Sat Feb 26 08:16:32 2011
@@ -1272,7 +1272,7 @@
         if (!self->extra)
             return PyList_New(0);
 
-        if (PySlice_GetIndicesEx((PySliceObject *)item,
+        if (PySlice_GetIndicesEx(item,
                 self->extra->length,
                 &start, &stop, &step, &slicelen) < 0) {
             return NULL;
@@ -1331,7 +1331,7 @@
         if (!self->extra)
             element_new_extra(self, NULL);
 
-        if (PySlice_GetIndicesEx((PySliceObject *)item,
+        if (PySlice_GetIndicesEx(item,
                 self->extra->length,
                 &start, &stop, &step, &slicelen) < 0) {
             return -1;
@@ -1483,6 +1483,9 @@
 
     if (PyUnicode_Check(nameobj))
         name = _PyUnicode_AsString(nameobj);
+    
+    if (name == NULL)
+        return NULL;
 
     /* handle common attributes first */
     if (strcmp(name, "tag") == 0) {
@@ -2139,7 +2142,7 @@
     PyObject *position;
     char buffer[256];
 
-    sprintf(buffer, "%s: line %d, column %d", message, line, column);
+    sprintf(buffer, "%.100s: line %d, column %d", message, line, column);
 
     error = PyObject_CallFunction(elementtree_parseerror_obj, "s", buffer);
     if (!error)
@@ -2194,8 +2197,8 @@
         Py_XDECREF(res);
     } else if (!PyErr_Occurred()) {
         /* Report the first error, not the last */
-        char message[128];
-        sprintf(message, "undefined entity &%.100s;", _PyUnicode_AsString(key));
+        char message[128] = "undefined entity ";
+        strncat(message, data_in, data_len < 100?data_len:100);
         expat_set_error(
             message,
             EXPAT(GetErrorLineNumber)(self->parser),
@@ -2796,29 +2799,25 @@
 static PyObject*  
 xmlparser_getattro(XMLParserObject* self, PyObject* nameobj)
 {
-    PyObject* res;
-    char *name = "";
-
-    if (PyUnicode_Check(nameobj))
-        name = _PyUnicode_AsString(nameobj);
-
-    PyErr_Clear();
-
-    if (strcmp(name, "entity") == 0)
-        res = self->entity;
-    else if (strcmp(name, "target") == 0)
-        res = self->target;
-    else if (strcmp(name, "version") == 0) {
-        char buffer[100];
-        sprintf(buffer, "Expat %d.%d.%d", XML_MAJOR_VERSION,
+    if (PyUnicode_Check(nameobj)) {
+        PyObject* res;
+        if (PyUnicode_CompareWithASCIIString(nameobj, "entity") == 0)
+            res = self->entity;
+        else if (PyUnicode_CompareWithASCIIString(nameobj, "target") == 0)
+            res = self->target;
+        else if (PyUnicode_CompareWithASCIIString(nameobj, "version") == 0) {
+            return PyUnicode_FromFormat(
+                "Expat %d.%d.%d", XML_MAJOR_VERSION,
                 XML_MINOR_VERSION, XML_MICRO_VERSION);
-        return PyUnicode_DecodeUTF8(buffer, strlen(buffer), "strict");
-    } else {
-        return PyObject_GenericGetAttr((PyObject*) self, nameobj);
-    }
+        }
+        else
+            goto generic;
 
-    Py_INCREF(res);
-    return res;
+        Py_INCREF(res);
+        return res;
+    }
+  generic:
+    return PyObject_GenericGetAttr((PyObject*) self, nameobj);
 }
 
 static PyTypeObject XMLParser_Type = {

Modified: python/branches/pep-3151/Modules/_functoolsmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/_functoolsmodule.c	(original)
+++ python/branches/pep-3151/Modules/_functoolsmodule.c	Sat Feb 26 08:16:32 2011
@@ -196,6 +196,48 @@
     {NULL} /* Sentinel */
 };
 
+static PyObject *
+partial_repr(partialobject *pto)
+{
+    PyObject *result;
+    PyObject *arglist;
+    PyObject *tmp;
+    Py_ssize_t i, n;
+
+    arglist = PyUnicode_FromString("");
+    if (arglist == NULL) {
+        return NULL;
+    }
+    /* Pack positional arguments */
+    assert (PyTuple_Check(pto->args));
+    n = PyTuple_GET_SIZE(pto->args);
+    for (i = 0; i < n; i++) {
+        tmp = PyUnicode_FromFormat("%U, %R", arglist,
+                                   PyTuple_GET_ITEM(pto->args, i));
+        Py_DECREF(arglist);
+        if (tmp == NULL)
+            return NULL;
+        arglist = tmp;
+    }
+    /* Pack keyword arguments */
+    assert (pto->kw == Py_None  ||  PyDict_Check(pto->kw));
+    if (pto->kw != Py_None) {
+        PyObject *key, *value;
+        for (i = 0; PyDict_Next(pto->kw, &i, &key, &value);) {
+            tmp = PyUnicode_FromFormat("%U, %U=%R", arglist,
+                                       key, value);
+            Py_DECREF(arglist);
+            if (tmp == NULL)
+                return NULL;
+            arglist = tmp;
+        }
+    }
+    result = PyUnicode_FromFormat("%s(%R%U)", Py_TYPE(pto)->tp_name,
+                                  pto->fn, arglist);
+    Py_DECREF(arglist);
+    return result;
+}
+
 /* Pickle strategy:
    __reduce__ by itself doesn't support getting kwargs in the unpickle
    operation so we define a __setstate__ that replaces all the information
@@ -254,7 +296,7 @@
     0,                                  /* tp_getattr */
     0,                                  /* tp_setattr */
     0,                                  /* tp_reserved */
-    0,                                  /* tp_repr */
+    (reprfunc)partial_repr,             /* tp_repr */
     0,                                  /* tp_as_number */
     0,                                  /* tp_as_sequence */
     0,                                  /* tp_as_mapping */

Modified: python/branches/pep-3151/Modules/_gdbmmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/_gdbmmodule.c	(original)
+++ python/branches/pep-3151/Modules/_gdbmmodule.c	Sat Feb 26 08:16:32 2011
@@ -135,6 +135,28 @@
     return v;
 }
 
+PyDoc_STRVAR(dbm_get__doc__,
+"get(key[, default]) -> value\n\
+Get the value for key, or default if not present; if not given,\n\
+default is None.");
+
+static PyObject *
+dbm_get(dbmobject *dp, PyObject *args)
+{
+    PyObject *v, *res;
+    PyObject *def = Py_None;
+
+    if (!PyArg_UnpackTuple(args, "get", 1, 2, &v, &def))
+        return NULL;
+    res = dbm_subscript(dp, v);
+    if (res == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
+        PyErr_Clear();
+        Py_INCREF(def);
+        return def;
+    }
+    return res;
+}
+
 static int
 dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
 {
@@ -176,6 +198,29 @@
     return 0;
 }
 
+PyDoc_STRVAR(dbm_setdefault__doc__,
+"setdefault(key[, default]) -> value\n\
+Get value for key, or set it to default and return default if not present;\n\
+if not given, default is None.");
+
+static PyObject *
+dbm_setdefault(dbmobject *dp, PyObject *args)
+{
+    PyObject *v, *res;
+    PyObject *def = Py_None;
+
+    if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &v, &def))
+        return NULL;
+    res = dbm_subscript(dp, v);
+    if (res == NULL && PyErr_ExceptionMatches(PyExc_KeyError)) {
+        PyErr_Clear();
+        if (dbm_ass_sub(dp, v, def) < 0)
+            return NULL;
+        return dbm_subscript(dp, v);
+    }
+    return res;
+}
+
 static PyMappingMethods dbm_as_mapping = {
     (lenfunc)dbm_length,                /*mp_length*/
     (binaryfunc)dbm_subscript,          /*mp_subscript*/
@@ -378,6 +423,8 @@
     {"nextkey",   (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__},
     {"reorganize",(PyCFunction)dbm_reorganize,METH_NOARGS, dbm_reorganize__doc__},
     {"sync",      (PyCFunction)dbm_sync,    METH_NOARGS, dbm_sync__doc__},
+    {"get",       (PyCFunction)dbm_get,     METH_VARARGS, dbm_get__doc__},
+    {"setdefault",(PyCFunction)dbm_setdefault,METH_VARARGS, dbm_setdefault__doc__},
     {NULL,              NULL}           /* sentinel */
 };
 

Modified: python/branches/pep-3151/Modules/_io/bufferedio.c
==============================================================================
--- python/branches/pep-3151/Modules/_io/bufferedio.c	(original)
+++ python/branches/pep-3151/Modules/_io/bufferedio.c	Sat Feb 26 08:16:32 2011
@@ -225,6 +225,7 @@
 
 #ifdef WITH_THREAD
     PyThread_type_lock lock;
+    volatile long owner;
 #endif
 
     Py_ssize_t buffer_size;
@@ -260,17 +261,34 @@
 /* These macros protect the buffered object against concurrent operations. */
 
 #ifdef WITH_THREAD
-#define ENTER_BUFFERED(self) \
-    if (!PyThread_acquire_lock(self->lock, 0)) { \
-        Py_BEGIN_ALLOW_THREADS \
-        PyThread_acquire_lock(self->lock, 1); \
-        Py_END_ALLOW_THREADS \
+
+static int
+_enter_buffered_busy(buffered *self)
+{
+    if (self->owner == PyThread_get_thread_ident()) {
+        PyErr_Format(PyExc_RuntimeError,
+                     "reentrant call inside %R", self);
+        return 0;
     }
+    Py_BEGIN_ALLOW_THREADS
+    PyThread_acquire_lock(self->lock, 1);
+    Py_END_ALLOW_THREADS
+    return 1;
+}
+
+#define ENTER_BUFFERED(self) \
+    ( (PyThread_acquire_lock(self->lock, 0) ? \
+       1 : _enter_buffered_busy(self)) \
+     && (self->owner = PyThread_get_thread_ident(), 1) )
 
 #define LEAVE_BUFFERED(self) \
-    PyThread_release_lock(self->lock);
+    do { \
+        self->owner = 0; \
+        PyThread_release_lock(self->lock); \
+    } while(0);
+
 #else
-#define ENTER_BUFFERED(self)
+#define ENTER_BUFFERED(self) 1
 #define LEAVE_BUFFERED(self)
 #endif
 
@@ -387,7 +405,7 @@
 /* Because this can call arbitrary code, it shouldn't be called when
    the refcount is 0 (that is, not directly from tp_dealloc unless
    the refcount has been temporarily re-incremented). */
-PyObject *
+static PyObject *
 buffered_dealloc_warn(buffered *self, PyObject *source)
 {
     if (self->ok && self->raw) {
@@ -444,7 +462,8 @@
     int r;
 
     CHECK_INITIALIZED(self)
-    ENTER_BUFFERED(self)
+    if (!ENTER_BUFFERED(self))
+        return NULL;
 
     r = buffered_closed(self);
     if (r < 0)
@@ -465,7 +484,8 @@
     /* flush() will most probably re-take the lock, so drop it first */
     LEAVE_BUFFERED(self)
     res = PyObject_CallMethodObjArgs((PyObject *)self, _PyIO_str_flush, NULL);
-    ENTER_BUFFERED(self)
+    if (!ENTER_BUFFERED(self))
+        return NULL;
     if (res == NULL) {
         goto end;
     }
@@ -679,6 +699,7 @@
         PyErr_SetString(PyExc_RuntimeError, "can't allocate read lock");
         return -1;
     }
+    self->owner = 0;
 #endif
     /* Find out whether buffer_size is a power of 2 */
     /* XXX is this optimization useful? */
@@ -693,6 +714,39 @@
     return 0;
 }
 
+/* Return 1 if an EnvironmentError with errno == EINTR is set (and then
+   clears the error indicator), 0 otherwise.
+   Should only be called when PyErr_Occurred() is true.
+*/
+static int
+_trap_eintr(void)
+{
+    static PyObject *eintr_int = NULL;
+    PyObject *typ, *val, *tb;
+    PyEnvironmentErrorObject *env_err;
+
+    if (eintr_int == NULL) {
+        eintr_int = PyLong_FromLong(EINTR);
+        assert(eintr_int != NULL);
+    }
+    if (!PyErr_ExceptionMatches(PyExc_EnvironmentError))
+        return 0;
+    PyErr_Fetch(&typ, &val, &tb);
+    PyErr_NormalizeException(&typ, &val, &tb);
+    env_err = (PyEnvironmentErrorObject *) val;
+    assert(env_err != NULL);
+    if (env_err->myerrno != NULL &&
+        PyObject_RichCompareBool(env_err->myerrno, eintr_int, Py_EQ) > 0) {
+        Py_DECREF(typ);
+        Py_DECREF(val);
+        Py_XDECREF(tb);
+        return 1;
+    }
+    /* This silences any error set by PyObject_RichCompareBool() */
+    PyErr_Restore(typ, val, tb);
+    return 0;
+}
+
 /*
  * Shared methods and wrappers
  */
@@ -705,7 +759,8 @@
     CHECK_INITIALIZED(self)
     CHECK_CLOSED(self, "flush of closed file")
 
-    ENTER_BUFFERED(self)
+    if (!ENTER_BUFFERED(self))
+        return NULL;
     res = _bufferedwriter_flush_unlocked(self, 0);
     if (res != NULL && self->readable) {
         /* Rewind the raw stream so that its position corresponds to
@@ -732,7 +787,8 @@
         return NULL;
     }
 
-    ENTER_BUFFERED(self)
+    if (!ENTER_BUFFERED(self))
+        return NULL;
 
     if (self->writable) {
         res = _bufferedwriter_flush_unlocked(self, 1);
@@ -767,7 +823,8 @@
 
     if (n == -1) {
         /* The number of bytes is unspecified, read until the end of stream */
-        ENTER_BUFFERED(self)
+        if (!ENTER_BUFFERED(self))
+            return NULL;
         res = _bufferedreader_read_all(self);
         LEAVE_BUFFERED(self)
     }
@@ -775,7 +832,8 @@
         res = _bufferedreader_read_fast(self, n);
         if (res == Py_None) {
             Py_DECREF(res);
-            ENTER_BUFFERED(self)
+            if (!ENTER_BUFFERED(self))
+                return NULL;
             res = _bufferedreader_read_generic(self, n);
             LEAVE_BUFFERED(self)
         }
@@ -803,7 +861,8 @@
     if (n == 0)
         return PyBytes_FromStringAndSize(NULL, 0);
 
-    ENTER_BUFFERED(self)
+    if (!ENTER_BUFFERED(self))
+        return NULL;
     
     if (self->writable) {
         res = _bufferedwriter_flush_unlocked(self, 1);
@@ -859,7 +918,8 @@
     
     /* TODO: use raw.readinto() instead! */
     if (self->writable) {
-        ENTER_BUFFERED(self)
+        if (!ENTER_BUFFERED(self))
+            return NULL;
         res = _bufferedwriter_flush_unlocked(self, 0);
         LEAVE_BUFFERED(self)
         if (res == NULL)
@@ -903,7 +963,8 @@
         goto end_unlocked;
     }
 
-    ENTER_BUFFERED(self)
+    if (!ENTER_BUFFERED(self))
+        goto end_unlocked;
 
     /* Now we try to get some more from the raw stream */
     if (self->writable) {
@@ -1053,7 +1114,8 @@
         }
     }
 
-    ENTER_BUFFERED(self)
+    if (!ENTER_BUFFERED(self))
+        return NULL;
 
     /* Fallback: invoke raw seek() method and clear buffer */
     if (self->writable) {
@@ -1091,7 +1153,8 @@
         return NULL;
     }
 
-    ENTER_BUFFERED(self)
+    if (!ENTER_BUFFERED(self))
+        return NULL;
 
     if (self->writable) {
         res = _bufferedwriter_flush_unlocked(self, 0);
@@ -1239,7 +1302,14 @@
     memobj = PyMemoryView_FromBuffer(&buf);
     if (memobj == NULL)
         return -1;
-    res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_readinto, memobj, NULL);
+    /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR
+       occurs so we needn't do it ourselves.
+       We then retry reading, ignoring the signal if no handler has
+       raised (see issue #10956).
+    */
+    do {
+        res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_readinto, memobj, NULL);
+    } while (res == NULL && _trap_eintr());
     Py_DECREF(memobj);
     if (res == NULL)
         return -1;
@@ -1511,7 +1581,7 @@
 };
 
 static PyMemberDef bufferedreader_members[] = {
-    {"raw", T_OBJECT, offsetof(buffered, raw), 0},
+    {"raw", T_OBJECT, offsetof(buffered, raw), READONLY},
     {NULL}
 };
 
@@ -1648,7 +1718,14 @@
     memobj = PyMemoryView_FromBuffer(&buf);
     if (memobj == NULL)
         return -1;
-    res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_write, memobj, NULL);
+    /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR
+       occurs so we needn't do it ourselves.
+       We then retry writing, ignoring the signal if no handler has
+       raised (see issue #10956).
+    */
+    do {
+        res = PyObject_CallMethodObjArgs(self->raw, _PyIO_str_write, memobj, NULL);
+    } while (res == NULL && _trap_eintr());
     Py_DECREF(memobj);
     if (res == NULL)
         return -1;
@@ -1748,7 +1825,10 @@
         return NULL;
     }
 
-    ENTER_BUFFERED(self)
+    if (!ENTER_BUFFERED(self)) {
+        PyBuffer_Release(&buf);
+        return NULL;
+    }
 
     /* Fast path: the data to write can be fully buffered. */
     if (!VALID_READ_BUFFER(self) && !VALID_WRITE_BUFFER(self)) {
@@ -1893,7 +1973,7 @@
 };
 
 static PyMemberDef bufferedwriter_members[] = {
-    {"raw", T_OBJECT, offsetof(buffered, raw), 0},
+    {"raw", T_OBJECT, offsetof(buffered, raw), READONLY},
     {NULL}
 };
 
@@ -2287,7 +2367,7 @@
 };
 
 static PyMemberDef bufferedrandom_members[] = {
-    {"raw", T_OBJECT, offsetof(buffered, raw), 0},
+    {"raw", T_OBJECT, offsetof(buffered, raw), READONLY},
     {NULL}
 };
 

Modified: python/branches/pep-3151/Modules/_io/bytesio.c
==============================================================================
--- python/branches/pep-3151/Modules/_io/bytesio.c	(original)
+++ python/branches/pep-3151/Modules/_io/bytesio.c	Sat Feb 26 08:16:32 2011
@@ -430,15 +430,20 @@
 bytesio_readinto(bytesio *self, PyObject *buffer)
 {
     void *raw_buffer;
-    Py_ssize_t len;
+    Py_ssize_t len, n;
 
     CHECK_CLOSED(self);
 
     if (PyObject_AsWriteBuffer(buffer, &raw_buffer, &len) == -1)
         return NULL;
 
-    if (self->pos + len > self->string_size)
-        len = self->string_size - self->pos;
+    /* adjust invalid sizes */
+    n = self->string_size - self->pos;
+    if (len > n) {
+        len = n;
+        if (len < 0)
+            len = 0;
+    }
 
     memcpy(raw_buffer, self->buf + self->pos, len);
     assert(self->pos + len < PY_SSIZE_T_MAX);
@@ -933,13 +938,11 @@
 bytesiobuf_getbuffer(bytesiobuf *obj, Py_buffer *view, int flags)
 {
     int ret;
-    void *ptr;
     bytesio *b = (bytesio *) obj->source;
     if (view == NULL) {
         b->exports++;
         return 0;
     }
-    ptr = (void *) obj;
     ret = PyBuffer_FillInfo(view, (PyObject*)obj, b->buf, b->string_size,
                             0, flags);
     if (ret >= 0) {

Modified: python/branches/pep-3151/Modules/_io/fileio.c
==============================================================================
--- python/branches/pep-3151/Modules/_io/fileio.c	(original)
+++ python/branches/pep-3151/Modules/_io/fileio.c	Sat Feb 26 08:16:32 2011
@@ -388,6 +388,11 @@
             goto error;
     }
 
+#if defined(MS_WINDOWS) || defined(__CYGWIN__)
+    /* don't translate newlines (\r\n <=> \n) */
+    _setmode(self->fd, O_BINARY);
+#endif
+
     if (PyObject_SetAttrString((PyObject *)self, "name", nameobj) < 0)
         goto error;
 
@@ -506,7 +511,7 @@
 fileio_readinto(fileio *self, PyObject *args)
 {
     Py_buffer pbuf;
-    Py_ssize_t n;
+    Py_ssize_t n, len;
 
     if (self->fd < 0)
         return err_closed();
@@ -517,9 +522,16 @@
         return NULL;
 
     if (_PyVerify_fd(self->fd)) {
+        len = pbuf.len;
         Py_BEGIN_ALLOW_THREADS
         errno = 0;
-        n = read(self->fd, pbuf.buf, pbuf.len);
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+        if (len > INT_MAX)
+            len = INT_MAX;
+        n = read(self->fd, pbuf.buf, (int)len);
+#else
+        n = read(self->fd, pbuf.buf, len);
+#endif
         Py_END_ALLOW_THREADS
     } else
         n = -1;
@@ -685,7 +697,7 @@
 fileio_write(fileio *self, PyObject *args)
 {
     Py_buffer pbuf;
-    Py_ssize_t n;
+    Py_ssize_t n, len;
 
     if (self->fd < 0)
         return err_closed();
@@ -698,7 +710,14 @@
     if (_PyVerify_fd(self->fd)) {
         Py_BEGIN_ALLOW_THREADS
         errno = 0;
-        n = write(self->fd, pbuf.buf, pbuf.len);
+        len = pbuf.len;
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+        if (len > INT_MAX)
+            len = INT_MAX;
+        n = write(self->fd, pbuf.buf, (int)len);
+#else
+        n = write(self->fd, pbuf.buf, len);
+#endif
         Py_END_ALLOW_THREADS
     } else
         n = -1;

Modified: python/branches/pep-3151/Modules/_io/textio.c
==============================================================================
--- python/branches/pep-3151/Modules/_io/textio.c	(original)
+++ python/branches/pep-3151/Modules/_io/textio.c	Sat Feb 26 08:16:32 2011
@@ -678,12 +678,16 @@
     PyObject *pending_bytes;       /* list of bytes objects waiting to be
                                       written, or NULL */
     Py_ssize_t pending_bytes_count;
-    PyObject *snapshot;
+
     /* snapshot is either None, or a tuple (dec_flags, next_input) where
      * dec_flags is the second (integer) item of the decoder state and
      * next_input is the chunk of input bytes that comes next after the
      * snapshot point.  We use this to reconstruct decoder states in tell().
      */
+    PyObject *snapshot;
+    /* Bytes-to-characters ratio for the current chunk. Serves as input for
+       the heuristic in tell(). */
+    double b2cratio;
 
     /* Cache raw object if it's a FileIO object */
     PyObject *raw;
@@ -850,6 +854,7 @@
     self->decoded_chars_used = 0;
     self->pending_bytes_count = 0;
     self->encodefunc = NULL;
+    self->b2cratio = 0.0;
 
     if (encoding == NULL) {
         /* Try os.device_encoding(fileno) */
@@ -1390,6 +1395,7 @@
     PyObject *dec_flags = NULL;
     PyObject *input_chunk = NULL;
     PyObject *decoded_chars, *chunk_size;
+    Py_ssize_t nbytes, nchars;
     int eof;
 
     /* The return value is True unless EOF was reached.  The decoded string is
@@ -1435,7 +1441,8 @@
         goto fail;
     assert(PyBytes_Check(input_chunk));
 
-    eof = (PyBytes_Size(input_chunk) == 0);
+    nbytes = PyBytes_Size(input_chunk);
+    eof = (nbytes == 0);
 
     if (Py_TYPE(self->decoder) == &PyIncrementalNewlineDecoder_Type) {
         decoded_chars = _PyIncrementalNewlineDecoder_decode(
@@ -1450,7 +1457,12 @@
     if (decoded_chars == NULL)
         goto fail;
     textiowrapper_set_decoded_chars(self, decoded_chars);
-    if (PyUnicode_GET_SIZE(decoded_chars) > 0)
+    nchars = PyUnicode_GET_SIZE(decoded_chars);
+    if (nchars > 0)
+        self->b2cratio = (double) nbytes / nchars;
+    else
+        self->b2cratio = 0.0;
+    if (nchars > 0)
         eof = 0;
 
     if (self->telling) {
@@ -2139,8 +2151,12 @@
     cookie_type cookie = {0,0,0,0,0};
     PyObject *next_input;
     Py_ssize_t chars_to_skip, chars_decoded;
+    Py_ssize_t skip_bytes, skip_back;
     PyObject *saved_state = NULL;
     char *input, *input_end;
+    char *dec_buffer;
+    Py_ssize_t dec_buffer_len;
+    int dec_flags;
 
     CHECK_INITIALIZED(self);
     CHECK_CLOSED(self);
@@ -2176,6 +2192,7 @@
 #else
     cookie.start_pos = PyLong_AsLong(posobj);
 #endif
+    Py_DECREF(posobj);
     if (PyErr_Occurred())
         goto fail;
 
@@ -2190,57 +2207,99 @@
     /* How many decoded characters have been used up since the snapshot? */
     if (self->decoded_chars_used == 0)  {
         /* We haven't moved from the snapshot point. */
-        Py_DECREF(posobj);
         return textiowrapper_build_cookie(&cookie);
     }
 
     chars_to_skip = self->decoded_chars_used;
 
-    /* Starting from the snapshot position, we will walk the decoder
-     * forward until it gives us enough decoded characters.
-     */
+    /* Decoder state will be restored at the end */
     saved_state = PyObject_CallMethodObjArgs(self->decoder,
                                              _PyIO_str_getstate, NULL);
     if (saved_state == NULL)
         goto fail;
 
-    /* Note our initial start point. */
-    if (_textiowrapper_decoder_setstate(self, &cookie) < 0)
-        goto fail;
+#define DECODER_GETSTATE() do { \
+        PyObject *_state = PyObject_CallMethodObjArgs(self->decoder, \
+            _PyIO_str_getstate, NULL); \
+        if (_state == NULL) \
+            goto fail; \
+        if (!PyArg_Parse(_state, "(y#i)", &dec_buffer, &dec_buffer_len, &dec_flags)) { \
+            Py_DECREF(_state); \
+            goto fail; \
+        } \
+        Py_DECREF(_state); \
+    } while (0)
+
+    /* TODO: replace assert with exception */
+#define DECODER_DECODE(start, len, res) do { \
+        PyObject *_decoded = PyObject_CallMethod( \
+            self->decoder, "decode", "y#", start, len); \
+        if (_decoded == NULL) \
+            goto fail; \
+        assert (PyUnicode_Check(_decoded)); \
+        res = PyUnicode_GET_SIZE(_decoded); \
+        Py_DECREF(_decoded); \
+    } while (0)
 
-    /* Feed the decoder one byte at a time.  As we go, note the
-     * nearest "safe start point" before the current location
-     * (a point where the decoder has nothing buffered, so seek()
+    /* Fast search for an acceptable start point, close to our
+       current pos */
+    skip_bytes = (Py_ssize_t) (self->b2cratio * chars_to_skip);
+    skip_back = 1;
+    assert(skip_back <= PyBytes_GET_SIZE(next_input));
+    input = PyBytes_AS_STRING(next_input);
+    while (skip_bytes > 0) {
+        /* Decode up to temptative start point */
+        if (_textiowrapper_decoder_setstate(self, &cookie) < 0)
+            goto fail;
+        DECODER_DECODE(input, skip_bytes, chars_decoded);
+        if (chars_decoded <= chars_to_skip) {
+            DECODER_GETSTATE();
+            if (dec_buffer_len == 0) {
+                /* Before pos and no bytes buffered in decoder => OK */
+                cookie.dec_flags = dec_flags;
+                chars_to_skip -= chars_decoded;
+                break;
+            }
+            /* Skip back by buffered amount and reset heuristic */
+            skip_bytes -= dec_buffer_len;
+            skip_back = 1;
+        }
+        else {
+            /* We're too far ahead, skip back a bit */
+            skip_bytes -= skip_back;
+            skip_back *= 2;
+        }
+    }
+    if (skip_bytes <= 0) {
+        skip_bytes = 0;
+        if (_textiowrapper_decoder_setstate(self, &cookie) < 0)
+            goto fail;
+    }
+
+    /* Note our initial start point. */
+    cookie.start_pos += skip_bytes;
+    cookie.chars_to_skip = chars_to_skip;
+    if (chars_to_skip == 0)
+        goto finally;
+
+    /* We should be close to the desired position.  Now feed the decoder one
+     * byte at a time until we reach the `chars_to_skip` target.
+     * As we go, note the nearest "safe start point" before the current
+     * location (a point where the decoder has nothing buffered, so seek()
      * can safely start from there and advance to this location).
      */
     chars_decoded = 0;
     input = PyBytes_AS_STRING(next_input);
     input_end = input + PyBytes_GET_SIZE(next_input);
+    input += skip_bytes;
     while (input < input_end) {
-        PyObject *state;
-        char *dec_buffer;
-        Py_ssize_t dec_buffer_len;
-        int dec_flags;
-
-        PyObject *decoded = PyObject_CallMethod(
-            self->decoder, "decode", "y#", input, 1);
-        if (decoded == NULL)
-            goto fail;
-        assert (PyUnicode_Check(decoded));
-        chars_decoded += PyUnicode_GET_SIZE(decoded);
-        Py_DECREF(decoded);
+        Py_ssize_t n;
 
+        DECODER_DECODE(input, 1, n);
+        /* We got n chars for 1 byte */
+        chars_decoded += n;
         cookie.bytes_to_feed += 1;
-
-        state = PyObject_CallMethodObjArgs(self->decoder,
-                                           _PyIO_str_getstate, NULL);
-        if (state == NULL)
-            goto fail;
-        if (!PyArg_Parse(state, "(y#i)", &dec_buffer, &dec_buffer_len, &dec_flags)) {
-            Py_DECREF(state);
-            goto fail;
-        }
-        Py_DECREF(state);
+        DECODER_GETSTATE();
 
         if (dec_buffer_len == 0 && chars_decoded <= chars_to_skip) {
             /* Decoder buffer is empty, so this is a safe start point. */
@@ -2272,8 +2331,7 @@
         }
     }
 
-    /* finally */
-    Py_XDECREF(posobj);
+finally:
     res = PyObject_CallMethod(self->decoder, "setstate", "(O)", saved_state);
     Py_DECREF(saved_state);
     if (res == NULL)
@@ -2284,8 +2342,7 @@
     cookie.chars_to_skip = Py_SAFE_DOWNCAST(chars_to_skip, Py_ssize_t, int);
     return textiowrapper_build_cookie(&cookie);
 
-  fail:
-    Py_XDECREF(posobj);
+fail:
     if (saved_state) {
         PyObject *type, *value, *traceback;
         PyErr_Fetch(&type, &value, &traceback);
@@ -2323,25 +2380,52 @@
 static PyObject *
 textiowrapper_repr(textio *self)
 {
-    PyObject *nameobj, *res;
+    PyObject *nameobj, *modeobj, *res, *s;
 
     CHECK_INITIALIZED(self);
 
+    res = PyUnicode_FromString("<_io.TextIOWrapper");
+    if (res == NULL)
+        return NULL;
     nameobj = PyObject_GetAttrString((PyObject *) self, "name");
     if (nameobj == NULL) {
         if (PyErr_ExceptionMatches(PyExc_AttributeError))
             PyErr_Clear();
         else
-            return NULL;
-        res = PyUnicode_FromFormat("<_io.TextIOWrapper encoding=%R>",
-                                   self->encoding);
+            goto error;
     }
     else {
-        res = PyUnicode_FromFormat("<_io.TextIOWrapper name=%R encoding=%R>",
-                                   nameobj, self->encoding);
+        s = PyUnicode_FromFormat(" name=%R", nameobj);
         Py_DECREF(nameobj);
+        if (s == NULL)
+            goto error;
+        PyUnicode_AppendAndDel(&res, s);
+        if (res == NULL)
+            return NULL;
+    }
+    modeobj = PyObject_GetAttrString((PyObject *) self, "mode");
+    if (modeobj == NULL) {
+        if (PyErr_ExceptionMatches(PyExc_AttributeError))
+            PyErr_Clear();
+        else
+            goto error;
     }
-    return res;
+    else {
+        s = PyUnicode_FromFormat(" mode=%R", modeobj);
+        Py_DECREF(modeobj);
+        if (s == NULL)
+            goto error;
+        PyUnicode_AppendAndDel(&res, s);
+        if (res == NULL)
+            return NULL;
+    }
+    s = PyUnicode_FromFormat("%U encoding=%R>",
+                             res, self->encoding);
+    Py_DECREF(res);
+    return s;
+error:
+    Py_XDECREF(res);
+    return NULL;
 }
 
 

Modified: python/branches/pep-3151/Modules/_json.c
==============================================================================
--- python/branches/pep-3151/Modules/_json.c	(original)
+++ python/branches/pep-3151/Modules/_json.c	Sat Feb 26 08:16:32 2011
@@ -335,7 +335,7 @@
     PyObject *rval = NULL;
     Py_ssize_t len = PyUnicode_GET_SIZE(pystr);
     Py_ssize_t begin = end - 1;
-    Py_ssize_t next = begin;
+    Py_ssize_t next /* = begin */;
     const Py_UNICODE *buf = PyUnicode_AS_UNICODE(pystr);
     PyObject *chunks = NULL;
     PyObject *chunk = NULL;
@@ -1532,13 +1532,12 @@
             goto bail;
         Py_CLEAR(ident);
     }
+    /* TODO DOES NOT RUN; dead code
     if (s->indent != Py_None) {
-        /* TODO: DOES NOT RUN */
         indent_level -= 1;
-        /*
-            yield '\n' + (' ' * (_indent * _current_indent_level))
-        */
-    }
+
+        yield '\n' + (' ' * (_indent * _current_indent_level))
+    }*/
     if (PyList_Append(rval, close_dict))
         goto bail;
     return 0;
@@ -1624,13 +1623,13 @@
             goto bail;
         Py_CLEAR(ident);
     }
+
+    /* TODO: DOES NOT RUN
     if (s->indent != Py_None) {
-        /* TODO: DOES NOT RUN */
         indent_level -= 1;
-        /*
-            yield '\n' + (' ' * (_indent * _current_indent_level))
-        */
-    }
+
+        yield '\n' + (' ' * (_indent * _current_indent_level))
+    }*/
     if (PyList_Append(rval, close_array))
         goto bail;
     Py_DECREF(s_fast);

Modified: python/branches/pep-3151/Modules/_lsprof.c
==============================================================================
--- python/branches/pep-3151/Modules/_lsprof.c	(original)
+++ python/branches/pep-3151/Modules/_lsprof.c	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,5 @@
 #include "Python.h"
-#include "compile.h"
 #include "frameobject.h"
-#include "structseq.h"
 #include "rotatingtree.h"
 
 #if !defined(HAVE_LONG_LONG)
@@ -180,7 +178,16 @@
         PyObject *mod = fn->m_module;
         const char *modname;
         if (mod && PyUnicode_Check(mod)) {
+            /* XXX: The following will truncate module names with embedded
+             * null-characters.  It is unlikely that this can happen in
+             * practice and the concequences are not serious enough to
+             * introduce extra checks here.
+             */
             modname = _PyUnicode_AsString(mod);
+            if (modname == NULL) {
+                modname = "<encoding error>";
+                PyErr_Clear();
+            }
         }
         else if (mod && PyModule_Check(mod)) {
             modname = PyModule_GetName(mod);

Modified: python/branches/pep-3151/Modules/_multiprocessing/multiprocessing.h
==============================================================================
--- python/branches/pep-3151/Modules/_multiprocessing/multiprocessing.h	(original)
+++ python/branches/pep-3151/Modules/_multiprocessing/multiprocessing.h	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,7 @@
 #define PY_SSIZE_T_CLEAN
 
 #ifdef __sun
-/* The control message API is only available on Solaris 
+/* The control message API is only available on Solaris
    if XPG 4.2 or later is requested. */
 #define _XOPEN_SOURCE 500
 #endif

Modified: python/branches/pep-3151/Modules/_pickle.c
==============================================================================
--- python/branches/pep-3151/Modules/_pickle.c	(original)
+++ python/branches/pep-3151/Modules/_pickle.c	Sat Feb 26 08:16:32 2011
@@ -977,11 +977,6 @@
 {
     Py_ssize_t num_read;
 
-    if (n == 0) {
-        *s = NULL;
-        return 0;
-    }
-
     if (self->next_read_idx + n <= self->input_len) {
         *s = self->input_buffer + self->next_read_idx;
         self->next_read_idx += n;
@@ -2244,19 +2239,21 @@
     if (len != 0) {
         /* Materialize the list elements. */
         if (PyList_CheckExact(obj) && self->proto > 0) {
-            if (Py_EnterRecursiveCall(" while pickling an object") == 0) {
-                status = batch_list_exact(self, obj);
-                Py_LeaveRecursiveCall();
-            }
+            if (Py_EnterRecursiveCall(" while pickling an object"))
+                goto error;
+            status = batch_list_exact(self, obj);
+            Py_LeaveRecursiveCall();
         } else {
             PyObject *iter = PyObject_GetIter(obj);
             if (iter == NULL)
                 goto error;
 
-            if (Py_EnterRecursiveCall(" while pickling an object") == 0) {
-                status = batch_list(self, iter);
-                Py_LeaveRecursiveCall();
+            if (Py_EnterRecursiveCall(" while pickling an object")) {
+                Py_DECREF(iter);
+                goto error;
             }
+            status = batch_list(self, iter);
+            Py_LeaveRecursiveCall();
             Py_DECREF(iter);
         }
     }
@@ -2504,10 +2501,10 @@
         if (PyDict_CheckExact(obj) && self->proto > 0) {
             /* We can take certain shortcuts if we know this is a dict and
                not a dict subclass. */
-            if (Py_EnterRecursiveCall(" while pickling an object") == 0) {
-                status = batch_dict_exact(self, obj);
-                Py_LeaveRecursiveCall();
-            }
+            if (Py_EnterRecursiveCall(" while pickling an object"))
+                goto error;
+            status = batch_dict_exact(self, obj);
+            Py_LeaveRecursiveCall();
         } else {
             items = PyObject_CallMethod(obj, "items", "()");
             if (items == NULL)
@@ -2516,7 +2513,12 @@
             Py_DECREF(items);
             if (iter == NULL)
                 goto error;
+            if (Py_EnterRecursiveCall(" while pickling an object")) {
+                Py_DECREF(iter);
+                goto error;
+            }
             status = batch_dict(self, iter);
+            Py_LeaveRecursiveCall();
             Py_DECREF(iter);
         }
     }
@@ -3044,7 +3046,7 @@
     PyObject *reduce_value = NULL;
     int status = 0;
 
-    if (Py_EnterRecursiveCall(" while pickling an object") < 0)
+    if (Py_EnterRecursiveCall(" while pickling an object"))
         return -1;
 
     /* The extra pers_save argument is necessary to avoid calling save_pers()

Modified: python/branches/pep-3151/Modules/_posixsubprocess.c
==============================================================================
--- python/branches/pep-3151/Modules/_posixsubprocess.c	(original)
+++ python/branches/pep-3151/Modules/_posixsubprocess.c	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,10 @@
 /* Authors: Gregory P. Smith & Jeffrey Yasskin */
 #include "Python.h"
+#ifdef HAVE_PIPE2
+#define _GNU_SOURCE
+#endif
 #include <unistd.h>
+#include <fcntl.h>
 
 
 #define POSIX_CALL(call)   if ((call) == -1) goto error
@@ -42,13 +46,14 @@
                        int errread, int errwrite,
                        int errpipe_read, int errpipe_write,
                        int close_fds, int restore_signals,
-                       int call_setsid,
+                       int call_setsid, Py_ssize_t num_fds_to_keep,
+                       PyObject *py_fds_to_keep,
                        PyObject *preexec_fn,
                        PyObject *preexec_fn_args_tuple)
 {
     int i, saved_errno, fd_num;
     PyObject *result;
-    const char* err_msg;
+    const char* err_msg = "";
     /* Buffer large enough to hold a hex integer.  We can't malloc. */
     char hex_errno[sizeof(saved_errno)*2+1];
 
@@ -64,38 +69,68 @@
     }
     POSIX_CALL(close(errpipe_read));
 
-    /* Dup fds for child. */
-    if (p2cread != -1) {
+    /* Dup fds for child.
+       dup2() removes the CLOEXEC flag but we must do it ourselves if dup2()
+       would be a no-op (issue #10806). */
+    if (p2cread == 0) {
+        int old = fcntl(p2cread, F_GETFD);
+        if (old != -1)
+            fcntl(p2cread, F_SETFD, old & ~FD_CLOEXEC);
+    } else if (p2cread != -1) {
         POSIX_CALL(dup2(p2cread, 0));  /* stdin */
     }
-    if (c2pwrite != -1) {
+    if (c2pwrite == 1) {
+        int old = fcntl(c2pwrite, F_GETFD);
+        if (old != -1)
+            fcntl(c2pwrite, F_SETFD, old & ~FD_CLOEXEC);
+    } else if (c2pwrite != -1) {
         POSIX_CALL(dup2(c2pwrite, 1));  /* stdout */
     }
-    if (errwrite != -1) {
+    if (errwrite == 2) {
+        int old = fcntl(errwrite, F_GETFD);
+        if (old != -1)
+            fcntl(errwrite, F_SETFD, old & ~FD_CLOEXEC);
+    } else if (errwrite != -1) {
         POSIX_CALL(dup2(errwrite, 2));  /* stderr */
     }
 
     /* Close pipe fds.  Make sure we don't close the same fd more than */
     /* once, or standard fds. */
-    if (p2cread != -1 && p2cread != 0) {
+    if (p2cread > 2) {
         POSIX_CALL(close(p2cread));
     }
-    if (c2pwrite != -1 && c2pwrite != p2cread && c2pwrite != 1) {
+    if (c2pwrite > 2) {
         POSIX_CALL(close(c2pwrite));
     }
-    if (errwrite != -1 && errwrite != p2cread &&
-        errwrite != c2pwrite && errwrite != 2) {
+    if (errwrite != c2pwrite && errwrite > 2) {
         POSIX_CALL(close(errwrite));
     }
 
     /* close() is intentionally not checked for errors here as we are closing */
     /* a large range of fds, some of which may be invalid. */
     if (close_fds) {
-        for (fd_num = 3; fd_num < errpipe_write; ++fd_num) {
-            close(fd_num);
-        }
-        for (fd_num = errpipe_write+1; fd_num < max_fd; ++fd_num) {
-            close(fd_num);
+        Py_ssize_t keep_seq_idx;
+        int start_fd = 3;
+        for (keep_seq_idx = 0; keep_seq_idx < num_fds_to_keep; ++keep_seq_idx) {
+            PyObject* py_keep_fd = PySequence_Fast_GET_ITEM(py_fds_to_keep,
+                                                            keep_seq_idx);
+            int keep_fd = PyLong_AsLong(py_keep_fd);
+            if (keep_fd < 0) {  /* Negative number, overflow or not a Long. */
+                err_msg = "bad value in fds_to_keep.";
+                errno = 0;  /* We don't want to report an OSError. */
+                goto error;
+            }
+            if (keep_fd < start_fd)
+                continue;
+            for (fd_num = start_fd; fd_num < keep_fd; ++fd_num) {
+                close(fd_num);
+            }
+            start_fd = keep_fd + 1;
+        }
+        if (start_fd <= max_fd) {
+            for (fd_num = start_fd; fd_num < max_fd; ++fd_num) {
+                close(fd_num);
+            }
         }
     }
 
@@ -170,7 +205,7 @@
 subprocess_fork_exec(PyObject* self, PyObject *args)
 {
     PyObject *gc_module = NULL;
-    PyObject *executable_list, *py_close_fds;
+    PyObject *executable_list, *py_close_fds, *py_fds_to_keep;
     PyObject *env_list, *preexec_fn;
     PyObject *process_args, *converted_args = NULL, *fast_args = NULL;
     PyObject *preexec_fn_args_tuple = NULL;
@@ -182,11 +217,11 @@
     pid_t pid;
     int need_to_reenable_gc = 0;
     char *const *exec_array, *const *argv = NULL, *const *envp = NULL;
-    Py_ssize_t arg_num;
+    Py_ssize_t arg_num, num_fds_to_keep;
 
     if (!PyArg_ParseTuple(
-            args, "OOOOOiiiiiiiiiiO:fork_exec",
-            &process_args, &executable_list, &py_close_fds,
+            args, "OOOOOOiiiiiiiiiiO:fork_exec",
+            &process_args, &executable_list, &py_close_fds, &py_fds_to_keep,
             &cwd_obj, &env_list,
             &p2cread, &p2cwrite, &c2pread, &c2pwrite,
             &errread, &errwrite, &errpipe_read, &errpipe_write,
@@ -198,6 +233,11 @@
         PyErr_SetString(PyExc_ValueError, "errpipe_write must be >= 3");
         return NULL;
     }
+    num_fds_to_keep = PySequence_Length(py_fds_to_keep);
+    if (num_fds_to_keep < 0) {
+        PyErr_SetString(PyExc_ValueError, "bad fds_to_keep");
+        return NULL;
+    }
 
     /* We need to call gc.disable() when we'll be calling preexec_fn */
     if (preexec_fn != Py_None) {
@@ -298,6 +338,7 @@
                    p2cread, p2cwrite, c2pread, c2pwrite,
                    errread, errwrite, errpipe_read, errpipe_write,
                    close_fds, restore_signals, call_setsid,
+                   num_fds_to_keep, py_fds_to_keep,
                    preexec_fn, preexec_fn_args_tuple);
         _exit(255);
         return NULL;  /* Dead code to avoid a potential compiler warning. */
@@ -374,6 +415,57 @@
 Raises: Only on an error in the parent process.\n\
 ");
 
+PyDoc_STRVAR(subprocess_cloexec_pipe_doc,
+"cloexec_pipe() -> (read_end, write_end)\n\n\
+Create a pipe whose ends have the cloexec flag set.");
+
+static PyObject *
+subprocess_cloexec_pipe(PyObject *self, PyObject *noargs)
+{
+    int fds[2];
+    int res;
+#ifdef HAVE_PIPE2
+    Py_BEGIN_ALLOW_THREADS
+    res = pipe2(fds, O_CLOEXEC);
+    Py_END_ALLOW_THREADS
+    if (res != 0 && errno == ENOSYS)
+    {
+        if (PyErr_WarnEx(
+                PyExc_RuntimeWarning,
+                "pipe2 set errno ENOSYS; falling "
+                "back to non-atomic pipe+fcntl.", 1) != 0) {
+            return NULL;
+        }
+        {
+#endif
+        /* We hold the GIL which offers some protection from other code calling
+         * fork() before the CLOEXEC flags have been set but we can't guarantee
+         * anything without pipe2(). */
+        long oldflags;
+
+        res = pipe(fds);
+
+        if (res == 0) {
+            oldflags = fcntl(fds[0], F_GETFD, 0);
+            if (oldflags < 0) res = oldflags;
+        }
+        if (res == 0)
+            res = fcntl(fds[0], F_SETFD, oldflags | FD_CLOEXEC);
+
+        if (res == 0) {
+            oldflags = fcntl(fds[1], F_GETFD, 0);
+            if (oldflags < 0) res = oldflags;
+        }
+        if (res == 0)
+            res = fcntl(fds[1], F_SETFD, oldflags | FD_CLOEXEC);
+#ifdef HAVE_PIPE2
+        }
+    }
+#endif
+    if (res != 0)
+        return PyErr_SetFromErrno(PyExc_OSError);
+    return Py_BuildValue("(ii)", fds[0], fds[1]);
+}
 
 /* module level code ********************************************************/
 
@@ -383,6 +475,7 @@
 
 static PyMethodDef module_methods[] = {
     {"fork_exec", subprocess_fork_exec, METH_VARARGS, subprocess_fork_exec_doc},
+    {"cloexec_pipe", subprocess_cloexec_pipe, METH_NOARGS, subprocess_cloexec_pipe_doc},
     {NULL, NULL}  /* sentinel */
 };
 

Modified: python/branches/pep-3151/Modules/_sqlite/connection.c
==============================================================================
--- python/branches/pep-3151/Modules/_sqlite/connection.c	(original)
+++ python/branches/pep-3151/Modules/_sqlite/connection.c	Sat Feb 26 08:16:32 2011
@@ -673,7 +673,6 @@
 {
     PyObject* function_result = NULL;
     PyObject** aggregate_instance;
-    PyObject* aggregate_class;
 
 #ifdef WITH_THREAD
     PyGILState_STATE threadstate;
@@ -681,8 +680,6 @@
     threadstate = PyGILState_Ensure();
 #endif
 
-    aggregate_class = (PyObject*)sqlite3_user_data(context);
-
     aggregate_instance = (PyObject**)sqlite3_aggregate_context(context, sizeof(PyObject*));
     if (!*aggregate_instance) {
         /* this branch is executed if there was an exception in the aggregate's

Modified: python/branches/pep-3151/Modules/_sqlite/cursor.c
==============================================================================
--- python/branches/pep-3151/Modules/_sqlite/cursor.c	(original)
+++ python/branches/pep-3151/Modules/_sqlite/cursor.c	Sat Feb 26 08:16:32 2011
@@ -126,11 +126,9 @@
 
 static void pysqlite_cursor_dealloc(pysqlite_Cursor* self)
 {
-    int rc;
-
     /* Reset the statement if the user has not closed the cursor */
     if (self->statement) {
-        rc = pysqlite_statement_reset(self->statement);
+        pysqlite_statement_reset(self->statement);
         Py_DECREF(self->statement);
     }
 
@@ -529,7 +527,7 @@
 
     if (self->statement != NULL) {
         /* There is an active statement */
-        rc = pysqlite_statement_reset(self->statement);
+        pysqlite_statement_reset(self->statement);
     }
 
     operation_cstr = _PyUnicode_AsStringAndSize(operation, &operation_len);
@@ -734,7 +732,7 @@
         }
 
         if (multiple) {
-            rc = pysqlite_statement_reset(self->statement);
+            pysqlite_statement_reset(self->statement);
         }
         Py_XDECREF(parameters);
     }

Modified: python/branches/pep-3151/Modules/_sqlite/module.c
==============================================================================
--- python/branches/pep-3151/Modules/_sqlite/module.c	(original)
+++ python/branches/pep-3151/Modules/_sqlite/module.c	Sat Feb 26 08:16:32 2011
@@ -329,7 +329,7 @@
         (pysqlite_statement_setup_types() < 0) ||
         (pysqlite_prepare_protocol_setup_types() < 0)
        ) {
-        Py_DECREF(module);
+        Py_XDECREF(module);
         return NULL;
     }
 

Modified: python/branches/pep-3151/Modules/_sqlite/statement.c
==============================================================================
--- python/branches/pep-3151/Modules/_sqlite/statement.c	(original)
+++ python/branches/pep-3151/Modules/_sqlite/statement.c	Sat Feb 26 08:16:32 2011
@@ -369,11 +369,9 @@
 
 void pysqlite_statement_dealloc(pysqlite_Statement* self)
 {
-    int rc;
-
     if (self->st) {
         Py_BEGIN_ALLOW_THREADS
-        rc = sqlite3_finalize(self->st);
+        sqlite3_finalize(self->st);
         Py_END_ALLOW_THREADS
     }
 

Modified: python/branches/pep-3151/Modules/_ssl.c
==============================================================================
--- python/branches/pep-3151/Modules/_ssl.c	(original)
+++ python/branches/pep-3151/Modules/_ssl.c	Sat Feb 26 08:16:32 2011
@@ -354,7 +354,6 @@
 
     /* Actually negotiate SSL connection */
     /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
-    sockstate = 0;
     do {
         PySSL_BEGIN_ALLOW_THREADS
         ret = SSL_do_handshake(self->ssl);
@@ -370,7 +369,7 @@
             sockstate = SOCKET_OPERATION_OK;
         }
         if (sockstate == SOCKET_HAS_TIMED_OUT) {
-            PyErr_SetString(PySSLErrorObject,
+            PyErr_SetString(PySocketModule.timeout_error,
                             ERRSTR("The handshake operation timed out"));
             goto error;
         } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
@@ -928,10 +927,10 @@
     char *cipher_protocol;
 
     if (self->ssl == NULL)
-        return Py_None;
+        Py_RETURN_NONE;
     current = SSL_get_current_cipher(self->ssl);
     if (current == NULL)
-        return Py_None;
+        Py_RETURN_NONE;
 
     retval = PyTuple_New(3);
     if (retval == NULL)
@@ -939,6 +938,7 @@
 
     cipher_name = (char *) SSL_CIPHER_get_name(current);
     if (cipher_name == NULL) {
+        Py_INCREF(Py_None);
         PyTuple_SET_ITEM(retval, 0, Py_None);
     } else {
         v = PyUnicode_FromString(cipher_name);
@@ -948,6 +948,7 @@
     }
     cipher_protocol = SSL_CIPHER_get_version(current);
     if (cipher_protocol == NULL) {
+        Py_INCREF(Py_None);
         PyTuple_SET_ITEM(retval, 1, Py_None);
     } else {
         v = PyUnicode_FromString(cipher_protocol);
@@ -1075,7 +1076,7 @@
 
     sockstate = check_socket_and_wait_for_timeout(sock, 1);
     if (sockstate == SOCKET_HAS_TIMED_OUT) {
-        PyErr_SetString(PySSLErrorObject,
+        PyErr_SetString(PySocketModule.timeout_error,
                         "The write operation timed out");
         goto error;
     } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
@@ -1088,7 +1089,6 @@
         goto error;
     }
     do {
-        err = 0;
         PySSL_BEGIN_ALLOW_THREADS
         len = SSL_write(self->ssl, buf.buf, buf.len);
         err = SSL_get_error(self->ssl, len);
@@ -1104,7 +1104,7 @@
             sockstate = SOCKET_OPERATION_OK;
         }
         if (sockstate == SOCKET_HAS_TIMED_OUT) {
-            PyErr_SetString(PySSLErrorObject,
+            PyErr_SetString(PySocketModule.timeout_error,
                             "The write operation timed out");
             goto error;
         } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
@@ -1211,7 +1211,7 @@
     if (!count) {
         sockstate = check_socket_and_wait_for_timeout(sock, 0);
         if (sockstate == SOCKET_HAS_TIMED_OUT) {
-            PyErr_SetString(PySSLErrorObject,
+            PyErr_SetString(PySocketModule.timeout_error,
                             "The read operation timed out");
             goto error;
         } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
@@ -1224,7 +1224,6 @@
         }
     }
     do {
-        err = 0;
         PySSL_BEGIN_ALLOW_THREADS
         count = SSL_read(self->ssl, mem, len);
         err = SSL_get_error(self->ssl, count);
@@ -1245,7 +1244,7 @@
             sockstate = SOCKET_OPERATION_OK;
         }
         if (sockstate == SOCKET_HAS_TIMED_OUT) {
-            PyErr_SetString(PySSLErrorObject,
+            PyErr_SetString(PySocketModule.timeout_error,
                             "The read operation timed out");
             goto error;
         } else if (sockstate == SOCKET_IS_NONBLOCKING) {
@@ -1340,10 +1339,10 @@
             break;
         if (sockstate == SOCKET_HAS_TIMED_OUT) {
             if (ssl_err == SSL_ERROR_WANT_READ)
-                PyErr_SetString(PySSLErrorObject,
+                PyErr_SetString(PySocketModule.timeout_error,
                                 "The read operation timed out");
             else
-                PyErr_SetString(PySSLErrorObject,
+                PyErr_SetString(PySocketModule.timeout_error,
                                 "The write operation timed out");
             goto error;
         }
@@ -1681,7 +1680,7 @@
         return NULL;
     }
     if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
-        Py_DECREF(cafile_bytes);
+        Py_XDECREF(cafile_bytes);
         PyErr_SetString(PyExc_TypeError,
                         "capath should be a valid filesystem path");
         return NULL;
@@ -1783,6 +1782,16 @@
     return NULL;
 }
 
+static PyObject *
+set_default_verify_paths(PySSLContext *self, PyObject *unused)
+{
+    if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
+        _setSSLError(NULL, 0, __FILE__, __LINE__);
+        return NULL;
+    }
+    Py_RETURN_NONE;
+}
+
 static PyGetSetDef context_getsetlist[] = {
     {"options", (getter) get_options,
                 (setter) set_options, NULL},
@@ -1802,6 +1811,8 @@
                               METH_VARARGS | METH_KEYWORDS, NULL},
     {"session_stats", (PyCFunction) session_stats,
                       METH_NOARGS, NULL},
+    {"set_default_verify_paths", (PyCFunction) set_default_verify_paths,
+                                 METH_NOARGS, NULL},
     {NULL, NULL}        /* sentinel */
 };
 

Modified: python/branches/pep-3151/Modules/_struct.c
==============================================================================
--- python/branches/pep-3151/Modules/_struct.c	(original)
+++ python/branches/pep-3151/Modules/_struct.c	Sat Feb 26 08:16:32 2011
@@ -6,7 +6,6 @@
 #define PY_SSIZE_T_CLEAN
 
 #include "Python.h"
-#include "structseq.h"
 #include "structmember.h"
 #include <ctype.h>
 
@@ -463,14 +462,9 @@
 static int
 np_char(char *p, PyObject *v, const formatdef *f)
 {
-    if (PyUnicode_Check(v)) {
-        v = _PyUnicode_AsDefaultEncodedString(v, NULL);
-        if (v == NULL)
-            return -1;
-    }
     if (!PyBytes_Check(v) || PyBytes_Size(v) != 1) {
         PyErr_SetString(StructError,
-                        "char format requires bytes or string of length 1");
+                        "char format requires a bytes object of length 1");
         return -1;
     }
     *p = *PyBytes_AsString(v);
@@ -1346,7 +1340,7 @@
     if (!PyBytes_Check(o_format)) {
         Py_DECREF(o_format);
         PyErr_Format(PyExc_TypeError,
-                     "Struct() argument 1 must be bytes, not %.200s",
+                     "Struct() argument 1 must be a bytes object, not %.200s",
                      Py_TYPE(o_format)->tp_name);
         return -1;
     }
@@ -1424,7 +1418,7 @@
         return NULL;
     if (vbuf.len != soself->s_size) {
         PyErr_Format(StructError,
-                     "unpack requires a bytes argument of length %zd",
+                     "unpack requires a bytes object of length %zd",
                      soself->s_size);
         PyBuffer_Release(&vbuf);
         return NULL;
@@ -1504,15 +1498,10 @@
         if (e->format == 's') {
             int isstring;
             void *p;
-            if (PyUnicode_Check(v)) {
-                v = _PyUnicode_AsDefaultEncodedString(v, NULL);
-                if (v == NULL)
-                    return -1;
-            }
             isstring = PyBytes_Check(v);
             if (!isstring && !PyByteArray_Check(v)) {
                 PyErr_SetString(StructError,
-                                "argument for 's' must be a bytes or string");
+                                "argument for 's' must be a bytes object");
                 return -1;
             }
             if (isstring) {
@@ -1530,15 +1519,10 @@
         } else if (e->format == 'p') {
             int isstring;
             void *p;
-            if (PyUnicode_Check(v)) {
-                v = _PyUnicode_AsDefaultEncodedString(v, NULL);
-                if (v == NULL)
-                    return -1;
-            }
             isstring = PyBytes_Check(v);
             if (!isstring && !PyByteArray_Check(v)) {
                 PyErr_SetString(StructError,
-                                "argument for 'p' must be a bytes or string");
+                                "argument for 'p' must be a bytes object");
                 return -1;
             }
             if (isstring) {
@@ -1692,7 +1676,7 @@
     {NULL,       NULL}          /* sentinel */
 };
 
-PyDoc_STRVAR(s__doc__, 
+PyDoc_STRVAR(s__doc__,
 "Struct(fmt) --> compiled struct object\n"
 "\n"
 "Return a new Struct object which writes and reads binary data according to\n"

Modified: python/branches/pep-3151/Modules/_testcapimodule.c
==============================================================================
--- python/branches/pep-3151/Modules/_testcapimodule.c	(original)
+++ python/branches/pep-3151/Modules/_testcapimodule.c	Sat Feb 26 08:16:32 2011
@@ -1398,7 +1398,7 @@
     if (buffer == NULL)
         return PyErr_NoMemory();
 
-    size = PyUnicode_AsWideChar((PyUnicodeObject*)unicode, buffer, buflen);
+    size = PyUnicode_AsWideChar(unicode, buffer, buflen);
     if (size == -1) {
         PyMem_Free(buffer);
         return NULL;
@@ -1741,15 +1741,16 @@
 {
     PyObject *result;
     char *msg;
+    static const Py_UNICODE one[] = {'1', 0};
 
-#define CHECK_1_FORMAT(FORMAT, TYPE)                    \
-    result = PyUnicode_FromFormat(FORMAT, (TYPE)1);     \
-    if (result == NULL)                                 \
-        return NULL;                                    \
-    if (strcmp(_PyUnicode_AsString(result), "1")) {     \
-        msg = FORMAT " failed at 1";                    \
-        goto Fail;                                      \
-    }                                                   \
+#define CHECK_1_FORMAT(FORMAT, TYPE)                                \
+    result = PyUnicode_FromFormat(FORMAT, (TYPE)1);                 \
+    if (result == NULL)                                             \
+        return NULL;                                                \
+    if (Py_UNICODE_strcmp(PyUnicode_AS_UNICODE(result), one)) {     \
+        msg = FORMAT " failed at 1";                                \
+        goto Fail;                                                  \
+    }                                                               \
     Py_DECREF(result)
 
     CHECK_1_FORMAT("%d", int);
@@ -2187,7 +2188,7 @@
             /* argument converter not called? */
             return NULL;
         /* Should be 1 */
-        res = PyLong_FromLong(Py_REFCNT(str2));
+        res = PyLong_FromSsize_t(Py_REFCNT(str2));
         Py_DECREF(str2);
         PyErr_Clear();
         return res;
@@ -2230,6 +2231,15 @@
     return PyErr_NewExceptionWithDoc(name, doc, base, dict);
 }
 
+static PyObject *
+make_memoryview_from_NULL_pointer(PyObject *self)
+{
+    Py_buffer info;
+    if (PyBuffer_FillInfo(&info, NULL, NULL, 1, 1, PyBUF_FULL_RO) < 0)
+        return NULL;
+    return PyMemoryView_FromBuffer(&info);
+}
+
 /* Test that the fatal error from not having a current thread doesn't
    cause an infinite loop.  Run via Lib/test/test_capi.py */
 static PyObject *
@@ -2245,17 +2255,6 @@
     return NULL;
 }
 
-static PyObject *
-format_unicode(PyObject *self, PyObject *args)
-{
-    const char *format;
-    PyObject *arg;
-    if (!PyArg_ParseTuple(args, "yU", &format, &arg))
-        return NULL;
-    return PyUnicode_FromFormat(format, arg);
-
-}
-
 static PyMethodDef TestMethods[] = {
     {"raise_exception",         raise_exception,                 METH_VARARGS},
     {"raise_memoryerror",   (PyCFunction)raise_memoryerror,  METH_NOARGS},
@@ -2336,8 +2335,9 @@
     {"code_newempty",           code_newempty,                   METH_VARARGS},
     {"make_exception_with_doc", (PyCFunction)make_exception_with_doc,
      METH_VARARGS | METH_KEYWORDS},
+    {"make_memoryview_from_NULL_pointer", (PyCFunction)make_memoryview_from_NULL_pointer,
+     METH_NOARGS},
     {"crash_no_current_thread", (PyCFunction)crash_no_current_thread, METH_NOARGS},
-    {"format_unicode",          format_unicode,                 METH_VARARGS},
     {NULL, NULL} /* sentinel */
 };
 

Modified: python/branches/pep-3151/Modules/_threadmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/_threadmodule.c	(original)
+++ python/branches/pep-3151/Modules/_threadmodule.c	Sat Feb 26 08:16:32 2011
@@ -40,6 +40,59 @@
     PyObject_Del(self);
 }
 
+/* Helper to acquire an interruptible lock with a timeout.  If the lock acquire
+ * is interrupted, signal handlers are run, and if they raise an exception,
+ * PY_LOCK_INTR is returned.  Otherwise, PY_LOCK_ACQUIRED or PY_LOCK_FAILURE
+ * are returned, depending on whether the lock can be acquired withing the
+ * timeout.
+ */
+static PyLockStatus
+acquire_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds)
+{
+    PyLockStatus r;
+    _PyTime_timeval curtime;
+    _PyTime_timeval endtime;
+
+
+    _PyTime_gettimeofday(&endtime);
+    if (microseconds > 0) {
+        endtime.tv_sec += microseconds / (1000 * 1000);
+        endtime.tv_usec += microseconds % (1000 * 1000);
+    }
+
+
+    do {
+        Py_BEGIN_ALLOW_THREADS
+        r = PyThread_acquire_lock_timed(lock, microseconds, 1);
+        Py_END_ALLOW_THREADS
+
+        if (r == PY_LOCK_INTR) {
+            /* Run signal handlers if we were interrupted.  Propagate
+             * exceptions from signal handlers, such as KeyboardInterrupt, by
+             * passing up PY_LOCK_INTR.  */
+            if (Py_MakePendingCalls() < 0) {
+                return PY_LOCK_INTR;
+            }
+
+            /* If we're using a timeout, recompute the timeout after processing
+             * signals, since those can take time.  */
+            if (microseconds >= 0) {
+                _PyTime_gettimeofday(&curtime);
+                microseconds = ((endtime.tv_sec - curtime.tv_sec) * 1000000 +
+                                (endtime.tv_usec - curtime.tv_usec));
+
+                /* Check for negative values, since those mean block forever.
+                 */
+                if (microseconds <= 0) {
+                    r = PY_LOCK_FAILURE;
+                }
+            }
+        }
+    } while (r == PY_LOCK_INTR);  /* Retry if we were interrupted. */
+
+    return r;
+}
+
 static PyObject *
 lock_PyThread_acquire_lock(lockobject *self, PyObject *args, PyObject *kwds)
 {
@@ -47,7 +100,7 @@
     int blocking = 1;
     double timeout = -1;
     PY_TIMEOUT_T microseconds;
-    int r;
+    PyLockStatus r;
 
     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist,
                                      &blocking, &timeout))
@@ -77,11 +130,12 @@
         microseconds = (PY_TIMEOUT_T) timeout;
     }
 
-    Py_BEGIN_ALLOW_THREADS
-    r = PyThread_acquire_lock_timed(self->lock_lock, microseconds);
-    Py_END_ALLOW_THREADS
+    r = acquire_timed(self->lock_lock, microseconds);
+    if (r == PY_LOCK_INTR) {
+        return NULL;
+    }
 
-    return PyBool_FromLong(r);
+    return PyBool_FromLong(r == PY_LOCK_ACQUIRED);
 }
 
 PyDoc_STRVAR(acquire_doc,
@@ -93,7 +147,7 @@
 the lock, and return None once the lock is acquired.\n\
 With an argument, this will only block if the argument is true,\n\
 and the return value reflects whether the lock is acquired.\n\
-The blocking operation is not interruptible.");
+The blocking operation is interruptible.");
 
 static PyObject *
 lock_PyThread_release_lock(lockobject *self)
@@ -218,7 +272,7 @@
     double timeout = -1;
     PY_TIMEOUT_T microseconds;
     long tid;
-    int r = 1;
+    PyLockStatus r = PY_LOCK_ACQUIRED;
 
     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|id:acquire", kwlist,
                                      &blocking, &timeout))
@@ -265,17 +319,18 @@
         if (microseconds == 0) {
             Py_RETURN_FALSE;
         }
-        Py_BEGIN_ALLOW_THREADS
-        r = PyThread_acquire_lock_timed(self->rlock_lock, microseconds);
-        Py_END_ALLOW_THREADS
+        r = acquire_timed(self->rlock_lock, microseconds);
     }
-    if (r) {
+    if (r == PY_LOCK_ACQUIRED) {
         assert(self->rlock_count == 0);
         self->rlock_owner = tid;
         self->rlock_count = 1;
     }
+    else if (r == PY_LOCK_INTR) {
+        return NULL;
+    }
 
-    return PyBool_FromLong(r);
+    return PyBool_FromLong(r == PY_LOCK_ACQUIRED);
 }
 
 PyDoc_STRVAR(rlock_acquire_doc,
@@ -287,7 +342,7 @@
 immediately.  If `blocking` is True and another thread holds\n\
 the lock, the method will wait for the lock to be released,\n\
 take it and then return True.\n\
-(note: the blocking operation is not interruptible.)\n\
+(note: the blocking operation is interruptible.)\n\
 \n\
 In all other cases, the method will return True immediately.\n\
 Precisely, if the current thread already holds the lock, its\n\

Modified: python/branches/pep-3151/Modules/_tkinter.c
==============================================================================
--- python/branches/pep-3151/Modules/_tkinter.c	(original)
+++ python/branches/pep-3151/Modules/_tkinter.c	Sat Feb 26 08:16:32 2011
@@ -2005,7 +2005,7 @@
 PythonCmd(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[])
 {
     PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
-    PyObject *self, *func, *arg, *res;
+    PyObject *func, *arg, *res;
     int i, rv;
     Tcl_Obj *obj_res;
 
@@ -2014,7 +2014,6 @@
     /* TBD: no error checking here since we know, via the
      * Tkapp_CreateCommand() that the client data is a two-tuple
      */
-    self = data->self;
     func = data->func;
 
     /* Create argument list (argv1, ..., argvN) */

Modified: python/branches/pep-3151/Modules/arraymodule.c
==============================================================================
--- python/branches/pep-3151/Modules/arraymodule.c	(original)
+++ python/branches/pep-3151/Modules/arraymodule.c	Sat Feb 26 08:16:32 2011
@@ -674,11 +674,9 @@
 static PyObject *
 array_repeat(arrayobject *a, Py_ssize_t n)
 {
-    Py_ssize_t i;
     Py_ssize_t size;
     arrayobject *np;
-    char *p;
-    Py_ssize_t nbytes;
+    Py_ssize_t oldbytes, newbytes;
     if (n < 0)
         n = 0;
     if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
@@ -688,13 +686,23 @@
     np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
     if (np == NULL)
         return NULL;
-    p = np->ob_item;
-    nbytes = Py_SIZE(a) * a->ob_descr->itemsize;
-    for (i = 0; i < n; i++) {
-        memcpy(p, a->ob_item, nbytes);
-        p += nbytes;
+    if (n == 0)
+        return (PyObject *)np;
+    oldbytes = Py_SIZE(a) * a->ob_descr->itemsize;
+    newbytes = oldbytes * n;
+    /* this follows the code in unicode_repeat */
+    if (oldbytes == 1) {
+        memset(np->ob_item, a->ob_item[0], newbytes);
+    } else {
+        Py_ssize_t done = oldbytes;
+        Py_MEMCPY(np->ob_item, a->ob_item, oldbytes);
+        while (done < newbytes) {
+            Py_ssize_t ncopy = (done <= newbytes-done) ? done : newbytes-done;
+            Py_MEMCPY(np->ob_item+done, np->ob_item, ncopy);
+            done += ncopy;
+        }
     }
-    return (PyObject *) np;
+    return (PyObject *)np;
 }
 
 static int
@@ -868,7 +876,6 @@
     if (Py_SIZE(self) > 0) {
         if (n < 0)
             n = 0;
-        items = self->ob_item;
         if ((self->ob_descr->itemsize != 0) &&
             (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
             return PyErr_NoMemory();
@@ -1448,7 +1455,7 @@
 {
     Py_UNICODE *ustr;
     Py_ssize_t n;
-    char typecode;
+    Py_UNICODE typecode;
 
     if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n))
         return NULL;
@@ -1483,7 +1490,7 @@
 static PyObject *
 array_tounicode(arrayobject *self, PyObject *unused)
 {
-    char typecode;
+    Py_UNICODE typecode;
     typecode = self->ob_descr->typecode;
     if ((typecode != 'u')) {
         PyErr_SetString(PyExc_ValueError,
@@ -2002,8 +2009,8 @@
 static PyObject *
 array_get_typecode(arrayobject *a, void *closure)
 {
-    char tc = a->ob_descr->typecode;
-    return PyUnicode_FromStringAndSize(&tc, 1);
+    Py_UNICODE tc = a->ob_descr->typecode;
+    return PyUnicode_FromUnicode(&tc, 1);
 }
 
 static PyObject *
@@ -2075,21 +2082,21 @@
 static PyObject *
 array_repr(arrayobject *a)
 {
-    char typecode;
+    Py_UNICODE typecode;
     PyObject *s, *v = NULL;
     Py_ssize_t len;
 
     len = Py_SIZE(a);
     typecode = a->ob_descr->typecode;
     if (len == 0) {
-        return PyUnicode_FromFormat("array('%c')", typecode);
+        return PyUnicode_FromFormat("array('%c')", (int)typecode);
     }
     if ((typecode == 'u'))
         v = array_tounicode(a, NULL);
     else
         v = array_tolist(a, NULL);
 
-    s = PyUnicode_FromFormat("array('%c', %R)", typecode, v);
+    s = PyUnicode_FromFormat("array('%c', %R)", (int)typecode, v);
     Py_DECREF(v);
     return s;
 }
@@ -2112,7 +2119,7 @@
         arrayobject* ar;
         int itemsize = self->ob_descr->itemsize;
 
-        if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
+        if (PySlice_GetIndicesEx(item, Py_SIZE(self),
                          &start, &stop, &step, &slicelength) < 0) {
             return NULL;
         }
@@ -2183,7 +2190,7 @@
             return (*self->ob_descr->setitem)(self, i, value);
     }
     else if (PySlice_Check(item)) {
-        if (PySlice_GetIndicesEx((PySliceObject *)item,
+        if (PySlice_GetIndicesEx(item,
                                  Py_SIZE(self), &start, &stop,
                                  &step, &slicelength) < 0) {
             return -1;
@@ -2397,7 +2404,9 @@
           || PyByteArray_Check(initial)
           || PyBytes_Check(initial)
           || PyTuple_Check(initial)
-          || ((c=='u') && PyUnicode_Check(initial)))) {
+          || ((c=='u') && PyUnicode_Check(initial))
+          || (array_Check(initial)
+              && c == ((arrayobject*)initial)->ob_descr->typecode))) {
         it = PyObject_GetIter(initial);
         if (it == NULL)
             return NULL;
@@ -2413,17 +2422,20 @@
             PyObject *a;
             Py_ssize_t len;
 
-            if (initial == NULL || !(PyList_Check(initial)
-                || PyTuple_Check(initial)))
+            if (initial == NULL)
                 len = 0;
+            else if (PyList_Check(initial))
+                len = PyList_GET_SIZE(initial);
+            else if (PyTuple_Check(initial) || array_Check(initial))
+                len = Py_SIZE(initial);
             else
-                len = PySequence_Size(initial);
+                len = 0;
 
             a = newarrayobject(type, len, descr);
             if (a == NULL)
                 return NULL;
 
-            if (len > 0) {
+            if (len > 0 && !array_Check(initial)) {
                 Py_ssize_t i;
                 for (i = 0; i < len; i++) {
                     PyObject *v =
@@ -2474,6 +2486,11 @@
                     self->allocated = Py_SIZE(self);
                 }
             }
+            else if (initial != NULL && array_Check(initial)) {
+                arrayobject *self = (arrayobject *)a;
+                arrayobject *other = (arrayobject *)initial;
+                memcpy(self->ob_item, other->ob_item, len * other->ob_descr->itemsize);
+            }
             if (it != NULL) {
                 if (array_iter_extend((arrayobject *)a, it) == -1) {
                     Py_DECREF(it);

Modified: python/branches/pep-3151/Modules/atexitmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/atexitmodule.c	(original)
+++ python/branches/pep-3151/Modules/atexitmodule.c	Sat Feb 26 08:16:32 2011
@@ -72,6 +72,7 @@
             PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
             if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
                 PySys_WriteStderr("Error in atexit._run_exitfuncs:\n");
+                PyErr_NormalizeException(&exc_type, &exc_value, &exc_tb);
                 PyErr_Display(exc_type, exc_value, exc_tb);
             }
         }

Modified: python/branches/pep-3151/Modules/audioop.c
==============================================================================
--- python/branches/pep-3151/Modules/audioop.c	(original)
+++ python/branches/pep-3151/Modules/audioop.c	Sat Feb 26 08:16:32 2011
@@ -309,7 +309,7 @@
 }
 
 static int
-audioop_check_parameters(int len, int size)
+audioop_check_parameters(Py_ssize_t len, int size)
 {
     if (!audioop_check_size(size))
         return 0;
@@ -513,7 +513,6 @@
 
     best_result = result;
     best_j = 0;
-    j = 0;
 
     for ( j=1; j<=len1-len2; j++) {
         aj_m1 = (double)cp1[j-1];
@@ -599,7 +598,6 @@
 
     best_result = result;
     best_j = 0;
-    j = 0;
 
     for ( j=1; j<=len1-len2; j++) {
         aj_m1 = (double)cp1[j-1];
@@ -1433,7 +1431,6 @@
     if ( state == Py_None ) {
         /* First time, it seems. Set defaults */
         valpred = 0;
-        step = 7;
         index = 0;
     } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
         return 0;
@@ -1534,7 +1531,6 @@
     if ( state == Py_None ) {
         /* First time, it seems. Set defaults */
         valpred = 0;
-        step = 7;
         index = 0;
     } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
         return 0;

Modified: python/branches/pep-3151/Modules/cjkcodecs/_codecs_iso2022.c
==============================================================================
--- python/branches/pep-3151/Modules/cjkcodecs/_codecs_iso2022.c	(original)
+++ python/branches/pep-3151/Modules/cjkcodecs/_codecs_iso2022.c	Sat Feb 26 08:16:32 2011
@@ -123,7 +123,7 @@
 
 CODEC_INIT(iso2022)
 {
-    const struct iso2022_designation *desig = CONFIG_DESIGNATIONS;
+    const struct iso2022_designation *desig;
     for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++)
         if (desig->initializer != NULL && desig->initializer() != 0)
             return -1;

Modified: python/branches/pep-3151/Modules/cjkcodecs/multibytecodec.c
==============================================================================
--- python/branches/pep-3151/Modules/cjkcodecs/multibytecodec.c	(original)
+++ python/branches/pep-3151/Modules/cjkcodecs/multibytecodec.c	Sat Feb 26 08:16:32 2011
@@ -483,6 +483,7 @@
         return PyBytes_FromStringAndSize(NULL, 0);
 
     buf.excobj = NULL;
+    buf.outobj = NULL;
     buf.inbuf = buf.inbuf_top = *data;
     buf.inbuf_end = buf.inbuf_top + datalen;
 

Deleted: python/branches/pep-3151/Modules/cryptmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/cryptmodule.c	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,62 +0,0 @@
-/* cryptmodule.c - by Steve Majewski
- */
-
-#include "Python.h"
-
-#include <sys/types.h>
-
-#ifdef __VMS
-#include <openssl/des.h>
-#endif
-
-/* Module crypt */
-
-
-static PyObject *crypt_crypt(PyObject *self, PyObject *args)
-{
-    char *word, *salt;
-#ifndef __VMS
-    extern char * crypt(const char *, const char *);
-#endif
-
-    if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) {
-        return NULL;
-    }
-    /* On some platforms (AtheOS) crypt returns NULL for an invalid
-       salt. Return None in that case. XXX Maybe raise an exception?  */
-    return Py_BuildValue("s", crypt(word, salt));
-
-}
-
-PyDoc_STRVAR(crypt_crypt__doc__,
-"crypt(word, salt) -> string\n\
-word will usually be a user's password. salt is a 2-character string\n\
-which will be used to select one of 4096 variations of DES. The characters\n\
-in salt must be either \".\", \"/\", or an alphanumeric character. Returns\n\
-the hashed password as a string, which will be composed of characters from\n\
-the same alphabet as the salt.");
-
-
-static PyMethodDef crypt_methods[] = {
-    {"crypt",           crypt_crypt, METH_VARARGS, crypt_crypt__doc__},
-    {NULL,              NULL}           /* sentinel */
-};
-
-
-static struct PyModuleDef cryptmodule = {
-    PyModuleDef_HEAD_INIT,
-    "crypt",
-    NULL,
-    -1,
-    crypt_methods,
-    NULL,
-    NULL,
-    NULL,
-    NULL
-};
-
-PyMODINIT_FUNC
-PyInit_crypt(void)
-{
-    return PyModule_Create(&cryptmodule);
-}

Modified: python/branches/pep-3151/Modules/gcmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/gcmodule.c	(original)
+++ python/branches/pep-3151/Modules/gcmodule.c	Sat Feb 26 08:16:32 2011
@@ -1511,11 +1511,3 @@
     }
     PyObject_FREE(g);
 }
-
-/* for binary compatibility with 2.2 */
-#undef _PyObject_GC_Del
-void
-_PyObject_GC_Del(PyObject *op)
-{
-    PyObject_GC_Del(op);
-}

Modified: python/branches/pep-3151/Modules/getpath.c
==============================================================================
--- python/branches/pep-3151/Modules/getpath.c	(original)
+++ python/branches/pep-3151/Modules/getpath.c	Sat Feb 26 08:16:32 2011
@@ -361,7 +361,7 @@
             decoded = PyUnicode_DecodeUTF8(buf, n, "surrogateescape");
             if (decoded != NULL) {
                 Py_ssize_t k;
-                k = PyUnicode_AsWideChar((PyUnicodeObject*)decoded,
+                k = PyUnicode_AsWideChar(decoded,
                                          rel_builddir_path, MAXPATHLEN);
                 Py_DECREF(decoded);
                 if (k >= 0) {

Modified: python/branches/pep-3151/Modules/grpmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/grpmodule.c	(original)
+++ python/branches/pep-3151/Modules/grpmodule.c	Sat Feb 26 08:16:32 2011
@@ -2,7 +2,6 @@
 /* UNIX group file access module */
 
 #include "Python.h"
-#include "structseq.h"
 
 #include <sys/types.h>
 #include <grp.h>
@@ -160,7 +159,9 @@
 name is not valid, raise KeyError."},
     {"getgrall",        grp_getgrall,   METH_NOARGS,
      "getgrall() -> list of tuples\n\
-Return a list of all available group entries, in arbitrary order."},
+Return a list of all available group entries, in arbitrary order.\n\
+An entry whose name starts with '+' or '-' represents an instruction\n\
+to use YP/NIS and may not be accessible via getgrnam or getgrgid."},
     {NULL,              NULL}           /* sentinel */
 };
 

Modified: python/branches/pep-3151/Modules/itertoolsmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/itertoolsmodule.c	(original)
+++ python/branches/pep-3151/Modules/itertoolsmodule.c	Sat Feb 26 08:16:32 2011
@@ -1215,6 +1215,7 @@
 {
     PyObject *item;
     PyObject *it = lz->it;
+    Py_ssize_t stop = lz->stop;
     Py_ssize_t oldnext;
     PyObject *(*iternext)(PyObject *);
 
@@ -1226,7 +1227,7 @@
         Py_DECREF(item);
         lz->cnt++;
     }
-    if (lz->stop != -1 && lz->cnt >= lz->stop)
+    if (stop != -1 && lz->cnt >= stop)
         return NULL;
     item = iternext(it);
     if (item == NULL)
@@ -1234,8 +1235,8 @@
     lz->cnt++;
     oldnext = lz->next;
     lz->next += lz->step;
-    if (lz->next < oldnext)     /* Check for overflow */
-        lz->next = lz->stop;
+    if (lz->next < oldnext || (stop != -1 && lz->next > stop))
+        lz->next = stop;
     return item;
 }
 
@@ -2583,6 +2584,138 @@
     PyObject_GC_Del,                    /* tp_free */
 };
 
+/* accumulate object ************************************************************/
+
+typedef struct {
+    PyObject_HEAD
+    PyObject *total;
+    PyObject *it;
+} accumulateobject;
+
+static PyTypeObject accumulate_type;
+
+static PyObject *
+accumulate_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
+{
+    static char *kwargs[] = {"iterable", NULL};
+    PyObject *iterable;
+    PyObject *it;
+    accumulateobject *lz;
+
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:accumulate", kwargs, &iterable))
+        return NULL;
+
+    /* Get iterator. */
+    it = PyObject_GetIter(iterable);
+    if (it == NULL)
+        return NULL;
+
+    /* create accumulateobject structure */
+    lz = (accumulateobject *)type->tp_alloc(type, 0);
+    if (lz == NULL) {
+        Py_DECREF(it);
+        return NULL;
+    }
+
+    lz->total = NULL;
+    lz->it = it;
+    return (PyObject *)lz;
+}
+
+static void
+accumulate_dealloc(accumulateobject *lz)
+{
+    PyObject_GC_UnTrack(lz);
+    Py_XDECREF(lz->total);
+    Py_XDECREF(lz->it);
+    Py_TYPE(lz)->tp_free(lz);
+}
+
+static int
+accumulate_traverse(accumulateobject *lz, visitproc visit, void *arg)
+{
+    Py_VISIT(lz->it);
+    Py_VISIT(lz->total);
+    return 0;
+}
+
+static PyObject *
+accumulate_next(accumulateobject *lz)
+{
+    PyObject *val, *oldtotal, *newtotal;
+    
+    val = PyIter_Next(lz->it);
+    if (val == NULL)
+        return NULL;
+ 
+    if (lz->total == NULL) {
+        Py_INCREF(val);
+        lz->total = val;
+        return lz->total;
+    }
+   
+    newtotal = PyNumber_Add(lz->total, val);
+    Py_DECREF(val);
+    if (newtotal == NULL)
+        return NULL;
+
+    oldtotal = lz->total;
+    lz->total = newtotal;
+    Py_DECREF(oldtotal);
+    
+    Py_INCREF(newtotal);
+    return newtotal;
+}
+
+PyDoc_STRVAR(accumulate_doc,
+"accumulate(iterable) --> accumulate object\n\
+\n\
+Return series of accumulated sums.");
+
+static PyTypeObject accumulate_type = {
+    PyVarObject_HEAD_INIT(NULL, 0)
+    "itertools.accumulate",             /* tp_name */
+    sizeof(accumulateobject),           /* tp_basicsize */
+    0,                                  /* tp_itemsize */
+    /* methods */
+    (destructor)accumulate_dealloc,     /* tp_dealloc */
+    0,                                  /* tp_print */
+    0,                                  /* tp_getattr */
+    0,                                  /* tp_setattr */
+    0,                                  /* tp_reserved */
+    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 | Py_TPFLAGS_HAVE_GC |
+        Py_TPFLAGS_BASETYPE,            /* tp_flags */
+    accumulate_doc,                     /* tp_doc */
+    (traverseproc)accumulate_traverse,  /* tp_traverse */
+    0,                                  /* tp_clear */
+    0,                                  /* tp_richcompare */
+    0,                                  /* tp_weaklistoffset */
+    PyObject_SelfIter,                  /* tp_iter */
+    (iternextfunc)accumulate_next,      /* tp_iternext */
+    0,                                  /* tp_methods */
+    0,                                  /* tp_members */
+    0,                                  /* tp_getset */
+    0,                                  /* tp_base */
+    0,                                  /* tp_dict */
+    0,                                  /* tp_descr_get */
+    0,                                  /* tp_descr_set */
+    0,                                  /* tp_dictoffset */
+    0,                                  /* tp_init */
+    0,                                  /* tp_alloc */
+    accumulate_new,                     /* tp_new */
+    PyObject_GC_Del,                    /* tp_free */
+};
+
 
 /* compress object ************************************************************/
 
@@ -3495,6 +3628,7 @@
 repeat(elem [,n]) --> elem, elem, elem, ... endlessly or up to n times\n\
 \n\
 Iterators terminating on the shortest input sequence:\n\
+accumulate(p, start=0) --> p0, p0+p1, p0+p1+p2\n\
 chain(p, q, ...) --> p0, p1, ... plast, q0, q1, ... \n\
 compress(data, selectors) --> (d[0] if s[0]), (d[1] if s[1]), ...\n\
 dropwhile(pred, seq) --> seq[n], seq[n+1], starting when pred fails\n\
@@ -3540,6 +3674,7 @@
     PyObject *m;
     char *name;
     PyTypeObject *typelist[] = {
+        &accumulate_type,
         &combinations_type,
         &cwr_type,
         &cycle_type,

Modified: python/branches/pep-3151/Modules/ld_so_aix.in
==============================================================================
--- python/branches/pep-3151/Modules/ld_so_aix.in	(original)
+++ python/branches/pep-3151/Modules/ld_so_aix.in	Sat Feb 26 08:16:32 2011
@@ -131,7 +131,7 @@
   shift
 done
 
-if test "$objfile" = "libpython at VERSION@.so"; then
+if test "$objfile" = "libpython at VERSION@@ABIFLAGS at .so"; then
   ldsocoremode="true" 
 fi
 

Modified: python/branches/pep-3151/Modules/main.c
==============================================================================
--- python/branches/pep-3151/Modules/main.c	(original)
+++ python/branches/pep-3151/Modules/main.c	Sat Feb 26 08:16:32 2011
@@ -2,7 +2,6 @@
 
 #include "Python.h"
 #include "osdefs.h"
-#include "import.h"
 
 #include <locale.h>
 
@@ -47,7 +46,7 @@
 static int  orig_argc;
 
 /* command line options */
-#define BASE_OPTS L"bBc:dEhiJm:OsStuvVW:xX:?"
+#define BASE_OPTS L"bBc:dEhiJm:OqsStuvVW:xX:?"
 
 #define PROGRAM_OPTS BASE_OPTS
 
@@ -72,6 +71,7 @@
 -m mod : run library module as a script (terminates option list)\n\
 -O     : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x\n\
 -OO    : remove doc-strings in addition to the -O optimizations\n\
+-q     : don't print version and copyright messages on interactive startup\n\
 -s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE\n\
 -S     : don't imply 'import site' on initialization\n\
 ";
@@ -425,6 +425,10 @@
             PySys_AddXOption(_PyOS_optarg);
             break;
 
+        case 'q':
+            Py_QuietFlag++;
+            break;
+
         /* This space reserved for other options */
 
         default:
@@ -523,11 +527,14 @@
 
     stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
 
-    if (Py_UnbufferedStdioFlag) {
 #if defined(MS_WINDOWS) || defined(__CYGWIN__)
-        _setmode(fileno(stdin), O_BINARY);
-        _setmode(fileno(stdout), O_BINARY);
+    /* don't translate newlines (\r\n <=> \n) */
+    _setmode(fileno(stdin), O_BINARY);
+    _setmode(fileno(stdout), O_BINARY);
+    _setmode(fileno(stderr), O_BINARY);
 #endif
+
+    if (Py_UnbufferedStdioFlag) {
 #ifdef HAVE_SETVBUF
         setvbuf(stdin,  (char *)NULL, _IONBF, BUFSIZ);
         setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
@@ -570,7 +577,6 @@
     if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0') {
         wchar_t* buffer;
         size_t len = strlen(p);
-        size_t r;
 
         buffer = malloc(len * sizeof(wchar_t));
         if (buffer == NULL) {
@@ -578,7 +584,7 @@
                "not enough memory to copy PYTHONEXECUTABLE");
         }
 
-        r = mbstowcs(buffer, p, len);
+        mbstowcs(buffer, p, len);
         Py_SetProgramName(buffer);
         /* buffer is now handed off - do not free */
     } else {
@@ -589,8 +595,9 @@
 #endif
     Py_Initialize();
 
-    if (Py_VerboseFlag ||
-        (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
+    if (!Py_QuietFlag && (Py_VerboseFlag ||
+                        (command == NULL && filename == NULL &&
+                         module == NULL && stdin_is_interactive))) {
         fprintf(stderr, "Python %s on %s\n",
             Py_GetVersion(), Py_GetPlatform());
         if (!Py_NoSiteFlag)
@@ -712,7 +719,6 @@
      * trade off slower shutdown for less distraction in the memory
      * reports.  -baw
      */
-    _Py_ReleaseInternedStrings();
     _Py_ReleaseInternedUnicodeStrings();
 #endif /* __INSURE__ */
 

Modified: python/branches/pep-3151/Modules/md5module.c
==============================================================================
--- python/branches/pep-3151/Modules/md5module.c	(original)
+++ python/branches/pep-3151/Modules/md5module.c	Sat Feb 26 08:16:32 2011
@@ -228,9 +228,9 @@
    @param inlen  The length of the data (octets)
 */
 void md5_process(struct md5_state *md5,
-                const unsigned char *in, unsigned long inlen)
+                const unsigned char *in, Py_ssize_t inlen)
 {
-    unsigned long n;
+    Py_ssize_t n;
 
     assert(md5 != NULL);
     assert(in != NULL);

Modified: python/branches/pep-3151/Modules/mmapmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/mmapmodule.c	(original)
+++ python/branches/pep-3151/Modules/mmapmodule.c	Sat Feb 26 08:16:32 2011
@@ -88,7 +88,11 @@
     char *      data;
     size_t      size;
     size_t      pos;    /* relative to offset */
-    size_t      offset;
+#ifdef MS_WINDOWS
+    PY_LONG_LONG offset;
+#else
+    off_t       offset;
+#endif
     int     exports;
 
 #ifdef MS_WINDOWS
@@ -431,7 +435,11 @@
             PyErr_SetFromErrno(PyExc_IOError);
             return NULL;
         }
-        return PyLong_FromSsize_t(buf.st_size);
+#ifdef HAVE_LARGEFILE_SUPPORT
+        return PyLong_FromLongLong(buf.st_size);
+#else
+        return PyLong_FromLong(buf.st_size);
+#endif
     }
 #endif /* UNIX */
 }
@@ -465,17 +473,10 @@
         CloseHandle(self->map_handle);
         self->map_handle = NULL;
         /* Move to the desired EOF position */
-#if SIZEOF_SIZE_T > 4
         newSizeHigh = (DWORD)((self->offset + new_size) >> 32);
         newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF);
         off_hi = (DWORD)(self->offset >> 32);
         off_lo = (DWORD)(self->offset & 0xFFFFFFFF);
-#else
-        newSizeHigh = 0;
-        newSizeLow = (DWORD)(self->offset + new_size);
-        off_hi = 0;
-        off_lo = (DWORD)self->offset;
-#endif
         SetFilePointer(self->file_handle,
                        newSizeLow, &newSizeHigh, FILE_BEGIN);
         /* Change the size of the file */
@@ -760,7 +761,7 @@
     else if (PySlice_Check(item)) {
         Py_ssize_t start, stop, step, slicelen;
 
-        if (PySlice_GetIndicesEx((PySliceObject *)item, self->size,
+        if (PySlice_GetIndicesEx(item, self->size,
                          &start, &stop, &step, &slicelen) < 0) {
             return NULL;
         }
@@ -886,7 +887,7 @@
         Py_ssize_t start, stop, step, slicelen;
         Py_buffer vbuf;
 
-        if (PySlice_GetIndicesEx((PySliceObject *)item,
+        if (PySlice_GetIndicesEx(item,
                                  self->size, &start, &stop,
                                  &step, &slicelen) < 0) {
             return -1;
@@ -1049,6 +1050,12 @@
 }
 
 #ifdef UNIX
+#ifdef HAVE_LARGEFILE_SUPPORT
+#define _Py_PARSE_OFF_T "L"
+#else
+#define _Py_PARSE_OFF_T "l"
+#endif
+
 static PyObject *
 new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
 {
@@ -1056,8 +1063,9 @@
     struct stat st;
 #endif
     mmap_object *m_obj;
-    PyObject *map_size_obj = NULL, *offset_obj = NULL;
-    Py_ssize_t map_size, offset;
+    PyObject *map_size_obj = NULL;
+    Py_ssize_t map_size;
+    off_t offset = 0;
     int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
     int devzero = -1;
     int access = (int)ACCESS_DEFAULT;
@@ -1065,16 +1073,18 @@
                                      "flags", "prot",
                                      "access", "offset", NULL};
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords,
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iii" _Py_PARSE_OFF_T, keywords,
                                      &fd, &map_size_obj, &flags, &prot,
-                                     &access, &offset_obj))
+                                     &access, &offset))
         return NULL;
     map_size = _GetMapSize(map_size_obj, "size");
     if (map_size < 0)
         return NULL;
-    offset = _GetMapSize(offset_obj, "offset");
-    if (offset < 0)
+    if (offset < 0) {
+        PyErr_SetString(PyExc_OverflowError,
+            "memory mapped offset must be positive");
         return NULL;
+    }
 
     if ((access != (int)ACCESS_DEFAULT) &&
         ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ))))
@@ -1114,8 +1124,19 @@
 #  endif
     if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
         if (map_size == 0) {
-            map_size = st.st_size;
-        } else if ((size_t)offset + (size_t)map_size > st.st_size) {
+            if (offset >= st.st_size) {
+                PyErr_SetString(PyExc_ValueError,
+                                "mmap offset is greater than file size");
+                return NULL;
+            }
+            off_t calc_size = st.st_size - offset;
+            map_size = calc_size;
+            if (map_size != calc_size) {
+                PyErr_SetString(PyExc_ValueError,
+                                 "mmap length is too large");
+                 return NULL;
+             }
+        } else if (offset + (size_t)map_size > st.st_size) {
             PyErr_SetString(PyExc_ValueError,
                             "mmap length is greater than file size");
             return NULL;
@@ -1176,12 +1197,19 @@
 #endif /* UNIX */
 
 #ifdef MS_WINDOWS
+
+/* A note on sizes and offsets: while the actual map size must hold in a
+   Py_ssize_t, both the total file size and the start offset can be longer
+   than a Py_ssize_t, so we use PY_LONG_LONG which is always 64-bit.
+*/
+
 static PyObject *
 new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
 {
     mmap_object *m_obj;
-    PyObject *map_size_obj = NULL, *offset_obj = NULL;
-    Py_ssize_t map_size, offset;
+    PyObject *map_size_obj = NULL;
+    Py_ssize_t map_size;
+    PY_LONG_LONG offset = 0, size;
     DWORD off_hi;       /* upper 32 bits of offset */
     DWORD off_lo;       /* lower 32 bits of offset */
     DWORD size_hi;      /* upper 32 bits of size */
@@ -1196,9 +1224,9 @@
                                       "tagname",
                                       "access", "offset", NULL };
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords,
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziL", keywords,
                                      &fileno, &map_size_obj,
-                                     &tagname, &access, &offset_obj)) {
+                                     &tagname, &access, &offset)) {
         return NULL;
     }
 
@@ -1223,9 +1251,11 @@
     map_size = _GetMapSize(map_size_obj, "size");
     if (map_size < 0)
         return NULL;
-    offset = _GetMapSize(offset_obj, "offset");
-    if (offset < 0)
+    if (offset < 0) {
+        PyErr_SetString(PyExc_OverflowError,
+            "memory mapped offset must be positive");
         return NULL;
+    }
 
     /* assume -1 and 0 both mean invalid filedescriptor
        to 'anonymously' map memory.
@@ -1289,21 +1319,26 @@
                 return PyErr_SetFromWindowsErr(dwErr);
             }
 
-#if SIZEOF_SIZE_T > 4
-            m_obj->size = (((size_t)high)<<32) + low;
-#else
-            if (high)
-                /* File is too large to map completely */
-                m_obj->size = (size_t)-1;
+            size = (((PY_LONG_LONG) high) << 32) + low;
+            if (offset >= size) {
+                PyErr_SetString(PyExc_ValueError,
+                                "mmap offset is greater than file size");
+                Py_DECREF(m_obj);
+                return NULL;
+            }
+            if (offset - size > PY_SSIZE_T_MAX)
+                /* Map area too large to fit in memory */
+                m_obj->size = (Py_ssize_t) -1;
             else
-                m_obj->size = low;
-#endif
+                m_obj->size = (Py_ssize_t) (size - offset);
         } else {
             m_obj->size = map_size;
+            size = offset + map_size;
         }
     }
     else {
         m_obj->size = map_size;
+        size = offset + map_size;
     }
 
     /* set the initial position */
@@ -1324,22 +1359,10 @@
         m_obj->tagname = NULL;
 
     m_obj->access = (access_mode)access;
-    /* DWORD is a 4-byte int.  If we're on a box where size_t consumes
-     * more than 4 bytes, we need to break it apart.  Else (size_t
-     * consumes 4 bytes), C doesn't define what happens if we shift
-     * right by 32, so we need different code.
-     */
-#if SIZEOF_SIZE_T > 4
-    size_hi = (DWORD)((offset + m_obj->size) >> 32);
-    size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF);
+    size_hi = (DWORD)(size >> 32);
+    size_lo = (DWORD)(size & 0xFFFFFFFF);
     off_hi = (DWORD)(offset >> 32);
     off_lo = (DWORD)(offset & 0xFFFFFFFF);
-#else
-    size_hi = 0;
-    size_lo = (DWORD)(offset + m_obj->size);
-    off_hi = 0;
-    off_lo = (DWORD)offset;
-#endif
     /* For files, it would be sufficient to pass 0 as size.
        For anonymous maps, we have to pass the size explicitly. */
     m_obj->map_handle = CreateFileMapping(m_obj->file_handle,

Modified: python/branches/pep-3151/Modules/parsermodule.c
==============================================================================
--- python/branches/pep-3151/Modules/parsermodule.c	(original)
+++ python/branches/pep-3151/Modules/parsermodule.c	Sat Feb 26 08:16:32 2011
@@ -34,10 +34,8 @@
 #include "grammar.h"
 #include "parsetok.h"
                                         /* ISTERMINAL() / ISNONTERMINAL() */
-#include "compile.h"
 #undef Yield
 #include "ast.h"
-#include "pyarena.h"
 
 extern grammar _PyParser_Grammar; /* From graminit.c */
 
@@ -794,6 +792,11 @@
                 }
             }
             temp_str = _PyUnicode_AsStringAndSize(temp, &len);
+            if (temp_str == NULL) {
+                Py_DECREF(temp);
+                Py_XDECREF(elem);
+                return 0;
+            }
             strn = (char *)PyObject_MALLOC(len + 1);
             if (strn != NULL)
                 (void) memcpy(strn, temp_str, len + 1);
@@ -872,6 +875,8 @@
             encoding = PySequence_GetItem(tuple, 2);
             /* tuple isn't borrowed anymore here, need to DECREF */
             tuple = PySequence_GetSlice(tuple, 0, 2);
+            if (tuple == NULL)
+                return NULL;
         }
         res = PyNode_New(num);
         if (res != NULL) {
@@ -883,6 +888,12 @@
                 Py_ssize_t len;
                 const char *temp;
                 temp = _PyUnicode_AsStringAndSize(encoding, &len);
+                if (temp == NULL) {
+                    Py_DECREF(res);
+                    Py_DECREF(encoding);
+                    Py_DECREF(tuple);
+                    return NULL;
+                }
                 res->n_str = (char *)PyObject_MALLOC(len + 1);
                 if (res->n_str != NULL && temp != NULL)
                     (void) memcpy(res->n_str, temp, len + 1);

Modified: python/branches/pep-3151/Modules/posixmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/posixmodule.c	(original)
+++ python/branches/pep-3151/Modules/posixmodule.c	Sat Feb 26 08:16:32 2011
@@ -28,7 +28,6 @@
 #define PY_SSIZE_T_CLEAN
 
 #include "Python.h"
-#include "structseq.h"
 
 #if defined(__VMS)
 #    include <unixio.h>
@@ -96,6 +95,20 @@
 #include <langinfo.h>
 #endif
 
+#ifdef HAVE_SYS_SENDFILE_H
+#include <sys/sendfile.h>
+#endif
+
+#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
+#ifdef HAVE_SYS_SOCKET_H
+#include <sys/socket.h>
+#endif
+
+#ifdef HAVE_SYS_UIO_H
+#include <sys/uio.h>
+#endif
+#endif
+
 /* Various compilers have only certain posix functions */
 /* XXX Gosh I wish these were all moved into pyconfig.h */
 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
@@ -122,7 +135,7 @@
 #ifdef _MSC_VER         /* Microsoft compiler */
 #define HAVE_GETCWD     1
 #define HAVE_GETPPID    1
-#define HAVE_GETLOGIN   1 
+#define HAVE_GETLOGIN   1
 #define HAVE_SPAWNV     1
 #define HAVE_EXECV      1
 #define HAVE_PIPE       1
@@ -278,6 +291,10 @@
 #include <windows.h>
 #include <shellapi.h>   /* for ShellExecute() */
 #include <lmcons.h>     /* for UNLEN */
+#ifdef SE_CREATE_SYMBOLIC_LINK_NAME /* Available starting with Vista */
+#define HAVE_SYMLINK
+static int win32_can_symlink = 0;
+#endif
 #endif /* _MSC_VER */
 
 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
@@ -323,6 +340,8 @@
 
 /* choose the appropriate stat and fstat functions and return structs */
 #undef STAT
+#undef FSTAT
+#undef STRUCT_STAT
 #if defined(MS_WIN64) || defined(MS_WINDOWS)
 #       define STAT win32_stat
 #       define FSTAT win32_fstat
@@ -344,6 +363,20 @@
 #endif
 #endif
 
+static int
+_parse_off_t(PyObject* arg, void* addr)
+{
+#if !defined(HAVE_LARGEFILE_SUPPORT)
+    *((off_t*)addr) = PyLong_AsLong(arg);
+#else
+    *((off_t*)addr) = PyLong_Check(arg) ? PyLong_AsLongLong(arg)
+            : PyLong_AsLong(arg);
+#endif
+    if (PyErr_Occurred())
+        return 0;
+    return 1;
+}
+
 #if defined _MSC_VER && _MSC_VER >= 1400
 /* Microsoft CRT in VS2005 and higher will verify that a filehandle is
  * valid and throw an assertion if it isn't.
@@ -437,6 +470,98 @@
 #define _PyVerify_fd_dup2(A, B) (1)
 #endif
 
+#ifdef MS_WINDOWS
+/* The following structure was copied from
+   http://msdn.microsoft.com/en-us/library/ms791514.aspx as the required
+   include doesn't seem to be present in the Windows SDK (at least as included
+   with Visual Studio Express). */
+typedef struct _REPARSE_DATA_BUFFER {
+    ULONG ReparseTag;
+    USHORT ReparseDataLength;
+    USHORT Reserved;
+    union {
+        struct {
+            USHORT SubstituteNameOffset;
+            USHORT SubstituteNameLength;
+            USHORT PrintNameOffset;
+            USHORT PrintNameLength;
+            ULONG Flags;
+            WCHAR PathBuffer[1];
+        } SymbolicLinkReparseBuffer;
+
+        struct {
+            USHORT SubstituteNameOffset;
+            USHORT  SubstituteNameLength;
+            USHORT  PrintNameOffset;
+            USHORT  PrintNameLength;
+            WCHAR  PathBuffer[1];
+        } MountPointReparseBuffer;
+
+        struct {
+            UCHAR  DataBuffer[1];
+        } GenericReparseBuffer;
+    };
+} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
+
+#define REPARSE_DATA_BUFFER_HEADER_SIZE  FIELD_OFFSET(REPARSE_DATA_BUFFER,\
+                                                      GenericReparseBuffer)
+#define MAXIMUM_REPARSE_DATA_BUFFER_SIZE  ( 16 * 1024 )
+
+static int
+win32_read_link(HANDLE reparse_point_handle, ULONG *reparse_tag, wchar_t **target_path)
+{
+    char target_buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
+    REPARSE_DATA_BUFFER *rdb = (REPARSE_DATA_BUFFER *)target_buffer;
+    DWORD n_bytes_returned;
+    const wchar_t *ptr;
+    wchar_t *buf;
+    size_t len;
+
+    if (0 == DeviceIoControl(
+        reparse_point_handle,
+        FSCTL_GET_REPARSE_POINT,
+        NULL, 0, /* in buffer */
+        target_buffer, sizeof(target_buffer),
+        &n_bytes_returned,
+        NULL)) /* we're not using OVERLAPPED_IO */
+        return -1;
+
+    if (reparse_tag)
+        *reparse_tag = rdb->ReparseTag;
+
+    if (target_path) {
+        switch (rdb->ReparseTag) {
+        case IO_REPARSE_TAG_SYMLINK:
+            /* XXX: Maybe should use SubstituteName? */
+            ptr = rdb->SymbolicLinkReparseBuffer.PathBuffer +
+                  rdb->SymbolicLinkReparseBuffer.PrintNameOffset/sizeof(WCHAR);
+            len = rdb->SymbolicLinkReparseBuffer.PrintNameLength/sizeof(WCHAR);
+            break;
+        case IO_REPARSE_TAG_MOUNT_POINT:
+            ptr = rdb->MountPointReparseBuffer.PathBuffer +
+                  rdb->MountPointReparseBuffer.SubstituteNameOffset/sizeof(WCHAR);
+            len = rdb->MountPointReparseBuffer.SubstituteNameLength/sizeof(WCHAR);
+            break;
+        default:
+            SetLastError(ERROR_REPARSE_TAG_MISMATCH); /* XXX: Proper error code? */
+            return -1;
+        }
+        buf = (wchar_t *)malloc(sizeof(wchar_t)*(len+1));
+        if (!buf) {
+            SetLastError(ERROR_OUTOFMEMORY);
+            return -1;
+        }
+        wcsncpy(buf, ptr, len);
+        buf[len] = L'\0';
+        if (wcsncmp(buf, L"\\??\\", 4) == 0)
+            buf[1] = L'\\';
+        *target_path = buf;
+    }
+
+    return 0;
+}
+#endif /* MS_WINDOWS */
+
 /* Return a dictionary corresponding to the POSIX environment table */
 #ifdef WITH_NEXT_FRAMEWORK
 /* On Darwin/MacOSX a shared library or framework has no access to
@@ -881,18 +1006,18 @@
     int st_gid;
     int st_rdev;
     __int64 st_size;
-    int st_atime;
+    time_t st_atime;
     int st_atime_nsec;
-    int st_mtime;
+    time_t st_mtime;
     int st_mtime_nsec;
-    int st_ctime;
+    time_t st_ctime;
     int st_ctime_nsec;
 };
 
 static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
 
 static void
-FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, int *time_out, int* nsec_out)
+FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
 {
     /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
     /* Cannot simply cast and dereference in_ptr,
@@ -900,12 +1025,11 @@
     __int64 in;
     memcpy(&in, in_ptr, sizeof(in));
     *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
-    /* XXX Win32 supports time stamps past 2038; we currently don't */
-    *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, int);
+    *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
 }
 
 static void
-time_t_to_FILE_TIME(int time_in, int nsec_in, FILETIME *out_ptr)
+time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
 {
     /* XXX endianness */
     __int64 out;
@@ -934,7 +1058,7 @@
 }
 
 static int
-attribute_data_to_stat(WIN32_FILE_ATTRIBUTE_DATA *info, struct win32_stat *result)
+attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag, struct win32_stat *result)
 {
     memset(result, 0, sizeof(*result));
     result->st_mode = attributes_to_mode(info->dwFileAttributes);
@@ -942,12 +1066,20 @@
     FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
     FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
     FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
+    result->st_nlink = info->nNumberOfLinks;
+    result->st_ino = (((__int64)info->nFileIndexHigh)<<32) + info->nFileIndexLow;
+    if (reparse_tag == IO_REPARSE_TAG_SYMLINK) {
+        /* first clear the S_IFMT bits */
+        result->st_mode ^= (result->st_mode & 0170000);
+        /* now set the bits that make this a symlink */
+        result->st_mode |= 0120000;
+    }
 
     return 0;
 }
 
 static BOOL
-attributes_from_dir(LPCSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
+attributes_from_dir(LPCSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
 {
     HANDLE hFindFile;
     WIN32_FIND_DATAA FileData;
@@ -955,17 +1087,22 @@
     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;
+    memset(info, 0, sizeof(*info));
+    *reparse_tag = 0;
+    info->dwFileAttributes = FileData.dwFileAttributes;
+    info->ftCreationTime   = FileData.ftCreationTime;
+    info->ftLastAccessTime = FileData.ftLastAccessTime;
+    info->ftLastWriteTime  = FileData.ftLastWriteTime;
+    info->nFileSizeHigh    = FileData.nFileSizeHigh;
+    info->nFileSizeLow     = FileData.nFileSizeLow;
+/*  info->nNumberOfLinks   = 1; */
+    if (FileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
+        *reparse_tag = FileData.dwReserved0;
     return TRUE;
 }
 
 static BOOL
-attributes_from_dir_w(LPCWSTR pszFile, LPWIN32_FILE_ATTRIBUTE_DATA pfad)
+attributes_from_dir_w(LPCWSTR pszFile, BY_HANDLE_FILE_INFORMATION *info, ULONG *reparse_tag)
 {
     HANDLE hFindFile;
     WIN32_FIND_DATAW FileData;
@@ -973,178 +1110,40 @@
     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;
+    memset(info, 0, sizeof(*info));
+    *reparse_tag = 0;
+    info->dwFileAttributes = FileData.dwFileAttributes;
+    info->ftCreationTime   = FileData.ftCreationTime;
+    info->ftLastAccessTime = FileData.ftLastAccessTime;
+    info->ftLastWriteTime  = FileData.ftLastWriteTime;
+    info->nFileSizeHigh    = FileData.nFileSizeHigh;
+    info->nFileSizeLow     = FileData.nFileSizeLow;
+/*  info->nNumberOfLinks   = 1; */
+    if (FileData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
+        *reparse_tag = FileData.dwReserved0;
     return TRUE;
 }
 
-/* About the following functions: win32_lstat, win32_lstat_w, win32_stat,
-   win32_stat_w
-
-   In Posix, stat automatically traverses symlinks and returns the stat
-   structure for the target.  In Windows, the equivalent GetFileAttributes by
-   default does not traverse symlinks and instead returns attributes for
-   the symlink.
-
-   Therefore, win32_lstat will get the attributes traditionally, and
-   win32_stat will first explicitly resolve the symlink target and then will
-   call win32_lstat on that result.
-
-   The _w represent Unicode equivalents of the aformentioned ANSI functions. */
-
-static int 
-win32_lstat(const char* path, struct win32_stat *result)
-{
-    WIN32_FILE_ATTRIBUTE_DATA info;
-    int code;
-    char *dot;
-    WIN32_FIND_DATAA find_data;
-    HANDLE find_data_handle;
-    if (!GetFileAttributesExA(path, GetFileExInfoStandard, &info)) {
-        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)
-        return code;
-
-    /* Get WIN32_FIND_DATA structure for the path to determine if
-       it is a symlink */
-    if(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
-        find_data_handle = FindFirstFileA(path, &find_data);
-        if(find_data_handle != INVALID_HANDLE_VALUE) {
-            if(find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK) {
-                /* first clear the S_IFMT bits */
-                result->st_mode ^= (result->st_mode & 0170000);
-                /* now set the bits that make this a symlink */
-                result->st_mode |= 0120000;
-            }
-            FindClose(find_data_handle);
-        }
-    }
-
-    /* Set S_IFEXEC if it is an .exe, .bat, ... */
-    dot = strrchr(path, '.');
-    if (dot) {
-        if (stricmp(dot, ".bat") == 0 || stricmp(dot, ".cmd") == 0 ||
-            stricmp(dot, ".exe") == 0 || stricmp(dot, ".com") == 0)
-            result->st_mode |= 0111;
-    }
-    return code;
-}
-
-static int
-win32_lstat_w(const wchar_t* path, struct win32_stat *result)
-{
-    int code;
-    const wchar_t *dot;
-    WIN32_FILE_ATTRIBUTE_DATA info;
-    WIN32_FIND_DATAW find_data;
-    HANDLE find_data_handle;
-    if (!GetFileAttributesExW(path, GetFileExInfoStandard, &info)) {
-        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)
-        return code;
-
-    /* Get WIN32_FIND_DATA structure for the path to determine if
-       it is a symlink */
-    if(info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
-        find_data_handle = FindFirstFileW(path, &find_data);
-        if(find_data_handle != INVALID_HANDLE_VALUE) {
-            if(find_data.dwReserved0 == IO_REPARSE_TAG_SYMLINK) {
-                /* first clear the S_IFMT bits */
-                result->st_mode ^= (result->st_mode & 0170000);
-                /* now set the bits that make this a symlink */
-                result->st_mode |= 0120000;
-            }
-            FindClose(find_data_handle);
-        }
-    }
-
-    /* Set IFEXEC if it is an .exe, .bat, ... */
-    dot = wcsrchr(path, '.');
-    if (dot) {
-        if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
-            _wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
-            result->st_mode |= 0111;
-    }
-    return code;
-}
+#ifndef SYMLOOP_MAX
+#define SYMLOOP_MAX ( 88 )
+#endif
 
-/* Grab GetFinalPathNameByHandle dynamically from kernel32 */
-static int has_GetFinalPathNameByHandle = 0;
-static DWORD (CALLBACK *Py_GetFinalPathNameByHandleA)(HANDLE, LPSTR, DWORD,
-                                                      DWORD);
-static DWORD (CALLBACK *Py_GetFinalPathNameByHandleW)(HANDLE, LPWSTR, DWORD,
-                                                      DWORD);
 static int
-check_GetFinalPathNameByHandle()
-{
-    HINSTANCE hKernel32;
-    /* only recheck */
-    if (!has_GetFinalPathNameByHandle)
-    {
-        hKernel32 = GetModuleHandle("KERNEL32");
-        *(FARPROC*)&Py_GetFinalPathNameByHandleA = GetProcAddress(hKernel32,
-                                                "GetFinalPathNameByHandleA");
-        *(FARPROC*)&Py_GetFinalPathNameByHandleW = GetProcAddress(hKernel32,
-                                                "GetFinalPathNameByHandleW");
-        has_GetFinalPathNameByHandle = Py_GetFinalPathNameByHandleA &&
-                                       Py_GetFinalPathNameByHandleW;
-    }
-    return has_GetFinalPathNameByHandle;
-}
+win32_xstat_impl_w(const wchar_t *path, struct win32_stat *result, BOOL traverse, int depth);
 
 static int
-win32_stat(const char* path, struct win32_stat *result)
+win32_xstat_impl(const char *path, struct win32_stat *result, BOOL traverse, int depth)
 {
-    /* Traverse the symlink to the target using
-    GetFinalPathNameByHandle()
-    */
     int code;
     HANDLE hFile;
-    int buf_size;
-    char *target_path;
-    int result_length;
-    WIN32_FILE_ATTRIBUTE_DATA info;
-    
-    if(!check_GetFinalPathNameByHandle()) {
-        /* if the OS doesn't have GetFinalPathNameByHandle, it doesn't
-           have symlinks, so just fall back to the traditional behavior
-           found in lstat. */
-        return win32_lstat(path, result);
+    BY_HANDLE_FILE_INFORMATION info;
+    ULONG reparse_tag = 0;
+    wchar_t *target_path;
+    const char *dot;
+
+    if (depth > SYMLOOP_MAX) {
+        SetLastError(ERROR_CANT_RESOLVE_FILENAME); /* XXX: ELOOP? */
+        return -1;
     }
 
     hFile = CreateFileA(
@@ -1154,75 +1153,70 @@
         NULL, /* security attributes */
         OPEN_EXISTING,
         /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
-        FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
+        FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,
         NULL);
-    
-    if(hFile == INVALID_HANDLE_VALUE) {
+
+    if (hFile == INVALID_HANDLE_VALUE) {
         /* Either the target doesn't exist, or we don't have access to
            get a handle to it. If the former, we need to return an error.
            If the latter, we can use attributes_from_dir. */
-        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;
+        if (GetLastError() != ERROR_SHARING_VIOLATION)
             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;
+        /* Could not get attributes on open file. Fall back to
+           reading the directory. */
+        if (!attributes_from_dir(path, &info, &reparse_tag))
+            /* Very strange. This should not fail now */
+            return -1;
+        if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+            if (traverse) {
+                /* Should traverse, but could not open reparse point handle */
+                SetLastError(ERROR_SHARING_VIOLATION);
                 return -1;
             }
         }
-        code = attribute_data_to_stat(&info, result);
+    } else {
+        if (!GetFileInformationByHandle(hFile, &info)) {
+            CloseHandle(hFile);
+            return -1;;
+        }
+        if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+            code = win32_read_link(hFile, &reparse_tag, traverse ? &target_path : NULL);
+            CloseHandle(hFile);
+            if (code < 0)
+                return code;
+            if (traverse) {
+                code = win32_xstat_impl_w(target_path, result, traverse, depth + 1);
+                free(target_path);
+                return code;
+            }
+        } else
+            CloseHandle(hFile);
     }
-    else {
-        /* We have a good handle to the target, use it to determine the target
-           path name (then we'll call lstat on it). */
-        buf_size = Py_GetFinalPathNameByHandleA(hFile, 0, 0, VOLUME_NAME_DOS);
-        if(!buf_size) return -1;
-        /* Due to a slight discrepancy between GetFinalPathNameByHandleA
-           and GetFinalPathNameByHandleW, we must allocate one more byte
-           than reported. */
-        target_path = (char *)malloc((buf_size+2)*sizeof(char));
-        result_length = Py_GetFinalPathNameByHandleA(hFile, target_path,
-                                                     buf_size+1, VOLUME_NAME_DOS);
-
-        if(!result_length) {
-            free(target_path);
-            return -1;
-        }
-
-        if(!CloseHandle(hFile)) {
-            free(target_path);
-            return -1;
-        }
+    attribute_data_to_stat(&info, reparse_tag, result);
 
-        target_path[result_length] = 0;
-        code = win32_lstat(target_path, result);
-        free(target_path);
+    /* Set S_IEXEC if it is an .exe, .bat, ... */
+    dot = strrchr(path, '.');
+    if (dot) {
+        if (stricmp(dot, ".bat") == 0 || stricmp(dot, ".cmd") == 0 ||
+            stricmp(dot, ".exe") == 0 || stricmp(dot, ".com") == 0)
+            result->st_mode |= 0111;
     }
-    
-    return code;
+    return 0;
 }
 
-static int 
-win32_stat_w(const wchar_t* path, struct win32_stat *result)
+static int
+win32_xstat_impl_w(const wchar_t *path, struct win32_stat *result, BOOL traverse, int depth)
 {
-    /* Traverse the symlink to the target using GetFinalPathNameByHandle() */
     int code;
     HANDLE hFile;
-    int buf_size;
-    wchar_t *target_path;
-    int result_length;
-    WIN32_FILE_ATTRIBUTE_DATA info;
-    
-    if(!check_GetFinalPathNameByHandle()) {
-        /* If the OS doesn't have GetFinalPathNameByHandle, it doesn't have
-           symlinks, so just fall back to the traditional behavior found
-           in lstat. */
-        return win32_lstat_w(path, result);
+    BY_HANDLE_FILE_INFORMATION info;
+    ULONG reparse_tag = 0;
+	wchar_t *target_path;
+    const wchar_t *dot;
+
+    if (depth > SYMLOOP_MAX) {
+        SetLastError(ERROR_CANT_RESOLVE_FILENAME); /* XXX: ELOOP? */
+        return -1;
     }
 
     hFile = CreateFileW(
@@ -1232,75 +1226,132 @@
         NULL, /* security attributes */
         OPEN_EXISTING,
         /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
-        FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS,
+        FILE_ATTRIBUTE_NORMAL|FILE_FLAG_BACKUP_SEMANTICS|FILE_FLAG_OPEN_REPARSE_POINT,
         NULL);
 
-    if(hFile == INVALID_HANDLE_VALUE) {
+    if (hFile == INVALID_HANDLE_VALUE) {
         /* Either the target doesn't exist, or we don't have access to
            get a handle to it. If the former, we need to return an error.
            If the latter, we can use attributes_from_dir. */
-        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;
+        if (GetLastError() != ERROR_SHARING_VIOLATION)
             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;
+        /* Could not get attributes on open file. Fall back to
+           reading the directory. */
+        if (!attributes_from_dir_w(path, &info, &reparse_tag))
+            /* Very strange. This should not fail now */
+            return -1;
+        if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+            if (traverse) {
+                /* Should traverse, but could not open reparse point handle */
+                SetLastError(ERROR_SHARING_VIOLATION);
                 return -1;
             }
         }
-        code = attribute_data_to_stat(&info, result);
+    } else {
+        if (!GetFileInformationByHandle(hFile, &info)) {
+            CloseHandle(hFile);
+            return -1;;
+        }
+        if (info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
+            code = win32_read_link(hFile, &reparse_tag, traverse ? &target_path : NULL);
+            CloseHandle(hFile);
+            if (code < 0)
+                return code;
+            if (traverse) {
+                code = win32_xstat_impl_w(target_path, result, traverse, depth + 1);
+                free(target_path);
+                return code;
+            }
+        } else
+            CloseHandle(hFile);
     }
-    else {
-        /* We have a good handle to the target, use it to determine the target
-           path name (then we'll call lstat on it). */
-        buf_size = Py_GetFinalPathNameByHandleW(hFile, 0, 0, VOLUME_NAME_DOS);
-        if(!buf_size)
-            return -1;
-
-        target_path = (wchar_t *)malloc((buf_size+1)*sizeof(wchar_t));
-        result_length = Py_GetFinalPathNameByHandleW(hFile, target_path,
-                                                buf_size, VOLUME_NAME_DOS);
-        
-        if(!result_length) {
-            free(target_path);
-            return -1;
-        }
-
-        if(!CloseHandle(hFile)) {
-            free(target_path);
-            return -1;
-        }
+    attribute_data_to_stat(&info, reparse_tag, result);
 
-        target_path[result_length] = 0;
-        code = win32_lstat_w(target_path, result);
-        free(target_path);
+    /* Set S_IEXEC if it is an .exe, .bat, ... */
+    dot = wcsrchr(path, '.');
+    if (dot) {
+        if (_wcsicmp(dot, L".bat") == 0 || _wcsicmp(dot, L".cmd") == 0 ||
+            _wcsicmp(dot, L".exe") == 0 || _wcsicmp(dot, L".com") == 0)
+            result->st_mode |= 0111;
     }
-    
-    return code;
+    return 0;
 }
 
 static int
-win32_fstat(int file_number, struct win32_stat *result)
+win32_xstat(const char *path, struct win32_stat *result, BOOL traverse)
 {
-    BY_HANDLE_FILE_INFORMATION info;
-    HANDLE h;
-    int type;
-
-    h = (HANDLE)_get_osfhandle(file_number);
+    /* Protocol violation: we explicitly clear errno, instead of
+       setting it to a POSIX error. Callers should use GetLastError. */
+    int code = win32_xstat_impl(path, result, traverse, 0);
+    errno = 0;
+    return code;
+}
 
+static int
+win32_xstat_w(const wchar_t *path, struct win32_stat *result, BOOL traverse)
+{
     /* Protocol violation: we explicitly clear errno, instead of
        setting it to a POSIX error. Callers should use GetLastError. */
+    int code = win32_xstat_impl_w(path, result, traverse, 0);
     errno = 0;
+    return code;
+}
 
-    if (h == INVALID_HANDLE_VALUE) {
-        /* This is really a C library error (invalid file handle).
-           We set the Win32 error to the closes one matching. */
-        SetLastError(ERROR_INVALID_HANDLE);
+/* About the following functions: win32_lstat, win32_lstat_w, win32_stat,
+   win32_stat_w
+
+   In Posix, stat automatically traverses symlinks and returns the stat
+   structure for the target.  In Windows, the equivalent GetFileAttributes by
+   default does not traverse symlinks and instead returns attributes for
+   the symlink.
+
+   Therefore, win32_lstat will get the attributes traditionally, and
+   win32_stat will first explicitly resolve the symlink target and then will
+   call win32_lstat on that result.
+
+   The _w represent Unicode equivalents of the aformentioned ANSI functions. */
+
+static int
+win32_lstat(const char* path, struct win32_stat *result)
+{
+    return win32_xstat(path, result, FALSE);
+}
+
+static int
+win32_lstat_w(const wchar_t* path, struct win32_stat *result)
+{
+    return win32_xstat_w(path, result, FALSE);
+}
+
+static int
+win32_stat(const char* path, struct win32_stat *result)
+{
+    return win32_xstat(path, result, TRUE);
+}
+
+static int
+win32_stat_w(const wchar_t* path, struct win32_stat *result)
+{
+    return win32_xstat_w(path, result, TRUE);
+}
+
+static int
+win32_fstat(int file_number, struct win32_stat *result)
+{
+    BY_HANDLE_FILE_INFORMATION info;
+    HANDLE h;
+    int type;
+
+    h = (HANDLE)_get_osfhandle(file_number);
+
+    /* Protocol violation: we explicitly clear errno, instead of
+       setting it to a POSIX error. Callers should use GetLastError. */
+    errno = 0;
+
+    if (h == INVALID_HANDLE_VALUE) {
+        /* This is really a C library error (invalid file handle).
+           We set the Win32 error to the closes one matching. */
+        SetLastError(ERROR_INVALID_HANDLE);
         return -1;
     }
     memset(result, 0, sizeof(*result));
@@ -1309,7 +1360,7 @@
     if (type == FILE_TYPE_UNKNOWN) {
         DWORD error = GetLastError();
         if (error != 0) {
-        return -1;
+            return -1;
         }
         /* else: valid but unknown file */
     }
@@ -1326,17 +1377,8 @@
         return -1;
     }
 
-    /* similar to stat() */
-    result->st_mode = attributes_to_mode(info.dwFileAttributes);
-    result->st_size = (((__int64)info.nFileSizeHigh)<<32) + info.nFileSizeLow;
-    FILE_TIME_to_time_t_nsec(&info.ftCreationTime, &result->st_ctime,
-                             &result->st_ctime_nsec);
-    FILE_TIME_to_time_t_nsec(&info.ftLastWriteTime, &result->st_mtime,
-                             &result->st_mtime_nsec);
-    FILE_TIME_to_time_t_nsec(&info.ftLastAccessTime, &result->st_atime,
-                             &result->st_atime_nsec);
+    attribute_data_to_stat(&info, 0, result);
     /* specific to fstat() */
-    result->st_nlink = info.nNumberOfLinks;
     result->st_ino = (((__int64)info.nFileIndexHigh)<<32) + info.nFileIndexLow;
     return 0;
 }
@@ -2057,7 +2099,7 @@
 static PyObject *
 posix_fsync(PyObject *self, PyObject *fdobj)
 {
-       return posix_fildes(fdobj, fsync);
+    return posix_fildes(fdobj, fsync);
 }
 #endif /* HAVE_FSYNC */
 
@@ -2075,7 +2117,7 @@
 static PyObject *
 posix_fdatasync(PyObject *self, PyObject *fdobj)
 {
-       return posix_fildes(fdobj, fdatasync);
+    return posix_fildes(fdobj, fdatasync);
 }
 #endif /* HAVE_FDATASYNC */
 
@@ -2247,6 +2289,54 @@
 }
 #endif /* HAVE_LINK */
 
+#ifdef MS_WINDOWS
+PyDoc_STRVAR(win32_link__doc__,
+"link(src, dst)\n\n\
+Create a hard link to a file.");
+
+static PyObject *
+win32_link(PyObject *self, PyObject *args)
+{
+    PyObject *osrc, *odst;
+    char *src, *dst;
+    BOOL rslt;
+
+    PyUnicodeObject *usrc, *udst;
+    if (PyArg_ParseTuple(args, "UU:link", &usrc, &udst)) {
+        Py_BEGIN_ALLOW_THREADS
+        rslt = CreateHardLinkW(PyUnicode_AS_UNICODE(udst),
+                               PyUnicode_AS_UNICODE(usrc), NULL);
+        Py_END_ALLOW_THREADS
+
+        if (rslt == 0)
+            return win32_error("link", NULL);
+
+        Py_RETURN_NONE;
+    }
+
+    /* Narrow strings also valid. */
+    PyErr_Clear();
+
+    if (!PyArg_ParseTuple(args, "O&O&:link", PyUnicode_FSConverter, &osrc,
+                          PyUnicode_FSConverter, &odst))
+        return NULL;
+
+    src = PyBytes_AsString(osrc);
+    dst = PyBytes_AsString(odst);
+
+    Py_BEGIN_ALLOW_THREADS
+    rslt = CreateHardLinkA(dst, src, NULL);
+    Py_END_ALLOW_THREADS
+
+    Py_DECREF(osrc);
+    Py_DECREF(odst);
+    if (rslt == 0)
+        return win32_error("link", NULL);
+
+    Py_RETURN_NONE;
+}
+#endif /* MS_WINDOWS */
+
 
 PyDoc_STRVAR(posix_listdir__doc__,
 "listdir([path]) -> list_of_strings\n\n\
@@ -2277,7 +2367,7 @@
     if (PyArg_ParseTuple(args, "|U:listdir", &po)) {
         WIN32_FIND_DATAW wFileData;
         Py_UNICODE *wnamebuf, *po_wchars;
-        
+
         if (po == NULL) { /* Default arg: "." */
             po_wchars = L".";
             len = 1;
@@ -2371,6 +2461,7 @@
     }
     strcpy(namebuf, PyBytes_AsString(opath));
     len = PyObject_Size(opath);
+    Py_DECREF(opath);
     if (len > 0) {
         char ch = namebuf[len-1];
         if (ch != SEP && ch != ALTSEP && ch != ':')
@@ -2526,7 +2617,7 @@
     if (!PyArg_ParseTuple(args, "|O&:listdir", PyUnicode_FSConverter, &oname))
         return NULL;
     if (oname == NULL) { /* Default arg: "." */
-      oname = PyBytes_FromString(".");
+        oname = PyBytes_FromString(".");
     }
     name = PyBytes_AsString(oname);
     Py_BEGIN_ALLOW_THREADS
@@ -2587,6 +2678,76 @@
 #endif /* which OS */
 }  /* end of posix_listdir */
 
+#ifdef HAVE_FDOPENDIR
+PyDoc_STRVAR(posix_fdlistdir__doc__,
+"fdlistdir(fd) -> list_of_strings\n\n\
+Like listdir(), but uses a file descriptor instead.\n\
+After succesful execution of this function, fd will be closed.");
+
+static PyObject *
+posix_fdlistdir(PyObject *self, PyObject *args)
+{
+    PyObject *d, *v;
+    DIR *dirp;
+    struct dirent *ep;
+    int fd;
+
+    errno = 0;
+    if (!PyArg_ParseTuple(args, "i:fdlistdir", &fd))
+        return NULL;
+    Py_BEGIN_ALLOW_THREADS
+    dirp = fdopendir(fd);
+    Py_END_ALLOW_THREADS
+    if (dirp == NULL) {
+        close(fd);
+        return posix_error();
+    }
+    if ((d = PyList_New(0)) == NULL) {
+        Py_BEGIN_ALLOW_THREADS
+        closedir(dirp);
+        Py_END_ALLOW_THREADS
+        return NULL;
+    }
+    for (;;) {
+        errno = 0;
+        Py_BEGIN_ALLOW_THREADS
+        ep = readdir(dirp);
+        Py_END_ALLOW_THREADS
+        if (ep == NULL) {
+            if (errno == 0) {
+                break;
+            } else {
+                Py_BEGIN_ALLOW_THREADS
+                closedir(dirp);
+                Py_END_ALLOW_THREADS
+                Py_DECREF(d);
+                return posix_error();
+            }
+        }
+        if (ep->d_name[0] == '.' &&
+            (NAMLEN(ep) == 1 ||
+             (ep->d_name[1] == '.' && NAMLEN(ep) == 2)))
+            continue;
+        v = PyUnicode_DecodeFSDefaultAndSize(ep->d_name, NAMLEN(ep));
+        if (v == NULL) {
+            Py_CLEAR(d);
+            break;
+        }
+        if (PyList_Append(d, v) != 0) {
+            Py_DECREF(v);
+            Py_CLEAR(d);
+            break;
+        }
+        Py_DECREF(v);
+    }
+    Py_BEGIN_ALLOW_THREADS
+    closedir(dirp);
+    Py_END_ALLOW_THREADS
+
+    return d;
+}
+#endif
+
 #ifdef MS_WINDOWS
 /* A helper function for abspath on win32 */
 static PyObject *
@@ -2644,6 +2805,30 @@
     return PyBytes_FromString(outbuf);
 } /* end of posix__getfullpathname */
 
+/* Grab GetFinalPathNameByHandle dynamically from kernel32 */
+static int has_GetFinalPathNameByHandle = 0;
+static DWORD (CALLBACK *Py_GetFinalPathNameByHandleA)(HANDLE, LPSTR, DWORD,
+                                                      DWORD);
+static DWORD (CALLBACK *Py_GetFinalPathNameByHandleW)(HANDLE, LPWSTR, DWORD,
+                                                      DWORD);
+static int
+check_GetFinalPathNameByHandle()
+{
+    HINSTANCE hKernel32;
+    /* only recheck */
+    if (!has_GetFinalPathNameByHandle)
+    {
+        hKernel32 = GetModuleHandle("KERNEL32");
+        *(FARPROC*)&Py_GetFinalPathNameByHandleA = GetProcAddress(hKernel32,
+                                                "GetFinalPathNameByHandleA");
+        *(FARPROC*)&Py_GetFinalPathNameByHandleW = GetProcAddress(hKernel32,
+                                                "GetFinalPathNameByHandleW");
+        has_GetFinalPathNameByHandle = Py_GetFinalPathNameByHandleA &&
+                                       Py_GetFinalPathNameByHandleW;
+    }
+    return has_GetFinalPathNameByHandle;
+}
+
 /* A helper function for samepath on windows */
 static PyObject *
 posix__getfinalpathname(PyObject *self, PyObject *args)
@@ -2654,7 +2839,7 @@
     int result_length;
     PyObject *result;
     wchar_t *path;
-    
+
     if (!PyArg_ParseTuple(args, "u|:_getfinalpathname", &path)) {
         return NULL;
     }
@@ -2675,7 +2860,7 @@
         /* FILE_FLAG_BACKUP_SEMANTICS is required to open a directory */
         FILE_FLAG_BACKUP_SEMANTICS,
         NULL);
-    
+
     if(hFile == INVALID_HANDLE_VALUE) {
         return win32_error_unicode("GetFinalPathNamyByHandle", path);
         return PyErr_Format(PyExc_RuntimeError,
@@ -2718,14 +2903,12 @@
     if (!PyArg_ParseTuple(args, "i:_getfileinformation", &fd))
         return NULL;
 
-    if (!_PyVerify_fd(fd)) {
-        PyErr_SetString(PyExc_ValueError, "received invalid file descriptor");
-        return NULL;
-    }
+    if (!_PyVerify_fd(fd))
+        return posix_error();
 
     hFile = (HANDLE)_get_osfhandle(fd);
     if (hFile == INVALID_HANDLE_VALUE)
-        return win32_error("_getfileinformation", NULL);
+        return posix_error();
 
     if (!GetFileInformationByHandle(hFile, &info))
         return win32_error("_getfileinformation", NULL);
@@ -2845,6 +3028,52 @@
 }
 #endif /* HAVE_NICE */
 
+
+#ifdef HAVE_GETPRIORITY
+PyDoc_STRVAR(posix_getpriority__doc__,
+"getpriority(which, who) -> current_priority\n\n\
+Get program scheduling priority.");
+
+static PyObject *
+posix_getpriority(PyObject *self, PyObject *args)
+{
+    int which, who, retval;
+
+    if (!PyArg_ParseTuple(args, "ii", &which, &who))
+        return NULL;
+    errno = 0;
+    Py_BEGIN_ALLOW_THREADS
+    retval = getpriority(which, who);
+    Py_END_ALLOW_THREADS
+    if (errno != 0)
+        return posix_error();
+    return PyLong_FromLong((long)retval);
+}
+#endif /* HAVE_GETPRIORITY */
+
+
+#ifdef HAVE_SETPRIORITY
+PyDoc_STRVAR(posix_setpriority__doc__,
+"setpriority(which, who, prio) -> None\n\n\
+Set program scheduling priority.");
+
+static PyObject *
+posix_setpriority(PyObject *self, PyObject *args)
+{
+    int which, who, prio, retval;
+
+    if (!PyArg_ParseTuple(args, "iii", &which, &who, &prio))
+        return NULL;
+    Py_BEGIN_ALLOW_THREADS
+    retval = setpriority(which, who, prio);
+    Py_END_ALLOW_THREADS
+    if (retval == -1)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif /* HAVE_SETPRIORITY */
+
+
 PyDoc_STRVAR(posix_rename__doc__,
 "rename(old, new)\n\n\
 Rename a file or directory.");
@@ -2987,7 +3216,7 @@
 
     if (GetFileAttributesExW(lpFileName, GetFileExInfoStandard, &info)) {
         is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
-        
+
         /* Get WIN32_FIND_DATA structure for the path to determine if
            it is a symlink */
         if(is_directory &&
@@ -3054,15 +3283,19 @@
 #endif /* HAVE_UNAME */
 
 static int
-extract_time(PyObject *t, long* sec, long* usec)
+extract_time(PyObject *t, time_t* sec, long* usec)
 {
-    long intval;
+    time_t intval;
     if (PyFloat_Check(t)) {
         double tval = PyFloat_AsDouble(t);
-        PyObject *intobj = Py_TYPE(t)->tp_as_number->nb_int(t);
+        PyObject *intobj = PyNumber_Long(t);
         if (!intobj)
             return -1;
+#if SIZEOF_TIME_T > SIZEOF_LONG
+        intval = PyLong_AsUnsignedLongLongMask(intobj);
+#else
         intval = PyLong_AsLong(intobj);
+#endif
         Py_DECREF(intobj);
         if (intval == -1 && PyErr_Occurred())
             return -1;
@@ -3074,7 +3307,11 @@
             *usec = 0;
         return 0;
     }
+#if SIZEOF_TIME_T > SIZEOF_LONG
+    intval = PyLong_AsUnsignedLongLongMask(t);
+#else
     intval = PyLong_AsLong(t);
+#endif
     if (intval == -1 && PyErr_Occurred())
         return -1;
     *sec = intval;
@@ -3098,7 +3335,8 @@
     PyObject *oapath;
     char *apath;
     HANDLE hFile;
-    long atimesec, mtimesec, ausec, musec;
+    time_t atimesec, mtimesec;
+    long ausec, musec;
     FILETIME atime, mtime;
     PyObject *result = NULL;
 
@@ -3141,7 +3379,7 @@
             !SystemTimeToFileTime(&now, &atime)) {
             win32_error("utime", NULL);
             goto done;
-            }
+        }
     }
     else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
         PyErr_SetString(PyExc_TypeError,
@@ -3164,6 +3402,7 @@
            something is wrong with the file, when it also
            could be the time stamp that gives a problem. */
         win32_error("utime", NULL);
+        goto done;
     }
     Py_INCREF(Py_None);
     result = Py_None;
@@ -3174,7 +3413,8 @@
 
     PyObject *opath;
     char *path;
-    long atime, mtime, ausec, musec;
+    time_t atime, mtime;
+    long ausec, musec;
     int res;
     PyObject* arg;
 
@@ -4166,7 +4406,7 @@
 #endif
     gid_t grouplist[MAX_GROUPS];
 
-    /* On MacOSX getgroups(2) can return more than MAX_GROUPS results 
+    /* On MacOSX getgroups(2) can return more than MAX_GROUPS results
      * This is a helper variable to store the intermediate result when
      * that happens.
      *
@@ -4209,9 +4449,9 @@
         for (i = 0; i < n; ++i) {
             PyObject *o = PyLong_FromLong((long)alt_grouplist[i]);
             if (o == NULL) {
-            Py_DECREF(result);
-            result = NULL;
-            break;
+                Py_DECREF(result);
+                result = NULL;
+                break;
             }
             PyList_SET_ITEM(result, i, o);
         }
@@ -4382,15 +4622,15 @@
 posix_getlogin(PyObject *self, PyObject *noargs)
 {
     PyObject *result = NULL;
-#ifdef MS_WINDOWS    
+#ifdef MS_WINDOWS
     wchar_t user_name[UNLEN + 1];
     DWORD num_chars = sizeof(user_name)/sizeof(user_name[0]);
 
     if (GetUserNameW(user_name, &num_chars)) {
         /* num_chars is the number of unicode chars plus null terminator */
         result = PyUnicode_FromWideChar(user_name, num_chars - 1);
-    } 
-    else 
+    }
+    else
         result = PyErr_SetFromWindowsErr(GetLastError());
 #else
     char *name;
@@ -5026,7 +5266,7 @@
 #endif /* HAVE_READLINK */
 
 
-#ifdef HAVE_SYMLINK
+#if defined(HAVE_SYMLINK) && !defined(MS_WINDOWS)
 PyDoc_STRVAR(posix_symlink__doc__,
 "symlink(src, dst)\n\n\
 Create a symbolic link pointing to src named dst.");
@@ -5044,43 +5284,6 @@
 "readlink(path) -> path\n\n\
 Return a string representing the path to which the symbolic link points.");
 
-/* The following structure was copied from
-   http://msdn.microsoft.com/en-us/library/ms791514.aspx as the required
-   include doesn't seem to be present in the Windows SDK (at least as included
-   with Visual Studio Express). */
-typedef struct _REPARSE_DATA_BUFFER {
-    ULONG ReparseTag;
-    USHORT ReparseDataLength;
-    USHORT Reserved;
-    union {
-        struct {
-            USHORT SubstituteNameOffset;
-            USHORT SubstituteNameLength;
-            USHORT PrintNameOffset;
-            USHORT PrintNameLength;
-            ULONG Flags;
-            WCHAR PathBuffer[1];
-        } SymbolicLinkReparseBuffer;
-
-        struct {
-            USHORT SubstituteNameOffset;
-            USHORT  SubstituteNameLength;
-            USHORT  PrintNameOffset;
-            USHORT  PrintNameLength;
-            WCHAR  PathBuffer[1];
-        } MountPointReparseBuffer;
-
-        struct {
-            UCHAR  DataBuffer[1];
-        } GenericReparseBuffer;
-    };
-} REPARSE_DATA_BUFFER, *PREPARSE_DATA_BUFFER;
-
-#define REPARSE_DATA_BUFFER_HEADER_SIZE  FIELD_OFFSET(REPARSE_DATA_BUFFER,\
-                                                      GenericReparseBuffer)
-
-#define MAXIMUM_REPARSE_DATA_BUFFER_SIZE  ( 16 * 1024 )
-
 /* Windows readlink implementation */
 static PyObject *
 win_readlink(PyObject *self, PyObject *args)
@@ -5111,12 +5314,12 @@
         FILE_FLAG_OPEN_REPARSE_POINT|FILE_FLAG_BACKUP_SEMANTICS,
         0);
     Py_END_ALLOW_THREADS
-    
+
     if (reparse_point_handle==INVALID_HANDLE_VALUE)
     {
         return win32_error_unicode("readlink", path);
     }
-    
+
     Py_BEGIN_ALLOW_THREADS
     /* New call DeviceIoControl to read the reparse point */
     io_result = DeviceIoControl(
@@ -5151,7 +5354,7 @@
 
 #endif /* !defined(HAVE_READLINK) && defined(MS_WINDOWS) */
 
-#if !defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
+#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
 
 /* Grab CreateSymbolicLinkW dynamically from kernel32 */
 static int has_CreateSymbolicLinkW = 0;
@@ -5187,7 +5390,7 @@
     int target_is_directory = 0;
     DWORD res;
     WIN32_FILE_ATTRIBUTE_DATA src_info;
-    
+
     if (!check_CreateSymbolicLinkW())
     {
         /* raise NotImplementedError */
@@ -5197,12 +5400,16 @@
     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "OO|i:symlink",
         kwlist, &src, &dest, &target_is_directory))
         return NULL;
+
+    if (win32_can_symlink == 0)
+        return PyErr_Format(PyExc_OSError, "symbolic link privilege not held");
+
     if (!convert_to_unicode(&src)) { return NULL; }
     if (!convert_to_unicode(&dest)) {
         Py_DECREF(src);
         return NULL;
     }
-    
+
     /* if src is a directory, ensure target_is_directory==1 */
     if(
         GetFileAttributesExW(
@@ -5225,11 +5432,11 @@
     {
         return win32_error_unicode("symlink", PyUnicode_AsUnicode(src));
     }
-    
+
     Py_INCREF(Py_None);
     return Py_None;
 }
-#endif /* !defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
+#endif /* defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
 
 #ifdef HAVE_TIMES
 #if defined(PYCC_VACPP) && defined(PYOS_OS2)
@@ -5610,8 +5817,10 @@
     buffer = PyBytes_FromStringAndSize((char *)NULL, size);
     if (buffer == NULL)
         return NULL;
-    if (!_PyVerify_fd(fd))
+    if (!_PyVerify_fd(fd)) {
+        Py_DECREF(buffer);
         return posix_error();
+    }
     Py_BEGIN_ALLOW_THREADS
     n = read(fd, PyBytes_AS_STRING(buffer), size);
     Py_END_ALLOW_THREADS
@@ -5634,21 +5843,203 @@
 {
     Py_buffer pbuf;
     int fd;
-    Py_ssize_t size;
+    Py_ssize_t size, len;
 
     if (!PyArg_ParseTuple(args, "iy*:write", &fd, &pbuf))
         return NULL;
-    if (!_PyVerify_fd(fd))
+    if (!_PyVerify_fd(fd)) {
+        PyBuffer_Release(&pbuf);
         return posix_error();
+    }
+    len = pbuf.len;
     Py_BEGIN_ALLOW_THREADS
-    size = write(fd, pbuf.buf, (size_t)pbuf.len);
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+    if (len > INT_MAX)
+        len = INT_MAX;
+    size = write(fd, pbuf.buf, (int)len);
+#else
+    size = write(fd, pbuf.buf, len);
+#endif
     Py_END_ALLOW_THREADS
-        PyBuffer_Release(&pbuf);
+    PyBuffer_Release(&pbuf);
     if (size < 0)
         return posix_error();
     return PyLong_FromSsize_t(size);
 }
 
+#ifdef HAVE_SENDFILE
+#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
+static int
+iov_setup(struct iovec **iov, Py_buffer **buf, PyObject *seq, int cnt, int type)
+{
+    int i, j;
+    *iov = PyMem_New(struct iovec, cnt);
+    if (*iov == NULL) {
+        PyErr_NoMemory();
+        return 0;
+    }
+    *buf = PyMem_New(Py_buffer, cnt);
+    if (*buf == NULL) {
+        PyMem_Del(*iov);
+        PyErr_NoMemory();
+        return 0;
+    }
+
+    for (i = 0; i < cnt; i++) {
+        if (PyObject_GetBuffer(PySequence_GetItem(seq, i), &(*buf)[i],
+                type) == -1) {
+            PyMem_Del(*iov);
+            for (j = 0; j < i; j++) {
+                PyBuffer_Release(&(*buf)[j]);
+           }
+            PyMem_Del(*buf);
+            return 0;
+        }
+        (*iov)[i].iov_base = (*buf)[i].buf;
+        (*iov)[i].iov_len = (*buf)[i].len;
+    }
+    return 1;
+}
+
+static void
+iov_cleanup(struct iovec *iov, Py_buffer *buf, int cnt)
+{
+    int i;
+    PyMem_Del(iov);
+    for (i = 0; i < cnt; i++) {
+        PyBuffer_Release(&buf[i]);
+    }
+    PyMem_Del(buf);
+}
+#endif
+
+PyDoc_STRVAR(posix_sendfile__doc__,
+"sendfile(out, in, offset, nbytes) -> byteswritten\n\
+sendfile(out, in, offset, nbytes, headers=None, trailers=None, flags=0)\n\
+            -> byteswritten\n\
+Copy nbytes bytes from file descriptor in to file descriptor out.");
+
+static PyObject *
+posix_sendfile(PyObject *self, PyObject *args, PyObject *kwdict)
+{
+    int in, out;
+    Py_ssize_t ret;
+    off_t offset;
+
+#if defined(__FreeBSD__) || defined(__DragonFly__) || defined(__APPLE__)
+#ifndef __APPLE__
+    Py_ssize_t len;
+#endif
+    PyObject *headers = NULL, *trailers = NULL;
+    Py_buffer *hbuf, *tbuf;
+    off_t sbytes;
+    struct sf_hdtr sf;
+    int flags = 0;
+    sf.headers = NULL;
+    sf.trailers = NULL;
+    static char *keywords[] = {"out", "in",
+                                "offset", "count",
+                                "headers", "trailers", "flags", NULL};
+
+#ifdef __APPLE__
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&O&|OOi:sendfile",
+        keywords, &out, &in, _parse_off_t, &offset, _parse_off_t, &sbytes,
+#else
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiO&n|OOi:sendfile",
+        keywords, &out, &in, _parse_off_t, &offset, &len,
+#endif
+                &headers, &trailers, &flags))
+            return NULL;
+    if (headers != NULL) {
+        if (!PySequence_Check(headers)) {
+            PyErr_SetString(PyExc_TypeError,
+                "sendfile() headers must be a sequence or None");
+            return NULL;
+        } else {
+            sf.hdr_cnt = PySequence_Size(headers);
+            if (sf.hdr_cnt > 0 && !iov_setup(&(sf.headers), &hbuf,
+                    headers, sf.hdr_cnt, PyBUF_SIMPLE))
+                return NULL;
+        }
+    }
+    if (trailers != NULL) {
+        if (!PySequence_Check(trailers)) {
+            PyErr_SetString(PyExc_TypeError,
+                "sendfile() trailers must be a sequence or None");
+            return NULL;
+        } else {
+            sf.trl_cnt = PySequence_Size(trailers);
+            if (sf.trl_cnt > 0 && !iov_setup(&(sf.trailers), &tbuf,
+                    trailers, sf.trl_cnt, PyBUF_SIMPLE))
+                return NULL;
+        }
+    }
+
+    Py_BEGIN_ALLOW_THREADS
+#ifdef __APPLE__
+    ret = sendfile(in, out, offset, &sbytes, &sf, flags);
+#else
+    ret = sendfile(in, out, offset, len, &sf, &sbytes, flags);
+#endif
+    Py_END_ALLOW_THREADS
+
+    if (sf.headers != NULL)
+        iov_cleanup(sf.headers, hbuf, sf.hdr_cnt);
+    if (sf.trailers != NULL)
+        iov_cleanup(sf.trailers, tbuf, sf.trl_cnt);
+
+    if (ret < 0) {
+        if ((errno == EAGAIN) || (errno == EBUSY)) {
+            if (sbytes != 0) {
+                // some data has been sent
+                goto done;
+            }
+            else {
+                // no data has been sent; upper application is supposed
+                // to retry on EAGAIN or EBUSY
+                return posix_error();
+            }
+        }
+        return posix_error();
+    }
+    goto done;
+
+done:
+    #if !defined(HAVE_LARGEFILE_SUPPORT)
+        return Py_BuildValue("l", sbytes);
+    #else
+        return Py_BuildValue("L", sbytes);
+    #endif
+
+#else
+    Py_ssize_t count;
+    PyObject *offobj;
+    static char *keywords[] = {"out", "in",
+                                "offset", "count", NULL};
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iiOn:sendfile",
+            keywords, &out, &in, &offobj, &count))
+        return NULL;
+#ifdef linux
+    if (offobj == Py_None) {
+        Py_BEGIN_ALLOW_THREADS
+        ret = sendfile(out, in, NULL, count);
+        Py_END_ALLOW_THREADS
+        if (ret < 0)
+            return posix_error();
+        Py_INCREF(Py_None);
+        return Py_BuildValue("nO", ret, Py_None);
+    }
+#endif
+    _parse_off_t(offobj, &offset);
+    Py_BEGIN_ALLOW_THREADS
+    ret = sendfile(out, in, &offset, count);
+    Py_END_ALLOW_THREADS
+    if (ret < 0)
+        return posix_error();
+    return Py_BuildValue("n", ret);
+#endif
+}
+#endif
 
 PyDoc_STRVAR(posix_fstat__doc__,
 "fstat(fd) -> stat result\n\n\
@@ -6348,38 +6739,38 @@
               size_t tablesize)
 {
     if (PyLong_Check(arg)) {
-    *valuep = PyLong_AS_LONG(arg);
-    return 1;
+        *valuep = PyLong_AS_LONG(arg);
+        return 1;
     }
     else {
-    /* look up the value in the table using a binary search */
-    size_t lo = 0;
-    size_t mid;
-    size_t hi = tablesize;
-    int cmp;
-    const char *confname;
-    if (!PyUnicode_Check(arg)) {
-        PyErr_SetString(PyExc_TypeError,
-                        "configuration names must be strings or integers");
-        return 0;
-    }
-    confname = _PyUnicode_AsString(arg);
-    if (confname == NULL)
-        return 0;
-    while (lo < hi) {
-        mid = (lo + hi) / 2;
-        cmp = strcmp(confname, table[mid].name);
-        if (cmp < 0)
-        hi = mid;
-        else if (cmp > 0)
-        lo = mid + 1;
-        else {
-        *valuep = table[mid].value;
-        return 1;
+        /* look up the value in the table using a binary search */
+        size_t lo = 0;
+        size_t mid;
+        size_t hi = tablesize;
+        int cmp;
+        const char *confname;
+        if (!PyUnicode_Check(arg)) {
+            PyErr_SetString(PyExc_TypeError,
+                "configuration names must be strings or integers");
+            return 0;
         }
-    }
-    PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
-    return 0;
+        confname = _PyUnicode_AsString(arg);
+        if (confname == NULL)
+            return 0;
+        while (lo < hi) {
+            mid = (lo + hi) / 2;
+            cmp = strcmp(confname, table[mid].name);
+            if (cmp < 0)
+                hi = mid;
+            else if (cmp > 0)
+                lo = mid + 1;
+            else {
+                *valuep = table[mid].value;
+                return 1;
+            }
+        }
+        PyErr_SetString(PyExc_ValueError, "unrecognized configuration name");
+        return 0;
     }
 }
 
@@ -6495,14 +6886,14 @@
 
     if (PyArg_ParseTuple(args, "iO&:fpathconf", &fd,
                          conv_path_confname, &name)) {
-    long limit;
+        long limit;
 
-    errno = 0;
-    limit = fpathconf(fd, name);
-    if (limit == -1 && errno != 0)
-        posix_error();
-    else
-        result = PyLong_FromLong(limit);
+        errno = 0;
+        limit = fpathconf(fd, name);
+        if (limit == -1 && errno != 0)
+            posix_error();
+        else
+            result = PyLong_FromLong(limit);
     }
     return result;
 }
@@ -6530,10 +6921,10 @@
     limit = pathconf(path, name);
     if (limit == -1 && errno != 0) {
         if (errno == EINVAL)
-        /* could be a path or name problem */
-        posix_error();
+            /* could be a path or name problem */
+            posix_error();
         else
-        posix_error_with_filename(path);
+            posix_error_with_filename(path);
     }
     else
         result = PyLong_FromLong(limit);
@@ -6714,7 +7105,7 @@
     PyObject *result = NULL;
     int name;
     char buffer[255];
-        int len;
+    int len;
 
     if (!PyArg_ParseTuple(args, "O&:confstr", conv_confstr_confname, &name))
         return NULL;
@@ -7329,21 +7720,21 @@
                              sizeof(posix_constants_pathconf)
                                / sizeof(struct constdef),
                              "pathconf_names", module))
-    return -1;
+        return -1;
 #endif
 #ifdef HAVE_CONFSTR
     if (setup_confname_table(posix_constants_confstr,
                              sizeof(posix_constants_confstr)
                                / sizeof(struct constdef),
                              "confstr_names", module))
-    return -1;
+        return -1;
 #endif
 #ifdef HAVE_SYSCONF
     if (setup_confname_table(posix_constants_sysconf,
                              sizeof(posix_constants_sysconf)
                                / sizeof(struct constdef),
                              "sysconf_names", module))
-    return -1;
+        return -1;
 #endif
     return 0;
 }
@@ -7456,10 +7847,10 @@
 {
     double loadavg[3];
     if (getloadavg(loadavg, 3)!=3) {
-    PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
-    return NULL;
+        PyErr_SetString(PyExc_OSError, "Load averages are unobtainable");
+        return NULL;
     } else
-    return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
+        return Py_BuildValue("ddd", loadavg[0], loadavg[1], loadavg[2]);
 }
 #endif
 
@@ -7688,6 +8079,552 @@
 }
 #endif
 
+/* Posix *at family of functions:
+    faccessat, fchmodat, fchownat, fstatat, futimesat,
+    linkat, mkdirat, mknodat, openat, readlinkat, renameat, symlinkat,
+    unlinkat, utimensat, mkfifoat */
+
+#ifdef HAVE_FACCESSAT
+PyDoc_STRVAR(posix_faccessat__doc__,
+"faccessat(dirfd, path, mode, flags=0) -> True if granted, False otherwise\n\n\
+Like access() but if path is relative, it is taken as relative to dirfd.\n\
+flags is optional and can be constructed by ORing together zero or more\n\
+of these values: AT_SYMLINK_NOFOLLOW, AT_EACCESS.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_faccessat(PyObject *self, PyObject *args)
+{
+    PyObject *opath;
+    char *path;
+    int mode;
+    int res;
+    int dirfd, flags = 0;
+    if (!PyArg_ParseTuple(args, "iO&i|i:faccessat",
+            &dirfd, PyUnicode_FSConverter, &opath, &mode, &flags))
+        return NULL;
+    path = PyBytes_AsString(opath);
+    Py_BEGIN_ALLOW_THREADS
+    res = faccessat(dirfd, path, mode, flags);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
+    return PyBool_FromLong(res == 0);
+}
+#endif
+
+#ifdef HAVE_FCHMODAT
+PyDoc_STRVAR(posix_fchmodat__doc__,
+"fchmodat(dirfd, path, mode, flags=0)\n\n\
+Like chmod() but if path is relative, it is taken as relative to dirfd.\n\
+flags is optional and may be 0 or AT_SYMLINK_NOFOLLOW.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_fchmodat(PyObject *self, PyObject *args)
+{
+    int dirfd, mode, res;
+    int flags = 0;
+    PyObject *opath;
+    char *path;
+
+    if (!PyArg_ParseTuple(args, "iO&i|i:fchmodat",
+            &dirfd, PyUnicode_FSConverter, &opath, &mode, &flags))
+        return NULL;
+
+    path = PyBytes_AsString(opath);
+
+    Py_BEGIN_ALLOW_THREADS
+    res = fchmodat(dirfd, path, mode, flags);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
+    if (res < 0)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif /* HAVE_FCHMODAT */
+
+#ifdef HAVE_FCHOWNAT
+PyDoc_STRVAR(posix_fchownat__doc__,
+"fchownat(dirfd, path, uid, gid, flags=0)\n\n\
+Like chown() but if path is relative, it is taken as relative to dirfd.\n\
+flags is optional and may be 0 or AT_SYMLINK_NOFOLLOW.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_fchownat(PyObject *self, PyObject *args)
+{
+    PyObject *opath;
+    int dirfd, res;
+    long uid, gid;
+    int flags = 0;
+    char *path;
+    
+    if (!PyArg_ParseTuple(args, "iO&ll|i:fchownat",
+            &dirfd, PyUnicode_FSConverter, &opath, &uid, &gid, &flags))
+        return NULL;
+
+    path = PyBytes_AsString(opath);
+
+    Py_BEGIN_ALLOW_THREADS
+    res = fchownat(dirfd, path, (uid_t) uid, (gid_t) gid, flags);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
+    if (res < 0)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif /* HAVE_FCHOWNAT */
+
+#ifdef HAVE_FSTATAT
+PyDoc_STRVAR(posix_fstatat__doc__,
+"fstatat(dirfd, path, flags=0) -> stat result\n\n\
+Like stat() but if path is relative, it is taken as relative to dirfd.\n\
+flags is optional and may be 0 or AT_SYMLINK_NOFOLLOW.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_fstatat(PyObject *self, PyObject *args)
+{
+    PyObject *opath;
+    char *path;
+    STRUCT_STAT st;
+    int dirfd, res, flags = 0;
+
+    if (!PyArg_ParseTuple(args, "iO&|i:fstatat",
+            &dirfd, PyUnicode_FSConverter, &opath, &flags))
+        return NULL;
+    path = PyBytes_AsString(opath);
+
+    Py_BEGIN_ALLOW_THREADS
+    res = fstatat(dirfd, path, &st, flags);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
+    if (res != 0)
+        return posix_error();
+
+    return _pystat_fromstructstat(&st);
+}
+#endif
+
+#ifdef HAVE_FUTIMESAT
+PyDoc_STRVAR(posix_futimesat__doc__,
+"futimesat(dirfd, path, (atime, mtime))\n\
+futimesat(dirfd, path, None)\n\n\
+Like utime() but if path is relative, it is taken as relative to dirfd.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_futimesat(PyObject *self, PyObject *args)
+{
+    PyObject *opath;
+    char *path;
+    int res, dirfd;
+    PyObject* arg;
+
+    struct timeval buf[2];
+
+    if (!PyArg_ParseTuple(args, "iO&O:futimesat",
+            &dirfd, PyUnicode_FSConverter, &opath, &arg))
+        return NULL;
+    path = PyBytes_AsString(opath);
+    if (arg == Py_None) {
+        /* optional time values not given */
+        Py_BEGIN_ALLOW_THREADS
+        res = futimesat(dirfd, path, NULL);
+        Py_END_ALLOW_THREADS
+    }
+    else if (!PyTuple_Check(arg) || PyTuple_Size(arg) != 2) {
+        PyErr_SetString(PyExc_TypeError,
+                "futimesat() arg 3 must be a tuple (atime, mtime)");
+        Py_DECREF(opath);
+        return NULL;
+    }
+    else {
+        if (extract_time(PyTuple_GET_ITEM(arg, 0),
+				&(buf[0].tv_sec), &(buf[0].tv_usec)) == -1) {
+            Py_DECREF(opath);
+            return NULL;
+        }
+        if (extract_time(PyTuple_GET_ITEM(arg, 1),
+				&(buf[1].tv_sec), &(buf[1].tv_usec)) == -1) {
+            Py_DECREF(opath);
+            return NULL;
+        }
+        Py_BEGIN_ALLOW_THREADS
+        res = futimesat(dirfd, path, buf);
+        Py_END_ALLOW_THREADS
+    }
+    Py_DECREF(opath);
+    if (res < 0) {
+        return posix_error();
+    }
+    Py_RETURN_NONE;
+}
+#endif
+
+#ifdef HAVE_LINKAT
+PyDoc_STRVAR(posix_linkat__doc__,
+"linkat(srcfd, srcpath, dstfd, dstpath, flags=0)\n\n\
+Like link() but if srcpath is relative, it is taken as relative to srcfd\n\
+and if dstpath is relative, it is taken as relative to dstfd.\n\
+flags is optional and may be 0 or AT_SYMLINK_FOLLOW.\n\
+If srcpath is relative and srcfd is the special value AT_FDCWD, then\n\
+srcpath is interpreted relative to the current working directory. This\n\
+also applies for dstpath.");
+
+static PyObject *
+posix_linkat(PyObject *self, PyObject *args)
+{
+    PyObject *osrc, *odst;
+    char *src, *dst;
+    int res, srcfd, dstfd;
+    int flags = 0;
+
+    if (!PyArg_ParseTuple(args, "iO&iO&|i:linkat",
+            &srcfd, PyUnicode_FSConverter, &osrc, &dstfd, PyUnicode_FSConverter, &odst, &flags))
+        return NULL;
+    src = PyBytes_AsString(osrc);
+    dst = PyBytes_AsString(odst);
+    Py_BEGIN_ALLOW_THREADS
+    res = linkat(srcfd, src, dstfd, dst, flags);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(osrc);
+    Py_DECREF(odst);
+    if (res < 0)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif /* HAVE_LINKAT */
+
+#ifdef HAVE_MKDIRAT
+PyDoc_STRVAR(posix_mkdirat__doc__,
+"mkdirat(dirfd, path, mode=0o777)\n\n\
+Like mkdir() but if path is relative, it is taken as relative to dirfd.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_mkdirat(PyObject *self, PyObject *args)
+{
+    int res, dirfd;
+    PyObject *opath;
+    char *path;
+    int mode = 0777;
+
+    if (!PyArg_ParseTuple(args, "iO&|i:mkdirat",
+            &dirfd, PyUnicode_FSConverter, &opath, &mode))
+        return NULL;
+    path = PyBytes_AsString(opath);
+    Py_BEGIN_ALLOW_THREADS
+    res = mkdirat(dirfd, path, mode);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
+    if (res < 0)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif
+
+#if defined(HAVE_MKNODAT) && defined(HAVE_MAKEDEV)
+PyDoc_STRVAR(posix_mknodat__doc__,
+"mknodat(dirfd, path, mode=0o600, device=0)\n\n\
+Like mknod() but if path is relative, it is taken as relative to dirfd.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_mknodat(PyObject *self, PyObject *args)
+{
+    PyObject *opath;
+    char *filename;
+    int mode = 0600;
+    int device = 0;
+    int res, dirfd;
+    if (!PyArg_ParseTuple(args, "iO&|ii:mknodat", &dirfd,
+            PyUnicode_FSConverter, &opath, &mode, &device))
+        return NULL;
+    filename = PyBytes_AS_STRING(opath);
+    Py_BEGIN_ALLOW_THREADS
+    res = mknodat(dirfd, filename, mode, device);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
+    if (res < 0)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif
+
+#ifdef HAVE_OPENAT
+PyDoc_STRVAR(posix_openat__doc__,
+"openat(dirfd, path, flag, mode=0o777) -> fd\n\n\
+Like open() but if path is relative, it is taken as relative to dirfd.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_openat(PyObject *self, PyObject *args)
+{
+    PyObject *ofile;
+    char *file;
+    int flag, dirfd, fd;
+    int mode = 0777;
+
+    if (!PyArg_ParseTuple(args, "iO&i|i:openat",
+            &dirfd, PyUnicode_FSConverter, &ofile,
+            &flag, &mode))
+        return NULL;
+    file = PyBytes_AsString(ofile);
+    Py_BEGIN_ALLOW_THREADS
+    fd = openat(dirfd, file, flag, mode);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(ofile);
+    if (fd < 0)
+        return posix_error();
+    return PyLong_FromLong((long)fd);
+}
+#endif
+
+#ifdef HAVE_READLINKAT
+PyDoc_STRVAR(posix_readlinkat__doc__,
+"readlinkat(dirfd, path) -> path\n\n\
+Like readlink() but if path is relative, it is taken as relative to dirfd.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_readlinkat(PyObject *self, PyObject *args)
+{
+    PyObject *v, *opath;
+    char buf[MAXPATHLEN];
+    char *path;
+    int n, dirfd;
+    int arg_is_unicode = 0;
+
+    if (!PyArg_ParseTuple(args, "iO&:readlinkat",
+            &dirfd, PyUnicode_FSConverter, &opath))
+        return NULL;
+    path = PyBytes_AsString(opath);
+    v = PySequence_GetItem(args, 1);
+    if (v == NULL) {
+        Py_DECREF(opath);
+        return NULL;
+    }
+
+    if (PyUnicode_Check(v)) {
+        arg_is_unicode = 1;
+    }
+    Py_DECREF(v);
+
+    Py_BEGIN_ALLOW_THREADS
+    n = readlinkat(dirfd, path, buf, (int) sizeof buf);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
+    if (n < 0)
+        return posix_error();
+
+    if (arg_is_unicode)
+        return PyUnicode_DecodeFSDefaultAndSize(buf, n);
+    else
+        return PyBytes_FromStringAndSize(buf, n);
+}
+#endif /* HAVE_READLINKAT */
+
+#ifdef HAVE_RENAMEAT
+PyDoc_STRVAR(posix_renameat__doc__,
+"renameat(olddirfd, oldpath, newdirfd, newpath)\n\n\
+Like rename() but if oldpath is relative, it is taken as relative to\n\
+olddirfd and if newpath is relative, it is taken as relative to newdirfd.\n\
+If oldpath is relative and olddirfd is the special value AT_FDCWD, then\n\
+oldpath is interpreted relative to the current working directory. This\n\
+also applies for newpath.");
+
+static PyObject *
+posix_renameat(PyObject *self, PyObject *args)
+{
+    int res;
+    PyObject *opathold, *opathnew;
+    char *opath, *npath;
+    int oldfd, newfd;
+
+    if (!PyArg_ParseTuple(args, "iO&iO&:renameat",
+            &oldfd, PyUnicode_FSConverter, &opathold, &newfd, PyUnicode_FSConverter, &opathnew))
+        return NULL;
+    opath = PyBytes_AsString(opathold);
+    npath = PyBytes_AsString(opathnew);
+    Py_BEGIN_ALLOW_THREADS
+    res = renameat(oldfd, opath, newfd, npath);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opathold);
+    Py_DECREF(opathnew);
+    if (res < 0)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif
+
+#if HAVE_SYMLINKAT
+PyDoc_STRVAR(posix_symlinkat__doc__,
+"symlinkat(src, dstfd, dst)\n\n\
+Like symlink() but if dst is relative, it is taken as relative to dstfd.\n\
+If dst is relative and dstfd is the special value AT_FDCWD, then dst\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_symlinkat(PyObject *self, PyObject *args)
+{
+    int res, dstfd;
+    PyObject *osrc, *odst;
+    char *src, *dst;
+
+    if (!PyArg_ParseTuple(args, "O&iO&:symlinkat",
+            PyUnicode_FSConverter, &osrc, &dstfd, PyUnicode_FSConverter, &odst))
+        return NULL;
+    src = PyBytes_AsString(osrc);
+    dst = PyBytes_AsString(odst);
+    Py_BEGIN_ALLOW_THREADS
+    res = symlinkat(src, dstfd, dst);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(osrc);
+    Py_DECREF(odst);
+    if (res < 0)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif /* HAVE_SYMLINKAT */
+
+#ifdef HAVE_UNLINKAT
+PyDoc_STRVAR(posix_unlinkat__doc__,
+"unlinkat(dirfd, path, flags=0)\n\n\
+Like unlink() but if path is relative, it is taken as relative to dirfd.\n\
+flags is optional and may be 0 or AT_REMOVEDIR. If AT_REMOVEDIR is\n\
+specified, unlinkat() behaves like rmdir().\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_unlinkat(PyObject *self, PyObject *args)
+{
+    int dirfd, res, flags = 0;
+    PyObject *opath;
+    char *path;
+
+    if (!PyArg_ParseTuple(args, "iO&|i:unlinkat",
+            &dirfd, PyUnicode_FSConverter, &opath, &flags))
+        return NULL;
+    path = PyBytes_AsString(opath);
+    Py_BEGIN_ALLOW_THREADS
+    res = unlinkat(dirfd, path, flags);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
+    if (res < 0)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif
+
+#ifdef HAVE_UTIMENSAT
+PyDoc_STRVAR(posix_utimensat__doc__,
+"utimensat(dirfd, path, (atime_sec, atime_nsec),\n\
+    (mtime_sec, mtime_nsec), flags)\n\
+utimensat(dirfd, path, None, None, flags)\n\n\
+Updates the timestamps of a file with nanosecond precision. If path is\n\
+relative, it is taken as relative to dirfd.\n\
+The second form sets atime and mtime to the current time.\n\
+flags is optional and may be 0 or AT_SYMLINK_NOFOLLOW.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.\n\
+If *_nsec is specified as UTIME_NOW, the timestamp is updated to the\n\
+current time.\n\
+If *_nsec is specified as UTIME_OMIT, the timestamp is not updated.");
+
+static PyObject *
+posix_utimensat(PyObject *self, PyObject *args)
+{
+    PyObject *opath;
+    char *path;
+    int res, dirfd, flags = 0;
+    PyObject *atime, *mtime;
+
+    struct timespec buf[2];
+
+    if (!PyArg_ParseTuple(args, "iO&OO|i:utimensat",
+            &dirfd, PyUnicode_FSConverter, &opath, &atime, &mtime, &flags))
+        return NULL;
+    path = PyBytes_AsString(opath);
+    if (atime == Py_None && mtime == Py_None) {
+        /* optional time values not given */
+        Py_BEGIN_ALLOW_THREADS
+        res = utimensat(dirfd, path, NULL, flags);
+        Py_END_ALLOW_THREADS
+    }
+    else if (!PyTuple_Check(atime) || PyTuple_Size(atime) != 2) {
+        PyErr_SetString(PyExc_TypeError,
+            "utimensat() arg 3 must be a tuple (atime_sec, atime_nsec)");
+        Py_DECREF(opath);
+        return NULL;
+    }
+    else if (!PyTuple_Check(mtime) || PyTuple_Size(mtime) != 2) {
+        PyErr_SetString(PyExc_TypeError,
+            "utimensat() arg 4 must be a tuple (mtime_sec, mtime_nsec)");
+        Py_DECREF(opath);
+        return NULL;
+    }
+    else {
+        if (!PyArg_ParseTuple(atime, "ll:utimensat",
+                &(buf[0].tv_sec), &(buf[0].tv_nsec))) {
+            Py_DECREF(opath);
+            return NULL;
+        }
+        if (!PyArg_ParseTuple(mtime, "ll:utimensat",
+                &(buf[1].tv_sec), &(buf[1].tv_nsec))) {
+            Py_DECREF(opath);
+            return NULL;
+        }
+        Py_BEGIN_ALLOW_THREADS
+        res = utimensat(dirfd, path, buf, flags);
+        Py_END_ALLOW_THREADS
+    }
+    Py_DECREF(opath);
+    if (res < 0) {
+        return posix_error();
+    }
+    Py_RETURN_NONE;
+}
+#endif
+
+#ifdef HAVE_MKFIFOAT
+PyDoc_STRVAR(posix_mkfifoat__doc__,
+"mkfifoat(dirfd, path, mode=0o666)\n\n\
+Like mkfifo() but if path is relative, it is taken as relative to dirfd.\n\
+If path is relative and dirfd is the special value AT_FDCWD, then path\n\
+is interpreted relative to the current working directory.");
+
+static PyObject *
+posix_mkfifoat(PyObject *self, PyObject *args)
+{
+    PyObject *opath;
+    char *filename;
+    int mode = 0666;
+    int res, dirfd;
+    if (!PyArg_ParseTuple(args, "iO&|i:mkfifoat",
+            &dirfd, PyUnicode_FSConverter, &opath, &mode))
+        return NULL;
+    filename = PyBytes_AS_STRING(opath);
+    Py_BEGIN_ALLOW_THREADS
+    res = mkfifoat(dirfd, filename, mode);
+    Py_END_ALLOW_THREADS
+    Py_DECREF(opath);
+    if (res < 0)
+        return posix_error();
+    Py_RETURN_NONE;
+}
+#endif
+
 static PyMethodDef posix_methods[] = {
     {"access",          posix_access, METH_VARARGS, posix_access__doc__},
 #ifdef HAVE_TTYNAME
@@ -7732,11 +8669,20 @@
     {"link",            posix_link, METH_VARARGS, posix_link__doc__},
 #endif /* HAVE_LINK */
     {"listdir",         posix_listdir, METH_VARARGS, posix_listdir__doc__},
+#ifdef HAVE_FDOPENDIR
+    {"fdlistdir",       posix_fdlistdir, METH_VARARGS, posix_fdlistdir__doc__},
+#endif
     {"lstat",           posix_lstat, METH_VARARGS, posix_lstat__doc__},
     {"mkdir",           posix_mkdir, METH_VARARGS, posix_mkdir__doc__},
 #ifdef HAVE_NICE
     {"nice",            posix_nice, METH_VARARGS, posix_nice__doc__},
 #endif /* HAVE_NICE */
+#ifdef HAVE_GETPRIORITY
+    {"getpriority",     posix_getpriority, METH_VARARGS, posix_getpriority__doc__},
+#endif /* HAVE_GETPRIORITY */
+#ifdef HAVE_SETPRIORITY
+    {"setpriority",     posix_setpriority, METH_VARARGS, posix_setpriority__doc__},
+#endif /* HAVE_SETPRIORITY */
 #ifdef HAVE_READLINK
     {"readlink",        posix_readlink, METH_VARARGS, posix_readlink__doc__},
 #endif /* HAVE_READLINK */
@@ -7747,13 +8693,13 @@
     {"rmdir",           posix_rmdir, METH_VARARGS, posix_rmdir__doc__},
     {"stat",            posix_stat, METH_VARARGS, posix_stat__doc__},
     {"stat_float_times", stat_float_times, METH_VARARGS, stat_float_times__doc__},
-#ifdef HAVE_SYMLINK
+#if defined(HAVE_SYMLINK) && !defined(MS_WINDOWS)
     {"symlink",         posix_symlink, METH_VARARGS, posix_symlink__doc__},
 #endif /* HAVE_SYMLINK */
-#if !defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
+#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
     {"symlink", (PyCFunction)win_symlink, METH_VARARGS | METH_KEYWORDS,
-                win_symlink__doc__},
-#endif /* !defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
+                 win_symlink__doc__},
+#endif /* defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
 #ifdef HAVE_SYSTEM
     {"system",          posix_system, METH_VARARGS, posix_system__doc__},
 #endif
@@ -7829,6 +8775,7 @@
 #ifdef MS_WINDOWS
     {"startfile",       win32_startfile, METH_VARARGS, win32_startfile__doc__},
     {"kill",    win32_kill, METH_VARARGS, win32_kill__doc__},
+    {"link",    win32_link, METH_VARARGS, win32_link__doc__},
 #endif
 #ifdef HAVE_SETUID
     {"setuid",          posix_setuid, METH_VARARGS, posix_setuid__doc__},
@@ -7896,6 +8843,10 @@
     {"lseek",           posix_lseek, METH_VARARGS, posix_lseek__doc__},
     {"read",            posix_read, METH_VARARGS, posix_read__doc__},
     {"write",           posix_write, METH_VARARGS, posix_write__doc__},
+#ifdef HAVE_SENDFILE
+    {"sendfile",        (PyCFunction)posix_sendfile, METH_VARARGS | METH_KEYWORDS,
+                            posix_sendfile__doc__},
+#endif
     {"fstat",           posix_fstat, METH_VARARGS, posix_fstat__doc__},
     {"isatty",          posix_isatty, METH_VARARGS, posix_isatty__doc__},
 #ifdef HAVE_PIPE
@@ -8003,6 +8954,52 @@
     {"getresgid",       posix_getresgid, METH_NOARGS, posix_getresgid__doc__},
 #endif
 
+/* posix *at family of functions */
+#ifdef HAVE_FACCESSAT
+    {"faccessat",       posix_faccessat, METH_VARARGS, posix_faccessat__doc__},
+#endif
+#ifdef HAVE_FCHMODAT
+    {"fchmodat",        posix_fchmodat, METH_VARARGS, posix_fchmodat__doc__},
+#endif /* HAVE_FCHMODAT */
+#ifdef HAVE_FCHOWNAT
+    {"fchownat",        posix_fchownat, METH_VARARGS, posix_fchownat__doc__},
+#endif /* HAVE_FCHOWNAT */
+#ifdef HAVE_FSTATAT
+    {"fstatat",         posix_fstatat, METH_VARARGS, posix_fstatat__doc__},
+#endif
+#ifdef HAVE_FUTIMESAT
+    {"futimesat",       posix_futimesat, METH_VARARGS, posix_futimesat__doc__},
+#endif
+#ifdef HAVE_LINKAT
+    {"linkat",          posix_linkat, METH_VARARGS, posix_linkat__doc__},
+#endif /* HAVE_LINKAT */
+#ifdef HAVE_MKDIRAT
+    {"mkdirat",         posix_mkdirat, METH_VARARGS, posix_mkdirat__doc__},
+#endif
+#if defined(HAVE_MKNODAT) && defined(HAVE_MAKEDEV)
+    {"mknodat",         posix_mknodat, METH_VARARGS, posix_mknodat__doc__},
+#endif
+#ifdef HAVE_OPENAT
+    {"openat",      posix_openat, METH_VARARGS, posix_openat__doc__},
+#endif
+#ifdef HAVE_READLINKAT
+    {"readlinkat",      posix_readlinkat, METH_VARARGS, posix_readlinkat__doc__},
+#endif /* HAVE_READLINKAT */
+#ifdef HAVE_RENAMEAT
+    {"renameat",        posix_renameat, METH_VARARGS, posix_renameat__doc__},
+#endif
+#if HAVE_SYMLINKAT
+    {"symlinkat",       posix_symlinkat, METH_VARARGS, posix_symlinkat__doc__},
+#endif /* HAVE_SYMLINKAT */
+#ifdef HAVE_UNLINKAT
+    {"unlinkat",        posix_unlinkat, METH_VARARGS, posix_unlinkat__doc__},
+#endif
+#ifdef HAVE_UTIMENSAT
+    {"utimensat",       posix_utimensat, METH_VARARGS, posix_utimensat__doc__},
+#endif
+#ifdef HAVE_MKFIFOAT
+    {"mkfifoat",        posix_mkfifoat, METH_VARARGS, posix_mkfifoat__doc__},
+#endif
     {NULL,              NULL}            /* Sentinel */
 };
 
@@ -8066,6 +9063,35 @@
 }
 #endif
 
+#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
+static int
+enable_symlink()
+{
+    HANDLE tok;
+    TOKEN_PRIVILEGES tok_priv;
+    LUID luid;
+    int meth_idx = 0;
+
+    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &tok))
+        return 0;
+
+    if (!LookupPrivilegeValue(NULL, SE_CREATE_SYMBOLIC_LINK_NAME, &luid))
+        return 0;
+
+    tok_priv.PrivilegeCount = 1;
+    tok_priv.Privileges[0].Luid = luid;
+    tok_priv.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
+
+    if (!AdjustTokenPrivileges(tok, FALSE, &tok_priv,
+                               sizeof(TOKEN_PRIVILEGES),
+                               (PTOKEN_PRIVILEGES) NULL, (PDWORD) NULL))
+        return 0;
+
+    /* ERROR_NOT_ALL_ASSIGNED returned when the privilege can't be assigned. */
+    return GetLastError() == ERROR_NOT_ALL_ASSIGNED ? 0 : 1;
+}
+#endif /* defined(HAVE_SYMLINK) && defined(MS_WINDOWS) */
+
 static int
 all_ins(PyObject *d)
 {
@@ -8150,6 +9176,38 @@
 #ifdef O_EXLOCK
     if (ins(d, "O_EXLOCK", (long)O_EXLOCK)) return -1;
 #endif
+#ifdef PRIO_PROCESS
+    if (ins(d, "PRIO_PROCESS", (long)PRIO_PROCESS)) return -1;
+#endif
+#ifdef PRIO_PGRP
+    if (ins(d, "PRIO_PGRP", (long)PRIO_PGRP)) return -1;
+#endif
+#ifdef PRIO_USER
+    if (ins(d, "PRIO_USER", (long)PRIO_USER)) return -1;
+#endif
+/* posix - constants for *at functions */
+#ifdef AT_SYMLINK_NOFOLLOW
+        if (ins(d, "AT_SYMLINK_NOFOLLOW", (long)AT_SYMLINK_NOFOLLOW)) return -1;
+#endif
+#ifdef AT_EACCESS
+        if (ins(d, "AT_EACCESS", (long)AT_EACCESS)) return -1;
+#endif
+#ifdef AT_FDCWD
+        if (ins(d, "AT_FDCWD", (long)AT_FDCWD)) return -1;
+#endif
+#ifdef AT_REMOVEDIR
+        if (ins(d, "AT_REMOVEDIR", (long)AT_REMOVEDIR)) return -1;
+#endif
+#ifdef AT_SYMLINK_FOLLOW
+        if (ins(d, "AT_SYMLINK_FOLLOW", (long)AT_SYMLINK_FOLLOW)) return -1;
+#endif
+#ifdef UTIME_NOW
+        if (ins(d, "UTIME_NOW", (long)UTIME_NOW)) return -1;
+#endif
+#ifdef UTIME_OMIT
+        if (ins(d, "UTIME_OMIT", (long)UTIME_OMIT)) return -1;
+#endif
+
 
 /* MS Windows */
 #ifdef O_NOINHERIT
@@ -8258,6 +9316,17 @@
     if (ins(d, "ST_NOSUID", (long)ST_NOSUID)) return -1;
 #endif /* ST_NOSUID */
 
+    /* FreeBSD sendfile() constants */
+#ifdef SF_NODISKIO
+    if (ins(d, "SF_NODISKIO", (long)SF_NODISKIO)) return -1;
+#endif
+#ifdef SF_MNOWAIT
+    if (ins(d, "SF_MNOWAIT", (long)SF_MNOWAIT)) return -1;
+#endif
+#ifdef SF_SYNC
+    if (ins(d, "SF_SYNC", (long)SF_SYNC)) return -1;
+#endif
+
 #ifdef HAVE_SPAWNV
 #if defined(PYOS_OS2) && defined(PYCC_GCC)
     if (ins(d, "P_WAIT", (long)P_WAIT)) return -1;
@@ -8327,6 +9396,10 @@
 {
     PyObject *m, *v;
 
+#if defined(HAVE_SYMLINK) && defined(MS_WINDOWS)
+    win32_can_symlink = enable_symlink();
+#endif
+
     m = PyModule_Create(&posixmodule);
     if (m == NULL)
         return NULL;

Modified: python/branches/pep-3151/Modules/pwdmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/pwdmodule.c	(original)
+++ python/branches/pep-3151/Modules/pwdmodule.c	Sat Feb 26 08:16:32 2011
@@ -2,7 +2,6 @@
 /* UNIX password file access module */
 
 #include "Python.h"
-#include "structseq.h"
 
 #include <sys/types.h>
 #include <pwd.h>

Modified: python/branches/pep-3151/Modules/pyexpat.c
==============================================================================
--- python/branches/pep-3151/Modules/pyexpat.c	(original)
+++ python/branches/pep-3151/Modules/pyexpat.c	Sat Feb 26 08:16:32 2011
@@ -797,25 +797,13 @@
 static int
 readinst(char *buf, int buf_size, PyObject *meth)
 {
-    PyObject *arg = NULL;
-    PyObject *bytes = NULL;
-    PyObject *str = NULL;
-    int len = -1;
+    PyObject *str;
+    Py_ssize_t len;
     char *ptr;
 
-    if ((bytes = PyLong_FromLong(buf_size)) == NULL)
-        goto finally;
-
-    if ((arg = PyTuple_New(1)) == NULL) {
-        Py_DECREF(bytes);
-        goto finally;
-    }
-
-    PyTuple_SET_ITEM(arg, 0, bytes);
-
-    str = PyObject_Call(meth, arg, NULL);
+    str = PyObject_CallFunction(meth, "n", buf_size);
     if (str == NULL)
-        goto finally;
+        goto error;
 
     if (PyBytes_Check(str))
         ptr = PyBytes_AS_STRING(str);
@@ -825,21 +813,24 @@
         PyErr_Format(PyExc_TypeError,
                      "read() did not return a bytes object (type=%.400s)",
                      Py_TYPE(str)->tp_name);
-        goto finally;
+        goto error;
     }
     len = Py_SIZE(str);
     if (len > buf_size) {
         PyErr_Format(PyExc_ValueError,
                      "read() returned too much data: "
-                     "%i bytes requested, %i returned",
+                     "%i bytes requested, %zd returned",
                      buf_size, len);
-        goto finally;
+        goto error;
     }
     memcpy(buf, ptr, len);
-finally:
-    Py_XDECREF(arg);
+    Py_DECREF(str);
+    /* len <= buf_size <= INT_MAX */
+    return (int)len;
+
+error:
     Py_XDECREF(str);
-    return len;
+    return -1;
 }
 
 PyDoc_STRVAR(xmlparse_ParseFile__doc__,
@@ -1215,11 +1206,12 @@
 }
 
 static int
-handlername2int(const char *name)
+handlername2int(PyObject *name)
 {
     int i;
     for (i = 0; handler_info[i].name != NULL; i++) {
-        if (strcmp(name, handler_info[i].name) == 0) {
+        if (PyUnicode_CompareWithASCIIString(
+                name, handler_info[i].name) == 0) {
             return i;
         }
     }
@@ -1237,13 +1229,13 @@
 static PyObject *
 xmlparse_getattro(xmlparseobject *self, PyObject *nameobj)
 {
-    char *name = "";
+    Py_UNICODE *name;
     int handlernum = -1;
 
-    if (PyUnicode_Check(nameobj))
-        name = _PyUnicode_AsString(nameobj);
+    if (!PyUnicode_Check(nameobj))
+        goto generic;
 
-    handlernum = handlername2int(name);
+    handlernum = handlername2int(nameobj);
 
     if (handlernum != -1) {
         PyObject *result = self->handlers[handlernum];
@@ -1252,46 +1244,48 @@
         Py_INCREF(result);
         return result;
     }
+
+    name = PyUnicode_AS_UNICODE(nameobj);
     if (name[0] == 'E') {
-        if (strcmp(name, "ErrorCode") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorCode") == 0)
             return PyLong_FromLong((long)
                                   XML_GetErrorCode(self->itself));
-        if (strcmp(name, "ErrorLineNumber") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorLineNumber") == 0)
             return PyLong_FromLong((long)
                                   XML_GetErrorLineNumber(self->itself));
-        if (strcmp(name, "ErrorColumnNumber") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorColumnNumber") == 0)
             return PyLong_FromLong((long)
                                   XML_GetErrorColumnNumber(self->itself));
-        if (strcmp(name, "ErrorByteIndex") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "ErrorByteIndex") == 0)
             return PyLong_FromLong((long)
                                   XML_GetErrorByteIndex(self->itself));
     }
     if (name[0] == 'C') {
-        if (strcmp(name, "CurrentLineNumber") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentLineNumber") == 0)
             return PyLong_FromLong((long)
                                   XML_GetCurrentLineNumber(self->itself));
-        if (strcmp(name, "CurrentColumnNumber") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentColumnNumber") == 0)
             return PyLong_FromLong((long)
                                   XML_GetCurrentColumnNumber(self->itself));
-        if (strcmp(name, "CurrentByteIndex") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "CurrentByteIndex") == 0)
             return PyLong_FromLong((long)
                                   XML_GetCurrentByteIndex(self->itself));
     }
     if (name[0] == 'b') {
-        if (strcmp(name, "buffer_size") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_size") == 0)
             return PyLong_FromLong((long) self->buffer_size);
-        if (strcmp(name, "buffer_text") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_text") == 0)
             return get_pybool(self->buffer != NULL);
-        if (strcmp(name, "buffer_used") == 0)
+        if (PyUnicode_CompareWithASCIIString(nameobj, "buffer_used") == 0)
             return PyLong_FromLong((long) self->buffer_used);
     }
-    if (strcmp(name, "namespace_prefixes") == 0)
+    if (PyUnicode_CompareWithASCIIString(nameobj, "namespace_prefixes") == 0)
         return get_pybool(self->ns_prefixes);
-    if (strcmp(name, "ordered_attributes") == 0)
+    if (PyUnicode_CompareWithASCIIString(nameobj, "ordered_attributes") == 0)
         return get_pybool(self->ordered_attributes);
-    if (strcmp(name, "specified_attributes") == 0)
+    if (PyUnicode_CompareWithASCIIString(nameobj, "specified_attributes") == 0)
         return get_pybool((long) self->specified_attributes);
-    if (strcmp(name, "intern") == 0) {
+    if (PyUnicode_CompareWithASCIIString(nameobj, "intern") == 0) {
         if (self->intern == NULL) {
             Py_INCREF(Py_None);
             return Py_None;
@@ -1301,7 +1295,7 @@
             return self->intern;
         }
     }
-
+  generic:
     return PyObject_GenericGetAttr((PyObject*)self, nameobj);
 }
 
@@ -1352,7 +1346,7 @@
 }
 
 static int
-sethandler(xmlparseobject *self, const char *name, PyObject* v)
+sethandler(xmlparseobject *self, PyObject *name, PyObject* v)
 {
     int handlernum = handlername2int(name);
     if (handlernum >= 0) {
@@ -1388,14 +1382,15 @@
 }
 
 static int
-xmlparse_setattr(xmlparseobject *self, char *name, PyObject *v)
+xmlparse_setattro(xmlparseobject *self, PyObject *name, PyObject *v)
 {
     /* Set attribute 'name' to value 'v'. v==NULL means delete */
     if (v == NULL) {
         PyErr_SetString(PyExc_RuntimeError, "Cannot delete attribute");
         return -1;
     }
-    if (strcmp(name, "buffer_text") == 0) {
+    assert(PyUnicode_Check(name));
+    if (PyUnicode_CompareWithASCIIString(name, "buffer_text") == 0) {
         if (PyObject_IsTrue(v)) {
             if (self->buffer == NULL) {
                 self->buffer = malloc(self->buffer_size);
@@ -1414,7 +1409,7 @@
         }
         return 0;
     }
-    if (strcmp(name, "namespace_prefixes") == 0) {
+    if (PyUnicode_CompareWithASCIIString(name, "namespace_prefixes") == 0) {
         if (PyObject_IsTrue(v))
             self->ns_prefixes = 1;
         else
@@ -1422,14 +1417,14 @@
         XML_SetReturnNSTriplet(self->itself, self->ns_prefixes);
         return 0;
     }
-    if (strcmp(name, "ordered_attributes") == 0) {
+    if (PyUnicode_CompareWithASCIIString(name, "ordered_attributes") == 0) {
         if (PyObject_IsTrue(v))
             self->ordered_attributes = 1;
         else
             self->ordered_attributes = 0;
         return 0;
     }
-    if (strcmp(name, "specified_attributes") == 0) {
+    if (PyUnicode_CompareWithASCIIString(name, "specified_attributes") == 0) {
         if (PyObject_IsTrue(v))
             self->specified_attributes = 1;
         else
@@ -1437,7 +1432,7 @@
         return 0;
     }
 
-    if (strcmp(name, "buffer_size") == 0) {
+    if (PyUnicode_CompareWithASCIIString(name, "buffer_size") == 0) {
       long new_buffer_size;
       if (!PyLong_Check(v)) {
         PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
@@ -1480,7 +1475,7 @@
       return 0;
     }
 
-    if (strcmp(name, "CharacterDataHandler") == 0) {
+    if (PyUnicode_CompareWithASCIIString(name, "CharacterDataHandler") == 0) {
         /* If we're changing the character data handler, flush all
          * cached data with the old handler.  Not sure there's a
          * "right" thing to do, though, but this probably won't
@@ -1492,7 +1487,7 @@
     if (sethandler(self, name, v)) {
         return 0;
     }
-    PyErr_SetString(PyExc_AttributeError, name);
+    PyErr_SetObject(PyExc_AttributeError, name);
     return -1;
 }
 
@@ -1518,13 +1513,13 @@
 static PyTypeObject Xmlparsetype = {
         PyVarObject_HEAD_INIT(NULL, 0)
         "pyexpat.xmlparser",            /*tp_name*/
-        sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/
+        sizeof(xmlparseobject),         /*tp_basicsize*/
         0,                              /*tp_itemsize*/
         /* methods */
         (destructor)xmlparse_dealloc,   /*tp_dealloc*/
         (printfunc)0,           /*tp_print*/
         0,                      /*tp_getattr*/
-        (setattrfunc)xmlparse_setattr,  /*tp_setattr*/
+        0,  /*tp_setattr*/
         0,                      /*tp_reserved*/
         (reprfunc)0,            /*tp_repr*/
         0,                      /*tp_as_number*/
@@ -1534,7 +1529,7 @@
         (ternaryfunc)0,         /*tp_call*/
         (reprfunc)0,            /*tp_str*/
         (getattrofunc)xmlparse_getattro, /* tp_getattro */
-        0,              /* tp_setattro */
+        (setattrofunc)xmlparse_setattro,              /* tp_setattro */
         0,              /* tp_as_buffer */
         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
         Xmlparsetype__doc__, /* tp_doc - Documentation string */
@@ -1803,7 +1798,7 @@
         Py_XDECREF(rev_codes_dict);
         return NULL;
     }
-    
+
 #define MYCONST(name) \
     if (PyModule_AddStringConstant(errors_module, #name,               \
                                    (char *)XML_ErrorString(name)) < 0) \
@@ -1869,7 +1864,7 @@
         return NULL;
     if (PyModule_AddObject(errors_module, "messages", rev_codes_dict) < 0)
         return NULL;
-    
+
 #undef MYCONST
 
 #define MYCONST(c) PyModule_AddIntConstant(m, #c, c)

Modified: python/branches/pep-3151/Modules/readline.c
==============================================================================
--- python/branches/pep-3151/Modules/readline.c	(original)
+++ python/branches/pep-3151/Modules/readline.c	Sat Feb 26 08:16:32 2011
@@ -889,6 +889,14 @@
         Py_FatalError("not enough memory to save locale");
 #endif
 
+#ifdef __APPLE__
+    /* the libedit readline emulation resets key bindings etc 
+     * when calling rl_initialize.  So call it upfront
+     */
+    if (using_libedit_emulation)
+        rl_initialize();
+#endif /* __APPLE__ */
+
     using_history();
 
     rl_readline_name = "python";
@@ -920,8 +928,13 @@
      * XXX: A bug in the readline-2.2 library causes a memory leak
      * inside this function.  Nothing we can do about it.
      */
-    rl_initialize();
-
+#ifdef __APPLE__
+    if (using_libedit_emulation)
+	rl_read_init_file(NULL);
+    else
+#endif /* __APPLE__ */
+        rl_initialize();
+    
     RESTORE_LOCALE(saved_locale)
 }
 

Modified: python/branches/pep-3151/Modules/resource.c
==============================================================================
--- python/branches/pep-3151/Modules/resource.c	(original)
+++ python/branches/pep-3151/Modules/resource.c	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,5 @@
 
 #include "Python.h"
-#include "structseq.h"
 #include <sys/resource.h>
 #include <sys/time.h>
 #include <string.h>
@@ -325,6 +324,10 @@
     PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH);
 #endif
 
+#ifdef RUSAGE_THREAD
+    PyModule_AddIntConstant(m, "RUSAGE_THREAD", RUSAGE_THREAD);
+#endif
+
 #if defined(HAVE_LONG_LONG)
     if (sizeof(RLIM_INFINITY) > sizeof(long)) {
         v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);

Modified: python/branches/pep-3151/Modules/selectmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/selectmodule.c	(original)
+++ python/branches/pep-3151/Modules/selectmodule.c	Sat Feb 26 08:16:32 2011
@@ -79,10 +79,9 @@
 static int
 seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
 {
-    int i;
     int max = -1;
     int index = 0;
-    int len = -1;
+    Py_ssize_t i, len = -1;
     PyObject* fast_seq = NULL;
     PyObject* o = NULL;
 

Modified: python/branches/pep-3151/Modules/sha1module.c
==============================================================================
--- python/branches/pep-3151/Modules/sha1module.c	(original)
+++ python/branches/pep-3151/Modules/sha1module.c	Sat Feb 26 08:16:32 2011
@@ -203,9 +203,9 @@
    @param inlen  The length of the data (octets)
 */
 void sha1_process(struct sha1_state *sha1,
-                  const unsigned char *in, unsigned long inlen)
+                  const unsigned char *in, Py_ssize_t inlen)
 {
-    unsigned long n;
+    Py_ssize_t n;
 
     assert(sha1 != NULL);
     assert(in != NULL);

Modified: python/branches/pep-3151/Modules/sha256module.c
==============================================================================
--- python/branches/pep-3151/Modules/sha256module.c	(original)
+++ python/branches/pep-3151/Modules/sha256module.c	Sat Feb 26 08:16:32 2011
@@ -265,9 +265,9 @@
 /* update the SHA digest */
 
 static void
-sha_update(SHAobject *sha_info, SHA_BYTE *buffer, int count)
+sha_update(SHAobject *sha_info, SHA_BYTE *buffer, Py_ssize_t count)
 {
-    int i;
+    Py_ssize_t i;
     SHA_INT32 clo;
 
     clo = sha_info->count_lo + ((SHA_INT32) count << 3);

Modified: python/branches/pep-3151/Modules/sha512module.c
==============================================================================
--- python/branches/pep-3151/Modules/sha512module.c	(original)
+++ python/branches/pep-3151/Modules/sha512module.c	Sat Feb 26 08:16:32 2011
@@ -291,9 +291,9 @@
 /* update the SHA digest */
 
 static void
-sha512_update(SHAobject *sha_info, SHA_BYTE *buffer, int count)
+sha512_update(SHAobject *sha_info, SHA_BYTE *buffer, Py_ssize_t count)
 {
-    int i;
+    Py_ssize_t i;
     SHA_INT32 clo;
 
     clo = sha_info->count_lo + ((SHA_INT32) count << 3);

Modified: python/branches/pep-3151/Modules/signalmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/signalmodule.c	(original)
+++ python/branches/pep-3151/Modules/signalmodule.c	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,6 @@
 /* XXX Signals should be recorded per thread, now we have thread state. */
 
 #include "Python.h"
-#include "intrcheck.h"
 
 #ifdef MS_WINDOWS
 #include <Windows.h>

Modified: python/branches/pep-3151/Modules/socketmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/socketmodule.c	(original)
+++ python/branches/pep-3151/Modules/socketmodule.c	Sat Feb 26 08:16:32 2011
@@ -1405,9 +1405,9 @@
         {
             struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
 #if defined(__NetBSD__) || defined(__DragonFly__)
-			char *straddr = PyBytes_AS_STRING(args);
+                        char *straddr = PyBytes_AS_STRING(args);
 
-			_BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
+                        _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
             if (straddr == NULL) {
                 PyErr_SetString(PyExc_IOError, "getsockaddrarg: "
                     "wrong format");
@@ -3406,7 +3406,7 @@
         goto finally;
     af = sa->sa_family;
     ap = NULL;
-    al = 0;
+    /* al = 0; */
     switch (af) {
     case AF_INET:
         ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
@@ -4021,8 +4021,10 @@
         pptr = pbuf;
     } else if (PyUnicode_Check(pobj)) {
         pptr = _PyUnicode_AsString(pobj);
+        if (pptr == NULL)
+            goto err;
     } else if (PyBytes_Check(pobj)) {
-        pptr = PyBytes_AsString(pobj);
+        pptr = PyBytes_AS_STRING(pobj);
     } else if (pobj == Py_None) {
         pptr = (char *)NULL;
     } else {
@@ -4357,6 +4359,7 @@
 PySocketModule_APIObject PySocketModuleAPI =
 {
     &sock_type,
+    NULL,
     NULL
 };
 
@@ -4421,6 +4424,7 @@
                                         PyExc_IOError, NULL);
     if (socket_timeout == NULL)
         return NULL;
+    PySocketModuleAPI.timeout_error = socket_timeout;
     Py_INCREF(socket_timeout);
     PyModule_AddObject(m, "timeout", socket_timeout);
     Py_INCREF((PyObject *)&sock_type);

Modified: python/branches/pep-3151/Modules/socketmodule.h
==============================================================================
--- python/branches/pep-3151/Modules/socketmodule.h	(original)
+++ python/branches/pep-3151/Modules/socketmodule.h	Sat Feb 26 08:16:32 2011
@@ -196,6 +196,7 @@
 typedef struct {
     PyTypeObject *Sock_Type;
     PyObject *error;
+    PyObject *timeout_error;
 } PySocketModule_APIObject;
 
 #define PySocketModule_ImportModuleAndAPI() PyCapsule_Import(PySocket_CAPSULE_NAME, 1)

Modified: python/branches/pep-3151/Modules/spwdmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/spwdmodule.c	(original)
+++ python/branches/pep-3151/Modules/spwdmodule.c	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,6 @@
 /* For info also see http://www.unixpapa.com/incnote/passwd.html */
 
 #include "Python.h"
-#include "structseq.h"
 
 #include <sys/types.h>
 #ifdef HAVE_SHADOW_H

Modified: python/branches/pep-3151/Modules/symtablemodule.c
==============================================================================
--- python/branches/pep-3151/Modules/symtablemodule.c	(original)
+++ python/branches/pep-3151/Modules/symtablemodule.c	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,6 @@
 #include "Python.h"
 
 #include "code.h"
-#include "compile.h"
 #include "Python-ast.h"
 #include "symtable.h"
 

Modified: python/branches/pep-3151/Modules/syslogmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/syslogmodule.c	(original)
+++ python/branches/pep-3151/Modules/syslogmodule.c	Sat Feb 26 08:16:32 2011
@@ -68,9 +68,9 @@
      * is optional.
      */
 
-    Py_ssize_t argv_len;
+    Py_ssize_t argv_len, scriptlen;
     PyObject *scriptobj;
-    char *atslash;
+    Py_UNICODE *atslash, *atstart;
     PyObject *argv = PySys_GetObject("argv");
 
     if (argv == NULL) {
@@ -90,13 +90,16 @@
     if (!PyUnicode_Check(scriptobj)) {
         return(NULL);
     }
-    if (PyUnicode_GET_SIZE(scriptobj) == 0) {
+    scriptlen = PyUnicode_GET_SIZE(scriptobj);
+    if (scriptlen == 0) {
         return(NULL);
     }
 
-    atslash = strrchr(_PyUnicode_AsString(scriptobj), SEP);
+    atstart = PyUnicode_AS_UNICODE(scriptobj);
+    atslash = Py_UNICODE_strrchr(atstart, SEP);
     if (atslash) {
-        return(PyUnicode_FromString(atslash + 1));
+        return(PyUnicode_FromUnicode(atslash + 1,
+                                     scriptlen - (atslash - atstart) - 1));
     } else {
         Py_INCREF(scriptobj);
         return(scriptobj);
@@ -113,6 +116,7 @@
     long facility = LOG_USER;
     PyObject *new_S_ident_o = NULL;
     static char *keywords[] = {"ident", "logoption", "facility", 0};
+    char *ident = NULL;
 
     if (!PyArg_ParseTupleAndKeywords(args, kwds,
                           "|Ull:openlog", keywords, &new_S_ident_o, &logopt, &facility))
@@ -120,12 +124,12 @@
 
     if (new_S_ident_o) {
         Py_INCREF(new_S_ident_o);
-        }
+    }
 
     /*  get sys.argv[0] or NULL if we can't for some reason  */
     if (!new_S_ident_o) {
         new_S_ident_o = syslog_get_argv();
-        }
+    }
 
     Py_XDECREF(S_ident_o);
     S_ident_o = new_S_ident_o;
@@ -134,8 +138,13 @@
      * make a copy, and syslog(3) later uses it.  We can't garbagecollect it
      * If NULL, just let openlog figure it out (probably using C argv[0]).
      */
+    if (S_ident_o) {
+        ident = _PyUnicode_AsString(S_ident_o);
+        if (ident == NULL)
+            return NULL;
+    }
 
-    openlog(S_ident_o ? _PyUnicode_AsString(S_ident_o) : NULL, logopt, facility);
+    openlog(ident, logopt, facility);
     S_log_open = 1;
 
     Py_INCREF(Py_None);

Modified: python/branches/pep-3151/Modules/termios.c
==============================================================================
--- python/branches/pep-3151/Modules/termios.c	(original)
+++ python/branches/pep-3151/Modules/termios.c	Sat Feb 26 08:16:32 2011
@@ -347,6 +347,43 @@
 #ifdef B230400
     {"B230400", B230400},
 #endif
+#ifdef B460800
+    {"B460800", B460800},
+#endif
+#ifdef B500000
+    {"B500000", B500000},
+#endif
+#ifdef B576000
+    {"B576000", B576000},
+#endif
+#ifdef B921600
+    {"B921600", B921600},
+#endif
+#ifdef B1000000
+    {"B1000000", B1000000},
+#endif
+#ifdef B1152000
+    {"B1152000", B1152000},
+#endif
+#ifdef B1500000
+    {"B1500000", B1500000},
+#endif
+#ifdef B2000000
+    {"B2000000", B2000000},
+#endif
+#ifdef B2500000
+    {"B2500000", B2500000},
+#endif
+#ifdef B3000000
+    {"B3000000", B3000000},
+#endif
+#ifdef B3500000
+    {"B3500000", B3500000},
+#endif
+#ifdef B4000000
+    {"B4000000", B4000000},
+#endif
+
 #ifdef CBAUDEX
     {"CBAUDEX", CBAUDEX},
 #endif

Modified: python/branches/pep-3151/Modules/timemodule.c
==============================================================================
--- python/branches/pep-3151/Modules/timemodule.c	(original)
+++ python/branches/pep-3151/Modules/timemodule.c	Sat Feb 26 08:16:32 2011
@@ -1,8 +1,6 @@
-
 /* Time module */
 
 #include "Python.h"
-#include "structseq.h"
 #include "_time.h"
 
 #define TZNAME_ENCODING "utf-8"
@@ -219,29 +217,6 @@
 }
 
 static PyObject *
-structtime_totuple(PyObject *t)
-{
-    PyObject *x = NULL;
-    unsigned int i;
-    PyObject *v = PyTuple_New(9);
-    if (v == NULL)
-        return NULL;
-
-    for (i=0; i<9; i++) {
-        x = PyStructSequence_GET_ITEM(t, i);
-        Py_INCREF(x);
-        PyTuple_SET_ITEM(v, i, x);
-    }
-
-    if (PyErr_Occurred()) {
-        Py_XDECREF(v);
-        return NULL;
-    }
-
-    return v;
-}
-
-static PyObject *
 time_convert(double when, struct tm * (*function)(const time_t *))
 {
     struct tm *p;
@@ -322,56 +297,62 @@
 gettmarg(PyObject *args, struct tm *p)
 {
     int y;
-    PyObject *t = NULL;
 
     memset((void *) p, '\0', sizeof(struct tm));
 
-    if (PyTuple_Check(args)) {
-        t = args;
-        Py_INCREF(t);
-    }
-    else if (Py_TYPE(args) == &StructTimeType) {
-        t = structtime_totuple(args);
-    }
-    else {
+    if (!PyTuple_Check(args)) {
         PyErr_SetString(PyExc_TypeError,
                         "Tuple or struct_time argument required");
         return 0;
     }
 
-    if (t == NULL || !PyArg_ParseTuple(t, "iiiiiiiii",
-                                       &y,
-                                       &p->tm_mon,
-                                       &p->tm_mday,
-                                       &p->tm_hour,
-                                       &p->tm_min,
-                                       &p->tm_sec,
-                                       &p->tm_wday,
-                                       &p->tm_yday,
-                                       &p->tm_isdst)) {
-        Py_XDECREF(t);
+    if (!PyArg_ParseTuple(args, "iiiiiiiii",
+                          &y, &p->tm_mon, &p->tm_mday,
+                          &p->tm_hour, &p->tm_min, &p->tm_sec,
+                          &p->tm_wday, &p->tm_yday, &p->tm_isdst))
         return 0;
-    }
-    Py_DECREF(t);
 
-    if (y < 1900) {
+    /* If year is specified with less than 4 digits, its interpretation
+     * depends on the accept2dyear value.
+     *
+     * If accept2dyear is true (default), a backward compatibility behavior is
+     * invoked as follows:
+     *
+     *   - for 2-digit year, century is guessed according to POSIX rules for
+     *      %y strptime format: 21st century for y < 69, 20th century
+     *      otherwise.  A deprecation warning is issued when century
+     *      information is guessed in this way.
+     *
+     *   - for 3-digit or negative year, a ValueError exception is raised.
+     *
+     * If accept2dyear is false (set by the program or as a result of a
+     * non-empty value assigned to PYTHONY2K environment variable) all year
+     * values are interpreted as given.
+     */
+    if (y < 1000) {
         PyObject *accept = PyDict_GetItemString(moddict,
                                                 "accept2dyear");
-        if (accept == NULL || !PyLong_CheckExact(accept) ||
-            !PyObject_IsTrue(accept)) {
-            PyErr_SetString(PyExc_ValueError,
-                            "year >= 1900 required");
-            return 0;
+        if (accept != NULL) {
+            int acceptval =  PyObject_IsTrue(accept);
+            if (acceptval == -1)
+                return 0;
+            if (acceptval) {
+                if (0 <= y && y < 69)
+                    y += 2000;
+                else if (69 <= y && y < 100)
+                    y += 1900;
+                else {
+                    PyErr_SetString(PyExc_ValueError,
+                                    "year out of range");
+                    return 0;
+                }
+                if (PyErr_WarnEx(PyExc_DeprecationWarning,
+                           "Century info guessed for a 2-digit year.", 1) != 0)
+                    return 0;
+            }
         }
-        if (69 <= y && y <= 99)
-            y += 1900;
-        else if (0 <= y && y <= 68)
-            y += 2000;
-        else {
-            PyErr_SetString(PyExc_ValueError,
-                            "year out of range");
+        else
             return 0;
-        }
     }
     p->tm_year = y - 1900;
     p->tm_mon--;
@@ -493,6 +474,15 @@
     else if (!gettmarg(tup, &buf) || !checktm(&buf))
         return NULL;
 
+#if defined(_MSC_VER) || defined(sun)
+    if (buf.tm_year + 1900 < 1 || 9999 < buf.tm_year + 1900) {
+        PyErr_Format(PyExc_ValueError,
+                     "strftime() requires year in [1; 9999]",
+                     buf.tm_year + 1900);
+        return NULL;
+    }
+#endif
+
     /* Normalize tm_isdst just in case someone foolishly implements %Z
        based on the assumption that tm_isdst falls within the range of
        [-1, 1] */
@@ -600,19 +590,51 @@
     return strptime_result;
 }
 
+
 PyDoc_STRVAR(strptime_doc,
 "strptime(string, format) -> struct_time\n\
 \n\
 Parse a string to a time tuple according to a format specification.\n\
 See the library reference manual for formatting codes (same as strftime()).");
 
+static PyObject *
+_asctime(struct tm *timeptr)
+{
+    /* Inspired by Open Group reference implementation available at
+     * http://pubs.opengroup.org/onlinepubs/009695399/functions/asctime.html */
+    static char wday_name[7][3] = {
+        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
+    };
+    static char mon_name[12][3] = {
+        "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+    };
+    char buf[20]; /* 'Sun Sep 16 01:03:52\0' */
+    int n;
+
+    n = PyOS_snprintf(buf, sizeof(buf), "%.3s %.3s%3d %.2d:%.2d:%.2d",
+                      wday_name[timeptr->tm_wday],
+                      mon_name[timeptr->tm_mon],
+                      timeptr->tm_mday, timeptr->tm_hour,
+                      timeptr->tm_min, timeptr->tm_sec);
+    /* XXX: since the fields used by snprintf above are validated in checktm,
+     * the following condition should never trigger. We keep the check because
+     * historically fixed size buffer used in asctime was the source of
+     * crashes. */
+    if (n + 1 != sizeof(buf)) {
+        PyErr_SetString(PyExc_ValueError, "unconvertible time");
+        return NULL;
+    }
+
+    return PyUnicode_FromFormat("%s %d", buf, 1900 + timeptr->tm_year);
+}
 
 static PyObject *
 time_asctime(PyObject *self, PyObject *args)
 {
     PyObject *tup = NULL;
     struct tm buf;
-    char *p;
+
     if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
         return NULL;
     if (tup == NULL) {
@@ -620,10 +642,7 @@
         buf = *localtime(&tt);
     } else if (!gettmarg(tup, &buf) || !checktm(&buf))
         return NULL;
-    p = asctime(&buf);
-    if (p[24] == '\n')
-        p[24] = '\0';
-    return PyUnicode_FromString(p);
+    return _asctime(&buf);
 }
 
 PyDoc_STRVAR(asctime_doc,
@@ -638,7 +657,7 @@
 {
     PyObject *ot = NULL;
     time_t tt;
-    char *p;
+    struct tm *timeptr;
 
     if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
         return NULL;
@@ -652,14 +671,12 @@
         if (tt == (time_t)-1 && PyErr_Occurred())
             return NULL;
     }
-    p = ctime(&tt);
-    if (p == NULL) {
+    timeptr = localtime(&tt);
+    if (timeptr == NULL) {
         PyErr_SetString(PyExc_ValueError, "unconvertible time");
         return NULL;
     }
-    if (p[24] == '\n')
-        p[24] = '\0';
-    return PyUnicode_FromString(p);
+    return _asctime(timeptr);
 }
 
 PyDoc_STRVAR(ctime_doc,
@@ -677,8 +694,11 @@
     time_t tt;
     if (!gettmarg(tup, &buf))
         return NULL;
+    buf.tm_wday = -1;  /* sentinel; original value ignored */
     tt = mktime(&buf);
-    if (tt == (time_t)(-1)) {
+    /* Return value of -1 does not necessarily mean an error, but tm_wday
+     * cannot remain set to -1 if mktime succedded. */
+    if (tt == (time_t)(-1) && buf.tm_wday == -1) {
         PyErr_SetString(PyExc_OverflowError,
                         "mktime argument out of range");
         return NULL;
@@ -716,7 +736,7 @@
 }
 
 PyDoc_STRVAR(tzset_doc,
-"tzset(zone)\n\
+"tzset()\n\
 \n\
 Initialize, or reinitialize, the local timezone to the value stored in\n\
 os.environ['TZ']. The TZ environment variable should be specified in\n\

Modified: python/branches/pep-3151/Modules/unicodedata.c
==============================================================================
--- python/branches/pep-3151/Modules/unicodedata.c	(original)
+++ python/branches/pep-3151/Modules/unicodedata.c	Sat Feb 26 08:16:32 2011
@@ -403,7 +403,8 @@
 {
     PyUnicodeObject *v;
     char decomp[256];
-    int code, index, count, i;
+    int code, index, count;
+    size_t i;
     unsigned int prefix_index;
     Py_UCS4 c;
 
@@ -450,15 +451,12 @@
     while (count-- > 0) {
         if (i)
             decomp[i++] = ' ';
-        assert((size_t)i < sizeof(decomp));
+        assert(i < sizeof(decomp));
         PyOS_snprintf(decomp + i, sizeof(decomp) - i, "%04X",
                       decomp_data[++index]);
         i += strlen(decomp + i);
     }
-
-    decomp[i] = '\0';
-
-    return PyUnicode_FromString(decomp);
+    return PyUnicode_FromStringAndSize(decomp, i);
 }
 
 static void
@@ -684,10 +682,14 @@
       comb = 0;
       while (i1 < end) {
           int comb1 = _getrecord_ex(*i1)->combining;
-          if (comb && (comb1 == 0 || comb == comb1)) {
-              /* Character is blocked. */
-              i1++;
-              continue;
+          if (comb) {
+              if (comb1 == 0)
+                  break;
+              if (comb >= comb1) {
+                  /* Character is blocked. */
+                  i1++;
+                  continue;
+              }
           }
           l = find_nfc_index(self, nfc_last, *i1);
           /* *i1 cannot be combined with *i. If *i1
@@ -711,6 +713,7 @@
           /* Replace the original character. */
           *i = code;
           /* Mark the second character unused. */
+          assert(cskipped < 20);
           skipped[cskipped++] = i1;
           i1++;
           f = find_nfc_index(self, nfc_first, *i);
@@ -866,13 +869,16 @@
     { 0,    0,     "H"  }
 };
 
+/* These ranges need to match makeunicodedata.py:cjk_ranges. */
 static int
 is_unified_ideograph(Py_UCS4 code)
 {
-    return (
-        (0x3400 <= code && code <= 0x4DB5) || /* CJK Ideograph Extension A */
-        (0x4E00 <= code && code <= 0x9FBB) || /* CJK Ideograph */
-        (0x20000 <= code && code <= 0x2A6D6));/* CJK Ideograph Extension B */
+    return
+        (0x3400 <= code && code <= 0x4DB5)   || /* CJK Ideograph Extension A */
+        (0x4E00 <= code && code <= 0x9FCB)   || /* CJK Ideograph */
+        (0x20000 <= code && code <= 0x2A6D6) || /* CJK Ideograph Extension B */
+        (0x2A700 <= code && code <= 0x2B734) || /* CJK Ideograph Extension C */
+        (0x2B740 <= code && code <= 0x2B81D);   /* CJK Ideograph Extension D */
 }
 
 static int

Modified: python/branches/pep-3151/Modules/zipimport.c
==============================================================================
--- python/branches/pep-3151/Modules/zipimport.c	(original)
+++ python/branches/pep-3151/Modules/zipimport.c	Sat Feb 26 08:16:32 2011
@@ -725,6 +725,7 @@
     long arc_offset; /* offset from beginning of file to start of zip-archive */
     PyObject *pathobj;
     const char *charset;
+    int bootstrap;
 
     if (PyUnicode_GET_SIZE(archive_obj) > MAXPATHLEN) {
         PyErr_SetString(PyExc_OverflowError,
@@ -801,13 +802,30 @@
         *p = 0;         /* Add terminating null byte */
         header_offset += header_size;
 
+        bootstrap = 0;
         if (flags & 0x0800)
             charset = "utf-8";
+        else if (!PyThreadState_GET()->interp->codecs_initialized) {
+            /* During bootstrap, we may need to load the encodings
+               package from a ZIP file. But the cp437 encoding is implemented
+               in Python in the encodings package.
+
+               Break out of this dependency by assuming that the path to
+               the encodings module is ASCII-only. */
+            charset = "ascii";
+            bootstrap = 1;
+        }
         else
             charset = "cp437";
         nameobj = PyUnicode_Decode(name, name_size, charset, NULL);
-        if (nameobj == NULL)
+        if (nameobj == NULL) {
+            if (bootstrap)
+                PyErr_Format(PyExc_NotImplementedError,
+                    "bootstrap issue: python%i%i.zip contains non-ASCII "
+                    "filenames without the unicode flag",
+                    PY_MAJOR_VERSION, PY_MINOR_VERSION);
             goto error;
+        }
         Py_UNICODE_strncpy(path + length + 1, PyUnicode_AS_UNICODE(nameobj), MAXPATHLEN - length - 1);
 
         pathobj = PyUnicode_FromUnicode(path, Py_UNICODE_strlen(path));

Modified: python/branches/pep-3151/Modules/zlibmodule.c
==============================================================================
--- python/branches/pep-3151/Modules/zlibmodule.c	(original)
+++ python/branches/pep-3151/Modules/zlibmodule.c	Sat Feb 26 08:16:32 2011
@@ -117,14 +117,21 @@
     PyObject *ReturnVal = NULL;
     Py_buffer pinput;
     Byte *input, *output;
-    int length, level=Z_DEFAULT_COMPRESSION, err;
+    unsigned int length;
+    int level=Z_DEFAULT_COMPRESSION, err;
     z_stream zst;
 
     /* require Python string object, optional 'level' arg */
     if (!PyArg_ParseTuple(args, "y*|i:compress", &pinput, &level))
         return NULL;
-    input = pinput.buf;
+
+    if (pinput.len > UINT_MAX) {
+        PyErr_SetString(PyExc_OverflowError,
+            "size does not fit in an unsigned int");
+        return NULL;
+    }
     length = pinput.len;
+    input = pinput.buf;
 
     zst.avail_out = length + length/1000 + 12 + 1;
 
@@ -199,7 +206,8 @@
     PyObject *result_str;
     Py_buffer pinput;
     Byte *input;
-    int length, err;
+    unsigned int length;
+    int err;
     int wsize=DEF_WBITS;
     Py_ssize_t r_strlen=DEFAULTALLOC;
     z_stream zst;
@@ -207,8 +215,14 @@
     if (!PyArg_ParseTuple(args, "y*|in:decompress",
                           &pinput, &wsize, &r_strlen))
         return NULL;
-    input = pinput.buf;
+
+    if (pinput.len > UINT_MAX) {
+        PyErr_SetString(PyExc_OverflowError,
+            "size does not fit in an unsigned int");
+        return NULL;
+    }
     length = pinput.len;
+    input = pinput.buf;
 
     if (r_strlen <= 0)
         r_strlen = 1;
@@ -931,8 +945,18 @@
     /* Releasing the GIL for very small buffers is inefficient
        and may lower performance */
     if (pbuf.len > 1024*5) {
+        unsigned char *buf = pbuf.buf;
+        Py_ssize_t len = pbuf.len;
+
         Py_BEGIN_ALLOW_THREADS
-        adler32val = adler32(adler32val, pbuf.buf, pbuf.len);
+        /* Avoid truncation of length for very large buffers. adler32() takes
+           length as an unsigned int, which may be narrower than Py_ssize_t. */
+        while (len > (size_t) UINT_MAX) {
+            adler32val = adler32(adler32val, buf, UINT_MAX);
+            buf += (size_t) UINT_MAX;
+            len -= (size_t) UINT_MAX;
+        }
+        adler32val = adler32(adler32val, buf, len);
         Py_END_ALLOW_THREADS
     } else {
         adler32val = adler32(adler32val, pbuf.buf, pbuf.len);
@@ -959,8 +983,18 @@
     /* Releasing the GIL for very small buffers is inefficient
        and may lower performance */
     if (pbuf.len > 1024*5) {
+        unsigned char *buf = pbuf.buf;
+        Py_ssize_t len = pbuf.len;
+
         Py_BEGIN_ALLOW_THREADS
-        signed_val = crc32(crc32val, pbuf.buf, pbuf.len);
+        /* Avoid truncation of length for very large buffers. crc32() takes
+           length as an unsigned int, which may be narrower than Py_ssize_t. */
+        while (len > (size_t) UINT_MAX) {
+            crc32val = crc32(crc32val, buf, UINT_MAX);
+            buf += (size_t) UINT_MAX;
+            len -= (size_t) UINT_MAX;
+        }
+        signed_val = crc32(crc32val, buf, len);
         Py_END_ALLOW_THREADS
     } else {
         signed_val = crc32(crc32val, pbuf.buf, pbuf.len);

Modified: python/branches/pep-3151/Objects/abstract.c
==============================================================================
--- python/branches/pep-3151/Objects/abstract.c	(original)
+++ python/branches/pep-3151/Objects/abstract.c	Sat Feb 26 08:16:32 2011
@@ -2500,7 +2500,10 @@
         if (retval == 0) {
             PyObject *c = PyObject_GetAttr(inst, __class__);
             if (c == NULL) {
-                PyErr_Clear();
+                if (PyErr_ExceptionMatches(PyExc_AttributeError))
+                    PyErr_Clear();
+                else
+                    retval = -1;
             }
             else {
                 if (c != (PyObject *)(inst->ob_type) &&
@@ -2518,8 +2521,10 @@
             return -1;
         icls = PyObject_GetAttr(inst, __class__);
         if (icls == NULL) {
-            PyErr_Clear();
-            retval = 0;
+            if (PyErr_ExceptionMatches(PyExc_AttributeError))
+                PyErr_Clear();
+            else
+                retval = -1;
         }
         else {
             retval = abstract_issubclass(icls, cls);

Modified: python/branches/pep-3151/Objects/bytearrayobject.c
==============================================================================
--- python/branches/pep-3151/Objects/bytearrayobject.c	(original)
+++ python/branches/pep-3151/Objects/bytearrayobject.c	Sat Feb 26 08:16:32 2011
@@ -389,7 +389,7 @@
     }
     else if (PySlice_Check(index)) {
         Py_ssize_t start, stop, step, slicelength, cur, i;
-        if (PySlice_GetIndicesEx((PySliceObject *)index,
+        if (PySlice_GetIndicesEx(index,
                                  PyByteArray_GET_SIZE(self),
                                  &start, &stop, &step, &slicelength) < 0) {
             return NULL;
@@ -573,7 +573,7 @@
         }
     }
     else if (PySlice_Check(index)) {
-        if (PySlice_GetIndicesEx((PySliceObject *)index,
+        if (PySlice_GetIndicesEx(index,
                                  PyByteArray_GET_SIZE(self),
                                  &start, &stop, &step, &slicelen) < 0) {
             return -1;
@@ -589,7 +589,7 @@
         needed = 0;
     }
     else if (values == (PyObject *)self || !PyByteArray_Check(values)) {
-        /* Make a copy an call this function recursively */
+        /* Make a copy and call this function recursively */
         int err;
         values = PyByteArray_FromObject(values);
         if (values == NULL)
@@ -2439,7 +2439,7 @@
 static PyObject *
 bytearray_rstrip(PyByteArrayObject *self, PyObject *args)
 {
-    Py_ssize_t left, right, mysize, argsize;
+    Py_ssize_t right, mysize, argsize;
     void *myptr, *argptr;
     PyObject *arg = Py_None;
     Py_buffer varg;
@@ -2457,11 +2457,10 @@
     }
     myptr = self->ob_bytes;
     mysize = Py_SIZE(self);
-    left = 0;
     right = rstrip_helper(myptr, mysize, argptr, argsize);
     if (arg != Py_None)
         PyBuffer_Release(&varg);
-    return PyByteArray_FromStringAndSize(self->ob_bytes + left, right - left);
+    return PyByteArray_FromStringAndSize(self->ob_bytes, right);
 }
 
 PyDoc_STRVAR(decode_doc,

Modified: python/branches/pep-3151/Objects/bytesobject.c
==============================================================================
--- python/branches/pep-3151/Objects/bytesobject.c	(original)
+++ python/branches/pep-3151/Objects/bytesobject.c	Sat Feb 26 08:16:32 2011
@@ -911,7 +911,7 @@
         char* result_buf;
         PyObject* result;
 
-        if (PySlice_GetIndicesEx((PySliceObject*)item,
+        if (PySlice_GetIndicesEx(item,
                          PyBytes_GET_SIZE(self),
                          &start, &stop, &step, &slicelength) < 0) {
             return NULL;

Modified: python/branches/pep-3151/Objects/codeobject.c
==============================================================================
--- python/branches/pep-3151/Objects/codeobject.c	(original)
+++ python/branches/pep-3151/Objects/codeobject.c	Sat Feb 26 08:16:32 2011
@@ -347,11 +347,11 @@
         lineno = -1;
     if (co->co_filename && PyUnicode_Check(co->co_filename)) {
         return PyUnicode_FromFormat(
-            "<code object %.100U at %p, file \"%.300U\", line %d>",
+            "<code object %U at %p, file \"%U\", line %d>",
             co->co_name, co, co->co_filename, lineno);
     } else {
         return PyUnicode_FromFormat(
-            "<code object %.100U at %p, file ???, line %d>",
+            "<code object %U at %p, file ???, line %d>",
             co->co_name, co, lineno);
     }
 }
@@ -492,7 +492,7 @@
 int
 PyCode_Addr2Line(PyCodeObject *co, int addrq)
 {
-    int size = PyBytes_Size(co->co_lnotab) / 2;
+    Py_ssize_t size = PyBytes_Size(co->co_lnotab) / 2;
     unsigned char *p = (unsigned char*)PyBytes_AsString(co->co_lnotab);
     int line = co->co_firstlineno;
     int addr = 0;
@@ -510,7 +510,8 @@
 int
 _PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
 {
-    int size, addr, line;
+    Py_ssize_t size;
+    int addr, line;
     unsigned char* p;
 
     p = (unsigned char*)PyBytes_AS_STRING(co->co_lnotab);

Modified: python/branches/pep-3151/Objects/complexobject.c
==============================================================================
--- python/branches/pep-3151/Objects/complexobject.c	(original)
+++ python/branches/pep-3151/Objects/complexobject.c	Sat Feb 26 08:16:32 2011
@@ -324,10 +324,11 @@
     op->ob_type->tp_free(op);
 }
 
-
 static PyObject *
-complex_format(PyComplexObject *v, int precision, char format_code)
+complex_repr(PyComplexObject *v)
 {
+    int precision = 0;
+    char format_code = 'r';
     PyObject *result = NULL;
     Py_ssize_t len;
 
@@ -344,6 +345,8 @@
     char *tail = "";
 
     if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
+        /* Real part is +0: just output the imaginary part and do not
+           include parens. */
         re = "";
         im = PyOS_double_to_string(v->cval.imag, format_code,
                                    precision, 0, NULL);
@@ -352,7 +355,8 @@
             goto done;
         }
     } else {
-        /* Format imaginary part with sign, real part without */
+        /* Format imaginary part with sign, real part without. Include
+           parens in the result. */
         pre = PyOS_double_to_string(v->cval.real, format_code,
                                     precision, 0, NULL);
         if (!pre) {
@@ -371,7 +375,7 @@
         tail = ")";
     }
     /* Alloc the final buffer. Add one for the "j" in the format string,
-       and one for the trailing zero. */
+       and one for the trailing zero byte. */
     len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
     buf = PyMem_Malloc(len);
     if (!buf) {
@@ -388,12 +392,6 @@
     return result;
 }
 
-static PyObject *
-complex_repr(PyComplexObject *v)
-{
-    return complex_format(v, 0, 'r');
-}
-
 static Py_hash_t
 complex_hash(PyComplexObject *v)
 {
@@ -766,24 +764,30 @@
     char *end;
     double x=0.0, y=0.0, z;
     int got_bracket=0;
-    char *s_buffer = NULL;
+    PyObject *s_buffer = NULL;
     Py_ssize_t len;
 
     if (PyUnicode_Check(v)) {
-        s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v) + 1);
+        Py_ssize_t i, buflen = PyUnicode_GET_SIZE(v);
+        Py_UNICODE *bufptr;
+        s_buffer = PyUnicode_TransformDecimalToASCII(
+            PyUnicode_AS_UNICODE(v), buflen);
         if (s_buffer == NULL)
-            return PyErr_NoMemory();
-        if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
-                                    PyUnicode_GET_SIZE(v),
-                                    s_buffer,
-                                    NULL))
+            return NULL;
+        /* Replace non-ASCII whitespace with ' ' */
+        bufptr = PyUnicode_AS_UNICODE(s_buffer);
+        for (i = 0; i < buflen; i++) {
+            Py_UNICODE ch = bufptr[i];
+            if (ch > 127 && Py_UNICODE_ISSPACE(ch))
+                bufptr[i] = ' ';
+        }
+        s = _PyUnicode_AsStringAndSize(s_buffer, &len);
+        if (s == NULL)
             goto error;
-        s = s_buffer;
-        len = strlen(s);
     }
     else if (PyObject_AsCharBuffer(v, &s, &len)) {
         PyErr_SetString(PyExc_TypeError,
-                        "complex() arg is not a string");
+                        "complex() argument must be a string or a number");
         return NULL;
     }
 
@@ -894,16 +898,14 @@
     if (s-start != len)
         goto parse_error;
 
-    if (s_buffer)
-        PyMem_FREE(s_buffer);
+    Py_XDECREF(s_buffer);
     return complex_subtype_from_doubles(type, x, y);
 
   parse_error:
     PyErr_SetString(PyExc_ValueError,
                     "complex() arg is a malformed string");
   error:
-    if (s_buffer)
-        PyMem_FREE(s_buffer);
+    Py_XDECREF(s_buffer);
     return NULL;
 }
 

Modified: python/branches/pep-3151/Objects/descrobject.c
==============================================================================
--- python/branches/pep-3151/Objects/descrobject.c	(original)
+++ python/branches/pep-3151/Objects/descrobject.c	Sat Feb 26 08:16:32 2011
@@ -710,19 +710,19 @@
 static PyObject *
 proxy_keys(proxyobject *pp)
 {
-    return PyMapping_Keys(pp->dict);
+    return PyObject_CallMethod(pp->dict, "keys", NULL);
 }
 
 static PyObject *
 proxy_values(proxyobject *pp)
 {
-    return PyMapping_Values(pp->dict);
+    return PyObject_CallMethod(pp->dict, "values", NULL);
 }
 
 static PyObject *
 proxy_items(proxyobject *pp)
 {
-    return PyMapping_Items(pp->dict);
+    return PyObject_CallMethod(pp->dict, "items", NULL);
 }
 
 static PyObject *
@@ -766,6 +766,12 @@
     return PyObject_Str(pp->dict);
 }
 
+static PyObject *
+proxy_repr(proxyobject *pp)
+{
+    return PyUnicode_FromFormat("dict_proxy(%R)", pp->dict);
+}
+
 static int
 proxy_traverse(PyObject *self, visitproc visit, void *arg)
 {
@@ -791,7 +797,7 @@
     0,                                          /* tp_getattr */
     0,                                          /* tp_setattr */
     0,                                          /* tp_reserved */
-    0,                                          /* tp_repr */
+    (reprfunc)proxy_repr,                       /* tp_repr */
     0,                                          /* tp_as_number */
     &proxy_as_sequence,                         /* tp_as_sequence */
     &proxy_as_mapping,                          /* tp_as_mapping */
@@ -1190,7 +1196,7 @@
         PyErr_SetString(PyExc_AttributeError, "unreadable attribute");
         return NULL;
     }
-    return PyObject_CallFunction(gs->prop_get, "(O)", obj);
+    return PyObject_CallFunctionObjArgs(gs->prop_get, obj, NULL);
 }
 
 static int
@@ -1211,9 +1217,9 @@
         return -1;
     }
     if (value == NULL)
-        res = PyObject_CallFunction(func, "(O)", obj);
+        res = PyObject_CallFunctionObjArgs(func, obj, NULL);
     else
-        res = PyObject_CallFunction(func, "(OO)", obj, value);
+        res = PyObject_CallFunctionObjArgs(func, obj, value, NULL);
     if (res == NULL)
         return -1;
     Py_DECREF(res);

Modified: python/branches/pep-3151/Objects/dictobject.c
==============================================================================
--- python/branches/pep-3151/Objects/dictobject.c	(original)
+++ python/branches/pep-3151/Objects/dictobject.c	Sat Feb 26 08:16:32 2011
@@ -454,7 +454,7 @@
 {
     Py_ssize_t pos = 0;
     PyObject *key, *value;
-    assert(PyDict_CheckExact(dict));
+    assert(PyDict_Check(dict));
     /* Shortcut */
     if (((PyDictObject *)dict)->ma_lookup == lookdict_unicode)
         return 1;

Modified: python/branches/pep-3151/Objects/fileobject.c
==============================================================================
--- python/branches/pep-3151/Objects/fileobject.c	(original)
+++ python/branches/pep-3151/Objects/fileobject.c	Sat Feb 26 08:16:32 2011
@@ -297,8 +297,8 @@
         *p++ = c;
         if (c == '\n') break;
     }
-    if ( c == EOF && skipnextlf )
-        newlinetypes |= NEWLINE_CR;
+    /* if ( c == EOF && skipnextlf )
+        newlinetypes |= NEWLINE_CR; */
     FUNLOCKFILE(stream);
     *p = '\0';
     if ( skipnextlf ) {
@@ -344,7 +344,7 @@
 }
 
 static int
-fileio_init(PyObject *self, PyObject *args, PyObject *kwds)
+stdprinter_init(PyObject *self, PyObject *args, PyObject *kwds)
 {
     PyErr_SetString(PyExc_TypeError,
                     "cannot create 'stderrprinter' instances");
@@ -390,7 +390,13 @@
 
     Py_BEGIN_ALLOW_THREADS
     errno = 0;
+#if defined(MS_WIN64) || defined(MS_WINDOWS)
+    if (n > INT_MAX)
+        n = INT_MAX;
+    n = write(self->fd, c, (int)n);
+#else
     n = write(self->fd, c, n);
+#endif
     Py_END_ALLOW_THREADS
 
     if (n < 0) {
@@ -509,7 +515,7 @@
     0,                                          /* tp_descr_get */
     0,                                          /* tp_descr_set */
     0,                                          /* tp_dictoffset */
-    fileio_init,                                /* tp_init */
+    stdprinter_init,                            /* tp_init */
     PyType_GenericAlloc,                        /* tp_alloc */
     stdprinter_new,                             /* tp_new */
     PyObject_Del,                               /* tp_free */

Modified: python/branches/pep-3151/Objects/floatobject.c
==============================================================================
--- python/branches/pep-3151/Objects/floatobject.c	(original)
+++ python/branches/pep-3151/Objects/floatobject.c	Sat Feb 26 08:16:32 2011
@@ -5,7 +5,6 @@
    for any kind of float exception without losing portability. */
 
 #include "Python.h"
-#include "structseq.h"
 
 #include <ctype.h>
 #include <float.h>
@@ -175,22 +174,29 @@
 {
     const char *s, *last, *end;
     double x;
-    char buffer[256]; /* for errors */
-    char *s_buffer = NULL;
+    PyObject *s_buffer = NULL;
     Py_ssize_t len;
     PyObject *result = NULL;
 
     if (PyUnicode_Check(v)) {
-        s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
+        Py_ssize_t i, buflen = PyUnicode_GET_SIZE(v);
+        Py_UNICODE *bufptr;
+        s_buffer = PyUnicode_TransformDecimalToASCII(
+            PyUnicode_AS_UNICODE(v), buflen);
         if (s_buffer == NULL)
-            return PyErr_NoMemory();
-        if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
-                                    PyUnicode_GET_SIZE(v),
-                                    s_buffer,
-                                    NULL))
-            goto error;
-        s = s_buffer;
-        len = strlen(s);
+            return NULL;
+        /* Replace non-ASCII whitespace with ' ' */
+        bufptr = PyUnicode_AS_UNICODE(s_buffer);
+        for (i = 0; i < buflen; i++) {
+            Py_UNICODE ch = bufptr[i];
+            if (ch > 127 && Py_UNICODE_ISSPACE(ch))
+                bufptr[i] = ' ';
+        }
+        s = _PyUnicode_AsStringAndSize(s_buffer, &len);
+        if (s == NULL) {
+            Py_DECREF(s_buffer);
+            return NULL;
+        }
     }
     else if (PyObject_AsCharBuffer(v, &s, &len)) {
         PyErr_SetString(PyExc_TypeError,
@@ -198,29 +204,27 @@
         return NULL;
     }
     last = s + len;
-
-    while (Py_ISSPACE(*s))
+    /* strip space */
+    while (s < last && Py_ISSPACE(*s))
         s++;
+    while (s < last - 1 && Py_ISSPACE(last[-1]))
+        last--;
     /* We don't care about overflow or underflow.  If the platform
      * supports them, infinities and signed zeroes (on underflow) are
      * fine. */
     x = PyOS_string_to_double(s, (char **)&end, NULL);
-    if (x == -1.0 && PyErr_Occurred())
-        goto error;
-    while (Py_ISSPACE(*end))
-        end++;
-    if (end == last)
-        result = PyFloat_FromDouble(x);
-    else {
-        PyOS_snprintf(buffer, sizeof(buffer),
-                      "invalid literal for float(): %.200s", s);
-        PyErr_SetString(PyExc_ValueError, buffer);
+    if (end != last) {
+        PyErr_Format(PyExc_ValueError,
+                     "could not convert string to float: "
+                     "%R", v);
         result = NULL;
     }
+    else if (x == -1.0 && PyErr_Occurred())
+        result = NULL;
+    else
+        result = PyFloat_FromDouble(x);
 
-  error:
-    if (s_buffer)
-        PyMem_FREE(s_buffer);
+    Py_XDECREF(s_buffer);
     return result;
 }
 
@@ -570,13 +574,11 @@
     double a,b;
     CONVERT_TO_DOUBLE(v, a);
     CONVERT_TO_DOUBLE(w, b);
-#ifdef Py_NAN
     if (b == 0.0) {
         PyErr_SetString(PyExc_ZeroDivisionError,
                         "float division by zero");
         return NULL;
     }
-#endif
     PyFPE_START_PROTECT("divide", return 0)
     a = a / b;
     PyFPE_END_PROTECT(a)
@@ -590,19 +592,24 @@
     double mod;
     CONVERT_TO_DOUBLE(v, vx);
     CONVERT_TO_DOUBLE(w, wx);
-#ifdef Py_NAN
     if (wx == 0.0) {
         PyErr_SetString(PyExc_ZeroDivisionError,
                         "float modulo");
         return NULL;
     }
-#endif
     PyFPE_START_PROTECT("modulo", return 0)
     mod = fmod(vx, wx);
-    /* note: checking mod*wx < 0 is incorrect -- underflows to
-       0 if wx < sqrt(smallest nonzero double) */
-    if (mod && ((wx < 0) != (mod < 0))) {
-        mod += wx;
+    if (mod) {
+        /* ensure the remainder has the same sign as the denominator */
+        if ((wx < 0) != (mod < 0)) {
+            mod += wx;
+        }
+    }
+    else {
+        /* the remainder is zero, and in the presence of signed zeroes
+           fmod returns different results across platforms; ensure
+           it has the same sign as the denominator. */
+        mod = copysign(0.0, wx);
     }
     PyFPE_END_PROTECT(mod)
     return PyFloat_FromDouble(mod);
@@ -638,11 +645,8 @@
     else {
         /* the remainder is zero, and in the presence of signed zeroes
            fmod returns different results across platforms; ensure
-           it has the same sign as the denominator; we'd like to do
-           "mod = wx * 0.0", but that may get optimized away */
-        mod *= mod;  /* hide "mod = +0" from optimizer */
-        if (wx < 0.0)
-            mod = -mod;
+           it has the same sign as the denominator. */
+        mod = copysign(0.0, wx);
     }
     /* snap quotient to nearest integral value */
     if (div) {
@@ -652,8 +656,7 @@
     }
     else {
         /* div is zero - get the same sign as the true quotient */
-        div *= div;             /* hide "div = +0" from optimizers */
-        floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
+        floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */
     }
     PyFPE_END_PROTECT(floordiv)
     return Py_BuildValue("(dd)", floordiv, mod);
@@ -1487,13 +1490,11 @@
                       "Cannot pass infinity to float.as_integer_ratio.");
       return NULL;
     }
-#ifdef Py_NAN
     if (Py_IS_NAN(self)) {
       PyErr_SetString(PyExc_ValueError,
                       "Cannot pass NaN to float.as_integer_ratio.");
       return NULL;
     }
-#endif
 
     PyFPE_START_PROTECT("as_integer_ratio", goto error);
     float_part = frexp(self, &exponent);        /* self == float_part * 2**exponent exactly */
@@ -2244,7 +2245,7 @@
 
         /* Eighth byte */
         *p = flo & 0xFF;
-        p += incr;
+        /* p += incr; */
 
         /* Done */
         return 0;

Modified: python/branches/pep-3151/Objects/funcobject.c
==============================================================================
--- python/branches/pep-3151/Objects/funcobject.c	(original)
+++ python/branches/pep-3151/Objects/funcobject.c	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,6 @@
 
 #include "Python.h"
 #include "code.h"
-#include "eval.h"
 #include "structmember.h"
 
 PyObject *
@@ -628,7 +627,7 @@
     }
 
     result = PyEval_EvalCodeEx(
-        (PyCodeObject *)PyFunction_GET_CODE(func),
+        PyFunction_GET_CODE(func),
         PyFunction_GET_GLOBALS(func), (PyObject *)NULL,
         &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg),
         k, nk, d, nd,

Modified: python/branches/pep-3151/Objects/genobject.c
==============================================================================
--- python/branches/pep-3151/Objects/genobject.c	(original)
+++ python/branches/pep-3151/Objects/genobject.c	Sat Feb 26 08:16:32 2011
@@ -2,8 +2,6 @@
 
 #include "Python.h"
 #include "frameobject.h"
-#include "genobject.h"
-#include "ceval.h"
 #include "structmember.h"
 #include "opcode.h"
 

Modified: python/branches/pep-3151/Objects/listobject.c
==============================================================================
--- python/branches/pep-3151/Objects/listobject.c	(original)
+++ python/branches/pep-3151/Objects/listobject.c	Sat Feb 26 08:16:32 2011
@@ -747,6 +747,19 @@
 }
 
 static PyObject *
+listclear(PyListObject *self)
+{
+    list_clear(self);
+    Py_RETURN_NONE;
+}
+
+static PyObject *
+listcopy(PyListObject *self)
+{
+    return list_slice(self, 0, Py_SIZE(self));
+}
+
+static PyObject *
 listappend(PyListObject *self, PyObject *v)
 {
     if (app1(self, v) == 0)
@@ -940,6 +953,71 @@
  * pieces to this algorithm; read listsort.txt for overviews and details.
  */
 
+/* A sortslice contains a pointer to an array of keys and a pointer to
+ * an array of corresponding values.  In other words, keys[i]
+ * corresponds with values[i].  If values == NULL, then the keys are
+ * also the values.
+ *
+ * Several convenience routines are provided here, so that keys and
+ * values are always moved in sync.
+ */
+
+typedef struct {
+    PyObject **keys;
+    PyObject **values;
+} sortslice;
+
+Py_LOCAL_INLINE(void)
+sortslice_copy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j)
+{
+    s1->keys[i] = s2->keys[j];
+    if (s1->values != NULL)
+        s1->values[i] = s2->values[j];
+}
+
+Py_LOCAL_INLINE(void)
+sortslice_copy_incr(sortslice *dst, sortslice *src)
+{
+    *dst->keys++ = *src->keys++;
+    if (dst->values != NULL)
+        *dst->values++ = *src->values++;
+}
+
+Py_LOCAL_INLINE(void)
+sortslice_copy_decr(sortslice *dst, sortslice *src)
+{
+    *dst->keys-- = *src->keys--;
+    if (dst->values != NULL)
+        *dst->values-- = *src->values--;
+}
+
+
+Py_LOCAL_INLINE(void)
+sortslice_memcpy(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
+                 Py_ssize_t n)
+{
+    memcpy(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
+    if (s1->values != NULL)
+        memcpy(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
+}
+
+Py_LOCAL_INLINE(void)
+sortslice_memmove(sortslice *s1, Py_ssize_t i, sortslice *s2, Py_ssize_t j,
+                  Py_ssize_t n)
+{
+    memmove(&s1->keys[i], &s2->keys[j], sizeof(PyObject *) * n);
+    if (s1->values != NULL)
+        memmove(&s1->values[i], &s2->values[j], sizeof(PyObject *) * n);
+}
+
+Py_LOCAL_INLINE(void)
+sortslice_advance(sortslice *slice, Py_ssize_t n)
+{
+    slice->keys += n;
+    if (slice->values != NULL)
+        slice->values += n;
+}
+
 /* Comparison function: PyObject_RichCompareBool with Py_LT.
  * Returns -1 on error, 1 if x < y, 0 if x >= y.
  */
@@ -965,19 +1043,19 @@
    the input (nothing is lost or duplicated).
 */
 static int
-binarysort(PyObject **lo, PyObject **hi, PyObject **start)
+binarysort(sortslice lo, PyObject **hi, PyObject **start)
 {
     register Py_ssize_t k;
     register PyObject **l, **p, **r;
     register PyObject *pivot;
 
-    assert(lo <= start && start <= hi);
+    assert(lo.keys <= start && start <= hi);
     /* assert [lo, start) is sorted */
-    if (lo == start)
+    if (lo.keys == start)
         ++start;
     for (; start < hi; ++start) {
         /* set l to where *start belongs */
-        l = lo;
+        l = lo.keys;
         r = start;
         pivot = *r;
         /* Invariants:
@@ -1004,6 +1082,15 @@
         for (p = start; p > l; --p)
             *p = *(p-1);
         *l = pivot;
+        if (lo.values != NULL) {
+            Py_ssize_t offset = lo.values - lo.keys;
+            p = start + offset;
+            pivot = *p;
+            l += offset;
+            for (p = start + offset; p > l; --p)
+                *p = *(p-1);
+            *l = pivot;
+        }
     }
     return 0;
 
@@ -1272,7 +1359,7 @@
  * a convenient way to pass state around among the helper functions.
  */
 struct s_slice {
-    PyObject **base;
+    sortslice base;
     Py_ssize_t len;
 };
 
@@ -1286,7 +1373,7 @@
     /* 'a' is temp storage to help with merges.  It contains room for
      * alloced entries.
      */
-    PyObject **a;       /* may point to temparray below */
+    sortslice a;        /* may point to temparray below */
     Py_ssize_t alloced;
 
     /* A stack of n pending runs yet to be merged.  Run #i starts at
@@ -1307,11 +1394,29 @@
 
 /* Conceptually a MergeState's constructor. */
 static void
-merge_init(MergeState *ms)
+merge_init(MergeState *ms, Py_ssize_t list_size, int has_keyfunc)
 {
     assert(ms != NULL);
-    ms->a = ms->temparray;
-    ms->alloced = MERGESTATE_TEMP_SIZE;
+    if (has_keyfunc) {
+        /* The temporary space for merging will need at most half the list
+         * size rounded up.  Use the minimum possible space so we can use the
+         * rest of temparray for other things.  In particular, if there is
+         * enough extra space, listsort() will use it to store the keys.
+         */
+        ms->alloced = (list_size + 1) / 2;
+
+        /* ms->alloced describes how many keys will be stored at
+           ms->temparray, but we also need to store the values.  Hence,
+           ms->alloced is capped at half of MERGESTATE_TEMP_SIZE. */
+        if (MERGESTATE_TEMP_SIZE / 2 < ms->alloced)
+            ms->alloced = MERGESTATE_TEMP_SIZE / 2;
+        ms->a.values = &ms->temparray[ms->alloced];
+    }
+    else {
+        ms->alloced = MERGESTATE_TEMP_SIZE;
+        ms->a.values = NULL;
+    }
+    ms->a.keys = ms->temparray;
     ms->n = 0;
     ms->min_gallop = MIN_GALLOP;
 }
@@ -1324,10 +1429,8 @@
 merge_freemem(MergeState *ms)
 {
     assert(ms != NULL);
-    if (ms->a != ms->temparray)
-        PyMem_Free(ms->a);
-    ms->a = ms->temparray;
-    ms->alloced = MERGESTATE_TEMP_SIZE;
+    if (ms->a.keys != ms->temparray)
+        PyMem_Free(ms->a.keys);
 }
 
 /* Ensure enough temp memory for 'need' array slots is available.
@@ -1336,52 +1439,60 @@
 static int
 merge_getmem(MergeState *ms, Py_ssize_t need)
 {
+    int multiplier;
+
     assert(ms != NULL);
     if (need <= ms->alloced)
         return 0;
+
+    multiplier = ms->a.values != NULL ? 2 : 1;
+
     /* Don't realloc!  That can cost cycles to copy the old data, but
      * we don't care what's in the block.
      */
     merge_freemem(ms);
-    if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
+    if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*) / multiplier) {
         PyErr_NoMemory();
         return -1;
     }
-    ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
-    if (ms->a) {
+    ms->a.keys = (PyObject**)PyMem_Malloc(multiplier * need
+                                          * sizeof(PyObject *));
+    if (ms->a.keys != NULL) {
         ms->alloced = need;
+        if (ms->a.values != NULL)
+            ms->a.values = &ms->a.keys[need];
         return 0;
     }
     PyErr_NoMemory();
-    merge_freemem(ms);          /* reset to sane state */
     return -1;
 }
 #define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 :   \
                                 merge_getmem(MS, NEED))
 
-/* Merge the na elements starting at pa with the nb elements starting at pb
- * in a stable way, in-place.  na and nb must be > 0, and pa + na == pb.
- * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
- * merge, and should have na <= nb.  See listsort.txt for more info.
- * Return 0 if successful, -1 if error.
+/* Merge the na elements starting at ssa with the nb elements starting at
+ * ssb.keys = ssa.keys + na in a stable way, in-place.  na and nb must be > 0.
+ * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
+ * should have na <= nb.  See listsort.txt for more info.  Return 0 if
+ * successful, -1 if error.
  */
 static Py_ssize_t
-merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
-                         PyObject **pb, Py_ssize_t nb)
+merge_lo(MergeState *ms, sortslice ssa, Py_ssize_t na,
+         sortslice ssb, Py_ssize_t nb)
 {
     Py_ssize_t k;
-    PyObject **dest;
+    sortslice dest;
     int result = -1;            /* guilty until proved innocent */
     Py_ssize_t min_gallop;
 
-    assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
+    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
+    assert(ssa.keys + na == ssb.keys);
     if (MERGE_GETMEM(ms, na) < 0)
         return -1;
-    memcpy(ms->a, pa, na * sizeof(PyObject*));
-    dest = pa;
-    pa = ms->a;
+    sortslice_memcpy(&ms->a, 0, &ssa, 0, na);
+    dest = ssa;
+    ssa = ms->a;
 
-    *dest++ = *pb++;
+    sortslice_copy_incr(&dest, &ssb);
     --nb;
     if (nb == 0)
         goto Succeed;
@@ -1398,11 +1509,11 @@
          */
         for (;;) {
             assert(na > 1 && nb > 0);
-            k = ISLT(*pb, *pa);
+            k = ISLT(ssb.keys[0], ssa.keys[0]);
             if (k) {
                 if (k < 0)
                     goto Fail;
-                *dest++ = *pb++;
+                sortslice_copy_incr(&dest, &ssb);
                 ++bcount;
                 acount = 0;
                 --nb;
@@ -1412,7 +1523,7 @@
                     break;
             }
             else {
-                *dest++ = *pa++;
+                sortslice_copy_incr(&dest, &ssa);
                 ++acount;
                 bcount = 0;
                 --na;
@@ -1433,14 +1544,14 @@
             assert(na > 1 && nb > 0);
             min_gallop -= min_gallop > 1;
             ms->min_gallop = min_gallop;
-            k = gallop_right(*pb, pa, na, 0);
+            k = gallop_right(ssb.keys[0], ssa.keys, na, 0);
             acount = k;
             if (k) {
                 if (k < 0)
                     goto Fail;
-                memcpy(dest, pa, k * sizeof(PyObject *));
-                dest += k;
-                pa += k;
+                sortslice_memcpy(&dest, 0, &ssa, 0, k);
+                sortslice_advance(&dest, k);
+                sortslice_advance(&ssa, k);
                 na -= k;
                 if (na == 1)
                     goto CopyB;
@@ -1451,24 +1562,24 @@
                 if (na == 0)
                     goto Succeed;
             }
-            *dest++ = *pb++;
+            sortslice_copy_incr(&dest, &ssb);
             --nb;
             if (nb == 0)
                 goto Succeed;
 
-            k = gallop_left(*pa, pb, nb, 0);
+            k = gallop_left(ssa.keys[0], ssb.keys, nb, 0);
             bcount = k;
             if (k) {
                 if (k < 0)
                     goto Fail;
-                memmove(dest, pb, k * sizeof(PyObject *));
-                dest += k;
-                pb += k;
+                sortslice_memmove(&dest, 0, &ssb, 0, k);
+                sortslice_advance(&dest, k);
+                sortslice_advance(&ssb, k);
                 nb -= k;
                 if (nb == 0)
                     goto Succeed;
             }
-            *dest++ = *pa++;
+            sortslice_copy_incr(&dest, &ssa);
             --na;
             if (na == 1)
                 goto CopyB;
@@ -1480,43 +1591,46 @@
     result = 0;
 Fail:
     if (na)
-        memcpy(dest, pa, na * sizeof(PyObject*));
+        sortslice_memcpy(&dest, 0, &ssa, 0, na);
     return result;
 CopyB:
     assert(na == 1 && nb > 0);
-    /* The last element of pa belongs at the end of the merge. */
-    memmove(dest, pb, nb * sizeof(PyObject *));
-    dest[nb] = *pa;
+    /* The last element of ssa belongs at the end of the merge. */
+    sortslice_memmove(&dest, 0, &ssb, 0, nb);
+    sortslice_copy(&dest, nb, &ssa, 0);
     return 0;
 }
 
-/* Merge the na elements starting at pa with the nb elements starting at pb
- * in a stable way, in-place.  na and nb must be > 0, and pa + na == pb.
- * Must also have that *pb < *pa, that pa[na-1] belongs at the end of the
- * merge, and should have na >= nb.  See listsort.txt for more info.
- * Return 0 if successful, -1 if error.
+/* Merge the na elements starting at pa with the nb elements starting at
+ * ssb.keys = ssa.keys + na in a stable way, in-place.  na and nb must be > 0.
+ * Must also have that ssa.keys[na-1] belongs at the end of the merge, and
+ * should have na >= nb.  See listsort.txt for more info.  Return 0 if
+ * successful, -1 if error.
  */
 static Py_ssize_t
-merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
+merge_hi(MergeState *ms, sortslice ssa, Py_ssize_t na,
+         sortslice ssb, Py_ssize_t nb)
 {
     Py_ssize_t k;
-    PyObject **dest;
+    sortslice dest, basea, baseb;
     int result = -1;            /* guilty until proved innocent */
-    PyObject **basea;
-    PyObject **baseb;
     Py_ssize_t min_gallop;
 
-    assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
+    assert(ms && ssa.keys && ssb.keys && na > 0 && nb > 0);
+    assert(ssa.keys + na == ssb.keys);
     if (MERGE_GETMEM(ms, nb) < 0)
         return -1;
-    dest = pb + nb - 1;
-    memcpy(ms->a, pb, nb * sizeof(PyObject*));
-    basea = pa;
+    dest = ssb;
+    sortslice_advance(&dest, nb-1);
+    sortslice_memcpy(&ms->a, 0, &ssb, 0, nb);
+    basea = ssa;
     baseb = ms->a;
-    pb = ms->a + nb - 1;
-    pa += na - 1;
+    ssb.keys = ms->a.keys + nb - 1;
+    if (ssb.values != NULL)
+        ssb.values = ms->a.values + nb - 1;
+    sortslice_advance(&ssa, na - 1);
 
-    *dest-- = *pa--;
+    sortslice_copy_decr(&dest, &ssa);
     --na;
     if (na == 0)
         goto Succeed;
@@ -1533,11 +1647,11 @@
          */
         for (;;) {
             assert(na > 0 && nb > 1);
-            k = ISLT(*pb, *pa);
+            k = ISLT(ssb.keys[0], ssa.keys[0]);
             if (k) {
                 if (k < 0)
                     goto Fail;
-                *dest-- = *pa--;
+                sortslice_copy_decr(&dest, &ssa);
                 ++acount;
                 bcount = 0;
                 --na;
@@ -1547,7 +1661,7 @@
                     break;
             }
             else {
-                *dest-- = *pb--;
+                sortslice_copy_decr(&dest, &ssb);
                 ++bcount;
                 acount = 0;
                 --nb;
@@ -1568,33 +1682,33 @@
             assert(na > 0 && nb > 1);
             min_gallop -= min_gallop > 1;
             ms->min_gallop = min_gallop;
-            k = gallop_right(*pb, basea, na, na-1);
+            k = gallop_right(ssb.keys[0], basea.keys, na, na-1);
             if (k < 0)
                 goto Fail;
             k = na - k;
             acount = k;
             if (k) {
-                dest -= k;
-                pa -= k;
-                memmove(dest+1, pa+1, k * sizeof(PyObject *));
+                sortslice_advance(&dest, -k);
+                sortslice_advance(&ssa, -k);
+                sortslice_memmove(&dest, 1, &ssa, 1, k);
                 na -= k;
                 if (na == 0)
                     goto Succeed;
             }
-            *dest-- = *pb--;
+            sortslice_copy_decr(&dest, &ssb);
             --nb;
             if (nb == 1)
                 goto CopyA;
 
-            k = gallop_left(*pa, baseb, nb, nb-1);
+            k = gallop_left(ssa.keys[0], baseb.keys, nb, nb-1);
             if (k < 0)
                 goto Fail;
             k = nb - k;
             bcount = k;
             if (k) {
-                dest -= k;
-                pb -= k;
-                memcpy(dest+1, pb+1, k * sizeof(PyObject *));
+                sortslice_advance(&dest, -k);
+                sortslice_advance(&ssb, -k);
+                sortslice_memcpy(&dest, 1, &ssb, 1, k);
                 nb -= k;
                 if (nb == 1)
                     goto CopyA;
@@ -1605,7 +1719,7 @@
                 if (nb == 0)
                     goto Succeed;
             }
-            *dest-- = *pa--;
+            sortslice_copy_decr(&dest, &ssa);
             --na;
             if (na == 0)
                 goto Succeed;
@@ -1617,15 +1731,15 @@
     result = 0;
 Fail:
     if (nb)
-        memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
+        sortslice_memcpy(&dest, -(nb-1), &baseb, 0, nb);
     return result;
 CopyA:
     assert(nb == 1 && na > 0);
-    /* The first element of pb belongs at the front of the merge. */
-    dest -= na;
-    pa -= na;
-    memmove(dest+1, pa+1, na * sizeof(PyObject *));
-    *dest = *pb;
+    /* The first element of ssb belongs at the front of the merge. */
+    sortslice_memmove(&dest, 1-na, &ssa, 1-na, na);
+    sortslice_advance(&dest, -na);
+    sortslice_advance(&ssa, -na);
+    sortslice_copy(&dest, 0, &ssb, 0);
     return 0;
 }
 
@@ -1635,7 +1749,7 @@
 static Py_ssize_t
 merge_at(MergeState *ms, Py_ssize_t i)
 {
-    PyObject **pa, **pb;
+    sortslice ssa, ssb;
     Py_ssize_t na, nb;
     Py_ssize_t k;
 
@@ -1644,12 +1758,12 @@
     assert(i >= 0);
     assert(i == ms->n - 2 || i == ms->n - 3);
 
-    pa = ms->pending[i].base;
+    ssa = ms->pending[i].base;
     na = ms->pending[i].len;
-    pb = ms->pending[i+1].base;
+    ssb = ms->pending[i+1].base;
     nb = ms->pending[i+1].len;
     assert(na > 0 && nb > 0);
-    assert(pa + na == pb);
+    assert(ssa.keys + na == ssb.keys);
 
     /* Record the length of the combined runs; if i is the 3rd-last
      * run now, also slide over the last run (which isn't involved
@@ -1663,10 +1777,10 @@
     /* Where does b start in a?  Elements in a before that can be
      * ignored (already in place).
      */
-    k = gallop_right(*pb, pa, na, 0);
+    k = gallop_right(*ssb.keys, ssa.keys, na, 0);
     if (k < 0)
         return -1;
-    pa += k;
+    sortslice_advance(&ssa, k);
     na -= k;
     if (na == 0)
         return 0;
@@ -1674,7 +1788,7 @@
     /* Where does a end in b?  Elements in b after that can be
      * ignored (already in place).
      */
-    nb = gallop_left(pa[na-1], pb, nb, nb-1);
+    nb = gallop_left(ssa.keys[na-1], ssb.keys, nb, nb-1);
     if (nb <= 0)
         return nb;
 
@@ -1682,9 +1796,9 @@
      * min(na, nb) elements.
      */
     if (na <= nb)
-        return merge_lo(ms, pa, na, pb, nb);
+        return merge_lo(ms, ssa, na, ssb, nb);
     else
-        return merge_hi(ms, pa, na, pb, nb);
+        return merge_hi(ms, ssa, na, ssb, nb);
 }
 
 /* Examine the stack of runs waiting to be merged, merging adjacent runs
@@ -1765,103 +1879,12 @@
     return n + r;
 }
 
-/* Special wrapper to support stable sorting using the decorate-sort-undecorate
-   pattern.  Holds a key which is used for comparisons and the original record
-   which is returned during the undecorate phase.  By exposing only the key
-   during comparisons, the underlying sort stability characteristics are left
-   unchanged.  Also, the comparison function will only see the key instead of
-   a full record. */
-
-typedef struct {
-    PyObject_HEAD
-    PyObject *key;
-    PyObject *value;
-} sortwrapperobject;
-
-PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
-static PyObject *
-sortwrapper_richcompare(sortwrapperobject *, sortwrapperobject *, int);
 static void
-sortwrapper_dealloc(sortwrapperobject *);
-
-PyTypeObject PySortWrapper_Type = {
-    PyVarObject_HEAD_INIT(&PyType_Type, 0)
-    "sortwrapper",                              /* tp_name */
-    sizeof(sortwrapperobject),                  /* tp_basicsize */
-    0,                                          /* tp_itemsize */
-    /* methods */
-    (destructor)sortwrapper_dealloc,            /* tp_dealloc */
-    0,                                          /* tp_print */
-    0,                                          /* tp_getattr */
-    0,                                          /* tp_setattr */
-    0,                                          /* tp_reserved */
-    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 */
-    sortwrapper_doc,                            /* tp_doc */
-    0,                                          /* tp_traverse */
-    0,                                          /* tp_clear */
-    (richcmpfunc)sortwrapper_richcompare,       /* tp_richcompare */
-};
-
-
-static PyObject *
-sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
-{
-    if (!PyObject_TypeCheck(b, &PySortWrapper_Type)) {
-        PyErr_SetString(PyExc_TypeError,
-            "expected a sortwrapperobject");
-        return NULL;
-    }
-    return PyObject_RichCompare(a->key, b->key, op);
-}
-
-static void
-sortwrapper_dealloc(sortwrapperobject *so)
+reverse_sortslice(sortslice *s, Py_ssize_t n)
 {
-    Py_XDECREF(so->key);
-    Py_XDECREF(so->value);
-    PyObject_Del(so);
-}
-
-/* Returns a new reference to a sortwrapper.
-   Consumes the references to the two underlying objects. */
-
-static PyObject *
-build_sortwrapper(PyObject *key, PyObject *value)
-{
-    sortwrapperobject *so;
-
-    so = PyObject_New(sortwrapperobject, &PySortWrapper_Type);
-    if (so == NULL)
-        return NULL;
-    so->key = key;
-    so->value = value;
-    return (PyObject *)so;
-}
-
-/* Returns a new reference to the value underlying the wrapper. */
-static PyObject *
-sortwrapper_getvalue(PyObject *so)
-{
-    PyObject *value;
-
-    if (!PyObject_TypeCheck(so, &PySortWrapper_Type)) {
-        PyErr_SetString(PyExc_TypeError,
-            "expected a sortwrapperobject");
-        return NULL;
-    }
-    value = ((sortwrapperobject *)so)->value;
-    Py_INCREF(value);
-    return value;
+    reverse_slice(s->keys, &s->keys[n]);
+    if (s->values != NULL)
+        reverse_slice(s->values, &s->values[n]);
 }
 
 /* An adaptive, stable, natural mergesort.  See listsort.txt.
@@ -1873,9 +1896,9 @@
 listsort(PyListObject *self, PyObject *args, PyObject *kwds)
 {
     MergeState ms;
-    PyObject **lo, **hi;
     Py_ssize_t nremaining;
     Py_ssize_t minrun;
+    sortslice lo;
     Py_ssize_t saved_ob_size, saved_allocated;
     PyObject **saved_ob_item;
     PyObject **final_ob_item;
@@ -1883,8 +1906,8 @@
     int reverse = 0;
     PyObject *keyfunc = NULL;
     Py_ssize_t i;
-    PyObject *key, *value, *kvpair;
     static char *kwlist[] = {"key", "reverse", 0};
+    PyObject **keys;
 
     assert(self != NULL);
     assert (PyList_Check(self));
@@ -1913,28 +1936,36 @@
     self->ob_item = NULL;
     self->allocated = -1; /* any operation will reset it to >= 0 */
 
-    if (keyfunc != NULL) {
-        for (i=0 ; i < saved_ob_size ; i++) {
-            value = saved_ob_item[i];
-            key = PyObject_CallFunctionObjArgs(keyfunc, value,
-                                               NULL);
-            if (key == NULL) {
-                for (i=i-1 ; i>=0 ; i--) {
-                    kvpair = saved_ob_item[i];
-                    value = sortwrapper_getvalue(kvpair);
-                    saved_ob_item[i] = value;
-                    Py_DECREF(kvpair);
-                }
-                goto dsu_fail;
+    if (keyfunc == NULL) {
+        keys = NULL;
+        lo.keys = saved_ob_item;
+        lo.values = NULL;
+    }
+    else {
+        if (saved_ob_size < MERGESTATE_TEMP_SIZE/2)
+            /* Leverage stack space we allocated but won't otherwise use */
+            keys = &ms.temparray[saved_ob_size+1];
+        else {
+            keys = PyMem_MALLOC(sizeof(PyObject *) * saved_ob_size);
+            if (keys == NULL)
+                return NULL;
+        }
+
+        for (i = 0; i < saved_ob_size ; i++) {
+            keys[i] = PyObject_CallFunctionObjArgs(keyfunc, saved_ob_item[i],
+                                                   NULL);
+            if (keys[i] == NULL) {
+                for (i=i-1 ; i>=0 ; i--)
+                    Py_DECREF(keys[i]);
+                goto keyfunc_fail;
             }
-            kvpair = build_sortwrapper(key, value);
-            if (kvpair == NULL)
-                goto dsu_fail;
-            saved_ob_item[i] = kvpair;
         }
+
+        lo.keys = keys;
+        lo.values = saved_ob_item;
     }
 
-    merge_init(&ms);
+    merge_init(&ms, saved_ob_size, keys != NULL);
 
     nremaining = saved_ob_size;
     if (nremaining < 2)
@@ -1942,30 +1973,31 @@
 
     /* Reverse sort stability achieved by initially reversing the list,
     applying a stable forward sort, then reversing the final result. */
-    if (reverse)
-        reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
+    if (reverse) {
+        if (keys != NULL)
+            reverse_slice(&keys[0], &keys[saved_ob_size]);
+        reverse_slice(&saved_ob_item[0], &saved_ob_item[saved_ob_size]);
+    }
 
     /* March over the array once, left to right, finding natural runs,
      * and extending short natural runs to minrun elements.
      */
-    lo = saved_ob_item;
-    hi = lo + nremaining;
     minrun = merge_compute_minrun(nremaining);
     do {
         int descending;
         Py_ssize_t n;
 
         /* Identify next run. */
-        n = count_run(lo, hi, &descending);
+        n = count_run(lo.keys, lo.keys + nremaining, &descending);
         if (n < 0)
             goto fail;
         if (descending)
-            reverse_slice(lo, lo + n);
+            reverse_sortslice(&lo, n);
         /* If short, extend to min(minrun, nremaining). */
         if (n < minrun) {
             const Py_ssize_t force = nremaining <= minrun ?
                               nremaining : minrun;
-            if (binarysort(lo, lo + force, lo + n) < 0)
+            if (binarysort(lo, lo.keys + force, lo.keys + n) < 0)
                 goto fail;
             n = force;
         }
@@ -1977,27 +2009,27 @@
         if (merge_collapse(&ms) < 0)
             goto fail;
         /* Advance to find next run. */
-        lo += n;
+        sortslice_advance(&lo, n);
         nremaining -= n;
     } while (nremaining);
-    assert(lo == hi);
 
     if (merge_force_collapse(&ms) < 0)
         goto fail;
     assert(ms.n == 1);
-    assert(ms.pending[0].base == saved_ob_item);
+    assert(keys == NULL
+           ? ms.pending[0].base.keys == saved_ob_item
+           : ms.pending[0].base.keys == &keys[0]);
     assert(ms.pending[0].len == saved_ob_size);
+    lo = ms.pending[0].base;
 
 succeed:
     result = Py_None;
 fail:
-    if (keyfunc != NULL) {
-        for (i=0 ; i < saved_ob_size ; i++) {
-            kvpair = saved_ob_item[i];
-            value = sortwrapper_getvalue(kvpair);
-            saved_ob_item[i] = value;
-            Py_DECREF(kvpair);
-        }
+    if (keys != NULL) {
+        for (i = 0; i < saved_ob_size; i++)
+            Py_DECREF(keys[i]);
+        if (keys != &ms.temparray[saved_ob_size+1])
+            PyMem_FREE(keys);
     }
 
     if (self->allocated != -1 && result != NULL) {
@@ -2013,7 +2045,7 @@
 
     merge_freemem(&ms);
 
-dsu_fail:
+keyfunc_fail:
     final_ob_item = self->ob_item;
     i = Py_SIZE(self);
     Py_SIZE(self) = saved_ob_size;
@@ -2303,6 +2335,10 @@
 "L.__reversed__() -- return a reverse iterator over the list");
 PyDoc_STRVAR(sizeof_doc,
 "L.__sizeof__() -- size of L in memory, in bytes");
+PyDoc_STRVAR(clear_doc,
+"L.clear() -> None -- remove all items from L");
+PyDoc_STRVAR(copy_doc,
+"L.copy() -> list -- a shallow copy of L");
 PyDoc_STRVAR(append_doc,
 "L.append(object) -- append object to end");
 PyDoc_STRVAR(extend_doc,
@@ -2331,9 +2367,11 @@
     {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
     {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
     {"__sizeof__",  (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
+    {"clear",           (PyCFunction)listclear,   METH_NOARGS, clear_doc},
+    {"copy",            (PyCFunction)listcopy,   METH_NOARGS, copy_doc},
     {"append",          (PyCFunction)listappend,  METH_O, append_doc},
     {"insert",          (PyCFunction)listinsert,  METH_VARARGS, insert_doc},
-    {"extend",      (PyCFunction)listextend,  METH_O, extend_doc},
+    {"extend",          (PyCFunction)listextend,  METH_O, extend_doc},
     {"pop",             (PyCFunction)listpop,     METH_VARARGS, pop_doc},
     {"remove",          (PyCFunction)listremove,  METH_O, remove_doc},
     {"index",           (PyCFunction)listindex,   METH_VARARGS, index_doc},
@@ -2378,7 +2416,7 @@
         PyObject* it;
         PyObject **src, **dest;
 
-        if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
+        if (PySlice_GetIndicesEx(item, Py_SIZE(self),
                          &start, &stop, &step, &slicelength) < 0) {
             return NULL;
         }
@@ -2427,7 +2465,7 @@
     else if (PySlice_Check(item)) {
         Py_ssize_t start, stop, step, slicelength;
 
-        if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
+        if (PySlice_GetIndicesEx(item, Py_SIZE(self),
                          &start, &stop, &step, &slicelength) < 0) {
             return -1;
         }
@@ -2862,4 +2900,3 @@
         len = 0;
     return PyLong_FromSsize_t(len);
 }
-

Modified: python/branches/pep-3151/Objects/longobject.c
==============================================================================
--- python/branches/pep-3151/Objects/longobject.c	(original)
+++ python/branches/pep-3151/Objects/longobject.c	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,6 @@
 
 #include "Python.h"
 #include "longintrepr.h"
-#include "structseq.h"
 
 #include <float.h>
 #include <ctype.h>
@@ -2134,17 +2133,34 @@
 PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
 {
     PyObject *result;
-    char *buffer = (char *)PyMem_MALLOC(length+1);
-
-    if (buffer == NULL)
-        return NULL;
-
-    if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
-        PyMem_FREE(buffer);
+    PyObject *asciidig;
+    char *buffer, *end;
+    Py_ssize_t i, buflen;
+    Py_UNICODE *ptr;
+
+    asciidig = PyUnicode_TransformDecimalToASCII(u, length);
+    if (asciidig == NULL)
+        return NULL;
+    /* Replace non-ASCII whitespace with ' ' */
+    ptr = PyUnicode_AS_UNICODE(asciidig);
+    for (i = 0; i < length; i++) {
+        Py_UNICODE ch = ptr[i];
+        if (ch > 127 && Py_UNICODE_ISSPACE(ch))
+            ptr[i] = ' ';
+    }
+    buffer = _PyUnicode_AsStringAndSize(asciidig, &buflen);
+    if (buffer == NULL) {
+        Py_DECREF(asciidig);
         return NULL;
     }
-    result = PyLong_FromString(buffer, NULL, base);
-    PyMem_FREE(buffer);
+    result = PyLong_FromString(buffer, &end, base);
+    if (result != NULL && end != buffer + buflen) {
+        PyErr_SetString(PyExc_ValueError,
+                        "null byte in argument for int()");
+        Py_DECREF(result);
+        result = NULL;
+    }
+    Py_DECREF(asciidig);
     return result;
 }
 

Modified: python/branches/pep-3151/Objects/memoryobject.c
==============================================================================
--- python/branches/pep-3151/Objects/memoryobject.c	(original)
+++ python/branches/pep-3151/Objects/memoryobject.c	Sat Feb 26 08:16:32 2011
@@ -52,9 +52,6 @@
 {
     int res = 0;
     CHECK_RELEASED_INT(self);
-    /* XXX for whatever reason fixing the flags seems necessary */
-    if (self->view.readonly)
-        flags &= ~PyBUF_WRITABLE;
     if (self->view.obj != NULL)
         res = PyObject_GetBuffer(self->view.obj, view, flags);
     if (view)
@@ -78,6 +75,11 @@
 {
     PyMemoryViewObject *mview;
 
+    if (info->buf == NULL) {
+        PyErr_SetString(PyExc_ValueError,
+            "cannot make memory view from a buffer with a NULL data pointer");
+        return NULL;
+    }
     mview = (PyMemoryViewObject *)
         PyObject_GC_New(PyMemoryViewObject, &PyMemoryView_Type);
     if (mview == NULL)
@@ -599,7 +601,7 @@
     else if (PySlice_Check(key)) {
         Py_ssize_t start, stop, step, slicelength;
 
-        if (PySlice_GetIndicesEx((PySliceObject*)key, get_shape0(view),
+        if (PySlice_GetIndicesEx(key, get_shape0(view),
                                  &start, &stop, &step, &slicelength) < 0) {
             return NULL;
         }
@@ -678,7 +680,7 @@
     else if (PySlice_Check(key)) {
         Py_ssize_t stop, step;
 
-        if (PySlice_GetIndicesEx((PySliceObject*)key, get_shape0(view),
+        if (PySlice_GetIndicesEx(key, get_shape0(view),
                          &start, &stop, &step, &len) < 0) {
             return -1;
         }

Modified: python/branches/pep-3151/Objects/moduleobject.c
==============================================================================
--- python/branches/pep-3151/Objects/moduleobject.c	(original)
+++ python/branches/pep-3151/Objects/moduleobject.c	Sat Feb 26 08:16:32 2011
@@ -63,8 +63,9 @@
     PyMethodDef *ml;
     const char* name;
     PyModuleObject *m;
-    if (!Py_IsInitialized())
-        Py_FatalError("Interpreter not initialized (version mismatch?)");
+    PyInterpreterState *interp = PyThreadState_Get()->interp;
+    if (interp->modules == NULL)
+        Py_FatalError("Python import machinery not initialized");
     if (PyType_Ready(&moduledef_type) < 0)
         return NULL;
     if (module->m_base.m_index == 0) {
@@ -74,7 +75,7 @@
         module->m_base.m_index = max_module_number;
     }
     name = module->m_name;
-    if (module_api_version != PYTHON_API_VERSION) {
+    if (module_api_version != PYTHON_API_VERSION && module_api_version != PYTHON_ABI_VERSION) {
         int err;
         err = PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
             "Python C API version mismatch for module %.100s: "
@@ -168,24 +169,35 @@
     return d;
 }
 
-const char *
-PyModule_GetName(PyObject *m)
+PyObject*
+PyModule_GetNameObject(PyObject *m)
 {
     PyObject *d;
-    PyObject *nameobj;
+    PyObject *name;
     if (!PyModule_Check(m)) {
         PyErr_BadArgument();
         return NULL;
     }
     d = ((PyModuleObject *)m)->md_dict;
     if (d == NULL ||
-        (nameobj = PyDict_GetItemString(d, "__name__")) == NULL ||
-        !PyUnicode_Check(nameobj))
+        (name = PyDict_GetItemString(d, "__name__")) == NULL ||
+        !PyUnicode_Check(name))
     {
         PyErr_SetString(PyExc_SystemError, "nameless module");
         return NULL;
     }
-    return _PyUnicode_AsString(nameobj);
+    Py_INCREF(name);
+    return name;
+}
+
+const char *
+PyModule_GetName(PyObject *m)
+{
+    PyObject *name = PyModule_GetNameObject(m);
+    if (name == NULL)
+        return NULL;
+    Py_DECREF(name);   /* module dict has still a reference */
+    return _PyUnicode_AsString(name);
 }
 
 PyObject*
@@ -218,7 +230,7 @@
     if (fileobj == NULL)
         return NULL;
     utf8 = _PyUnicode_AsString(fileobj);
-    Py_DECREF(fileobj);
+    Py_DECREF(fileobj);   /* module dict has still a reference */
     return utf8;
 }
 
@@ -346,21 +358,25 @@
 static PyObject *
 module_repr(PyModuleObject *m)
 {
-    const char *name;
-    PyObject *filename, *repr;
+    PyObject *name, *filename, *repr;
 
-    name = PyModule_GetName((PyObject *)m);
+    name = PyModule_GetNameObject((PyObject *)m);
     if (name == NULL) {
         PyErr_Clear();
-        name = "?";
+        name = PyUnicode_FromStringAndSize("?", 1);
+        if (name == NULL)
+            return NULL;
     }
     filename = PyModule_GetFilenameObject((PyObject *)m);
     if (filename == NULL) {
         PyErr_Clear();
-        return PyUnicode_FromFormat("<module '%s' (built-in)>", name);
+        repr = PyUnicode_FromFormat("<module %R (built-in)>", name);
+    }
+    else {
+        repr = PyUnicode_FromFormat("<module %R from %R>", name, filename);
+        Py_DECREF(filename);
     }
-    repr = PyUnicode_FromFormat("<module '%s' from '%U'>", name, filename);
-    Py_DECREF(filename);
+    Py_DECREF(name);
     return repr;
 }
 

Modified: python/branches/pep-3151/Objects/object.c
==============================================================================
--- python/branches/pep-3151/Objects/object.c	(original)
+++ python/branches/pep-3151/Objects/object.c	Sat Feb 26 08:16:32 2011
@@ -2,7 +2,6 @@
 /* Generic object operations; and implementation of None (NoObject) */
 
 #include "Python.h"
-#include "sliceobject.h" /* For PyEllipsis_Type */
 #include "frameobject.h"
 
 #ifdef __cplusplus
@@ -1756,7 +1755,6 @@
 
 #endif
 
-
 /* Hack to force loading of pycapsule.o */
 PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
 
@@ -1901,6 +1899,19 @@
     }
 }
 
+#ifndef Py_TRACE_REFS
+/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
+   Define this here, so we can undefine the macro. */
+#undef _Py_Dealloc
+PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
+void
+_Py_Dealloc(PyObject *op)
+{
+    _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
+    (*Py_TYPE(op)->tp_dealloc)(op);
+}
+#endif
+
 #ifdef __cplusplus
 }
 #endif

Modified: python/branches/pep-3151/Objects/obmalloc.c
==============================================================================
--- python/branches/pep-3151/Objects/obmalloc.c	(original)
+++ python/branches/pep-3151/Objects/obmalloc.c	Sat Feb 26 08:16:32 2011
@@ -249,7 +249,7 @@
 /* Pool for small blocks. */
 struct pool_header {
     union { block *_padding;
-        uint count; } ref;              /* number of allocated blocks    */
+            uint count; } ref;          /* number of allocated blocks    */
     block *freeblock;                   /* pool's free list head         */
     struct pool_header *nextpool;       /* next pool of this size class  */
     struct pool_header *prevpool;       /* previous pool       ""        */
@@ -404,7 +404,7 @@
 immediately follow a pool_header's first two members:
 
     union { block *_padding;
-        uint count; } ref;
+            uint count; } ref;
     block *freeblock;
 
 each of which consume sizeof(block *) bytes.  So what usedpools[i+i] really
@@ -682,11 +682,19 @@
 obmalloc in a small constant time, independent of the number of arenas
 obmalloc controls.  Since this test is needed at every entry point, it's
 extremely desirable that it be this fast.
+
+Since Py_ADDRESS_IN_RANGE may be reading from memory which was not allocated
+by Python, it is important that (POOL)->arenaindex is read only once, as
+another thread may be concurrently modifying the value without holding the
+GIL.  To accomplish this, the arenaindex_temp variable is used to store
+(POOL)->arenaindex for the duration of the Py_ADDRESS_IN_RANGE macro's
+execution.  The caller of the macro is responsible for declaring this
+variable.
 */
 #define Py_ADDRESS_IN_RANGE(P, POOL)                    \
-    ((POOL)->arenaindex < maxarenas &&                  \
-     (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \
-     arenas[(POOL)->arenaindex].address != 0)
+    ((arenaindex_temp = (POOL)->arenaindex) < maxarenas &&              \
+     (uptr)(P) - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE && \
+     arenas[arenaindex_temp].address != 0)
 
 
 /* This is only useful when running memory debuggers such as
@@ -709,7 +717,7 @@
 #undef Py_ADDRESS_IN_RANGE
 
 #if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
-              (__GNUC__ >= 4))
+                          (__GNUC__ >= 4))
 #define Py_NO_INLINE __attribute__((__noinline__))
 #else
 #define Py_NO_INLINE
@@ -945,6 +953,9 @@
     block *lastfree;
     poolp next, prev;
     uint size;
+#ifndef Py_USING_MEMORY_DEBUGGER
+    uint arenaindex_temp;
+#endif
 
     if (p == NULL)      /* free(NULL) has no effect */
         return;
@@ -1167,6 +1178,9 @@
     void *bp;
     poolp pool;
     size_t size;
+#ifndef Py_USING_MEMORY_DEBUGGER
+    uint arenaindex_temp;
+#endif
 
     if (p == NULL)
         return PyObject_Malloc(nbytes);
@@ -1514,7 +1528,7 @@
     if (nbytes > original_nbytes) {
         /* growing:  mark new extra memory clean */
         memset(q + original_nbytes, CLEANBYTE,
-            nbytes - original_nbytes);
+               nbytes - original_nbytes);
     }
 
     return q;
@@ -1641,11 +1655,11 @@
         fputs("FORBIDDENBYTE, as expected.\n", stderr);
     else {
         fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
-            FORBIDDENBYTE);
+                FORBIDDENBYTE);
         for (i = 0; i < SST; ++i) {
             const uchar byte = tail[i];
             fprintf(stderr, "        at tail+%d: 0x%02x",
-                i, byte);
+                    i, byte);
             if (byte != FORBIDDENBYTE)
                 fputs(" *** OUCH", stderr);
             fputc('\n', stderr);
@@ -1751,7 +1765,7 @@
     char buf[128];
 
     fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
-        SMALL_REQUEST_THRESHOLD, numclasses);
+            SMALL_REQUEST_THRESHOLD, numclasses);
 
     for (i = 0; i < numclasses; ++i)
         numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
@@ -1761,7 +1775,6 @@
      * will be living in full pools -- would be a shame to miss them.
      */
     for (i = 0; i < maxarenas; ++i) {
-        uint poolsinarena;
         uint j;
         uptr base = arenas[i].address;
 
@@ -1770,7 +1783,6 @@
             continue;
         narenas += 1;
 
-        poolsinarena = arenas[i].ntotalpools;
         numfreepools += arenas[i].nfreepools;
 
         /* round up to pool alignment */
@@ -1809,7 +1821,7 @@
     fputc('\n', stderr);
     fputs("class   size   num pools   blocks in use  avail blocks\n"
           "-----   ----   ---------   -------------  ------------\n",
-        stderr);
+          stderr);
 
     for (i = 0; i < numclasses; ++i) {
         size_t p = numpools[i];
@@ -1824,7 +1836,7 @@
                         "%11" PY_FORMAT_SIZE_T "u "
                         "%15" PY_FORMAT_SIZE_T "u "
                         "%13" PY_FORMAT_SIZE_T "u\n",
-            i, size, p, b, f);
+                i, size, p, b, f);
         allocated_bytes += b * size;
         available_bytes += f * size;
         pool_header_bytes += p * POOL_OVERHEAD;
@@ -1867,8 +1879,10 @@
 int
 Py_ADDRESS_IN_RANGE(void *P, poolp pool)
 {
-    return pool->arenaindex < maxarenas &&
-           (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE &&
-           arenas[pool->arenaindex].address != 0;
+    uint arenaindex_temp = pool->arenaindex;
+
+    return arenaindex_temp < maxarenas &&
+           (uptr)P - arenas[arenaindex_temp].address < (uptr)ARENA_SIZE &&
+           arenas[arenaindex_temp].address != 0;
 }
 #endif

Modified: python/branches/pep-3151/Objects/rangeobject.c
==============================================================================
--- python/branches/pep-3151/Objects/rangeobject.c	(original)
+++ python/branches/pep-3151/Objects/rangeobject.c	Sat Feb 26 08:16:32 2011
@@ -14,6 +14,7 @@
     PyObject *start;
     PyObject *stop;
     PyObject *step;
+    PyObject *length;
 } rangeobject;
 
 /* Helper function for validating step.  Always returns a new reference or
@@ -43,6 +44,31 @@
     return step;
 }
 
+static PyObject *
+compute_range_length(PyObject *start, PyObject *stop, PyObject *step);
+
+static rangeobject *
+make_range_object(PyTypeObject *type, PyObject *start,
+                  PyObject *stop, PyObject *step)
+{
+    rangeobject *obj = NULL;
+    PyObject *length;
+    length = compute_range_length(start, stop, step);
+    if (length == NULL) {
+        return NULL;
+    }
+    obj = PyObject_New(rangeobject, type);
+    if (obj == NULL) {
+        Py_DECREF(length);
+        return NULL;
+    }
+    obj->start = start;
+    obj->stop = stop;
+    obj->step = step;
+    obj->length = length;
+    return obj;
+}
+
 /* XXX(nnorwitz): should we error check if the user passes any empty ranges?
    range(-10)
    range(0, -5)
@@ -51,7 +77,7 @@
 static PyObject *
 range_new(PyTypeObject *type, PyObject *args, PyObject *kw)
 {
-    rangeobject *obj = NULL;
+    rangeobject *obj;
     PyObject *start = NULL, *stop = NULL, *step = NULL;
 
     if (!_PyArg_NoKeywords("range()", kw))
@@ -97,15 +123,11 @@
         }
     }
 
-    obj = PyObject_New(rangeobject, &PyRange_Type);
-    if (obj == NULL)
-        goto Fail;
-    obj->start = start;
-    obj->stop = stop;
-    obj->step = step;
-    return (PyObject *) obj;
+    obj = make_range_object(type, start, stop, step);
+    if (obj != NULL)
+        return (PyObject *) obj;
 
-Fail:
+    /* Failed to create object, release attributes */
     Py_XDECREF(start);
     Py_XDECREF(stop);
     Py_XDECREF(step);
@@ -115,7 +137,7 @@
 PyDoc_STRVAR(range_doc,
 "range([start,] stop[, step]) -> range object\n\
 \n\
-Returns an iterator that generates the numbers in the range on demand.");
+Returns a virtual sequence of numbers from start to stop by step.");
 
 static void
 range_dealloc(rangeobject *r)
@@ -123,6 +145,7 @@
     Py_DECREF(r->start);
     Py_DECREF(r->stop);
     Py_DECREF(r->step);
+    Py_DECREF(r->length);
     PyObject_Del(r);
 }
 
@@ -131,7 +154,7 @@
  * PyLong_Check().  Return NULL when there is an error.
  */
 static PyObject*
-range_length_obj(rangeobject *r)
+compute_range_length(PyObject *start, PyObject *stop, PyObject *step)
 {
     /* -------------------------------------------------------------
     Algorithm is equal to that of get_len_of_range(), but it operates
@@ -139,7 +162,6 @@
     ---------------------------------------------------------------*/
     int cmp_result;
     PyObject *lo, *hi;
-    PyObject *step = NULL;
     PyObject *diff = NULL;
     PyObject *one = NULL;
     PyObject *tmp1 = NULL, *tmp2 = NULL, *result;
@@ -148,20 +170,19 @@
     PyObject *zero = PyLong_FromLong(0);
     if (zero == NULL)
         return NULL;
-    cmp_result = PyObject_RichCompareBool(r->step, zero, Py_GT);
+    cmp_result = PyObject_RichCompareBool(step, zero, Py_GT);
     Py_DECREF(zero);
     if (cmp_result == -1)
         return NULL;
 
     if (cmp_result == 1) {
-        lo = r->start;
-        hi = r->stop;
-        step = r->step;
+        lo = start;
+        hi = stop;
         Py_INCREF(step);
     } else {
-        lo = r->stop;
-        hi = r->start;
-        step = PyNumber_Negative(r->step);
+        lo = stop;
+        hi = start;
+        step = PyNumber_Negative(step);
         if (!step)
             return NULL;
     }
@@ -206,71 +227,325 @@
 static Py_ssize_t
 range_length(rangeobject *r)
 {
-    PyObject *len = range_length_obj(r);
-    Py_ssize_t result = -1;
-    if (len) {
-        result = PyLong_AsSsize_t(len);
-        Py_DECREF(len);
-    }
-    return result;
+    return PyLong_AsSsize_t(r->length);
 }
 
-/* range(...)[x] is necessary for:  seq[:] = range(...) */
+static PyObject *
+compute_item(rangeobject *r, PyObject *i)
+{
+    PyObject *incr, *result;
+    /* PyLong equivalent to:
+     *    return r->start + (i * r->step)
+     */
+    incr = PyNumber_Multiply(i, r->step);
+    if (!incr)
+        return NULL;
+    result = PyNumber_Add(r->start, incr);
+    Py_DECREF(incr);
+    return result;
+}
 
 static PyObject *
-range_item(rangeobject *r, Py_ssize_t i)
+compute_range_item(rangeobject *r, PyObject *arg)
 {
-    Py_ssize_t len = range_length(r);
-    PyObject *rem, *incr, *result;
+    int cmp_result;
+    PyObject *i, *result;
 
-    /* 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,
-                            "range object index out of range");
+    PyObject *zero = PyLong_FromLong(0);
+    if (zero == NULL)
         return NULL;
-    }
 
-    /* XXX(nnorwitz): optimize for short ints. */
-    rem = PyLong_FromSsize_t(i);
-    if (!rem)
+    /* PyLong equivalent to:
+     *   if (arg < 0) {
+     *     i = r->length + arg
+     *   } else {
+     *     i = arg
+     *   }
+     */
+    cmp_result = PyObject_RichCompareBool(arg, zero, Py_LT);
+    if (cmp_result == -1) {
+        Py_DECREF(zero);
         return NULL;
-    incr = PyNumber_Multiply(rem, r->step);
-    Py_DECREF(rem);
-    if (!incr)
+    }
+    if (cmp_result == 1) {
+      i = PyNumber_Add(r->length, arg);
+      if (!i) {
+        Py_DECREF(zero);
         return NULL;
-    result = PyNumber_Add(r->start, incr);
-    Py_DECREF(incr);
+      }
+    } else {
+      i = arg;
+      Py_INCREF(i);
+    }
+
+    /* PyLong equivalent to:
+     *   if (i < 0 || i >= r->length) {
+     *     <report index out of bounds>
+     *   }
+     */
+    cmp_result = PyObject_RichCompareBool(i, zero, Py_LT);
+    Py_DECREF(zero);
+    if (cmp_result == 0) {
+        cmp_result = PyObject_RichCompareBool(i, r->length, Py_GE);
+    }
+    if (cmp_result == -1) {
+       Py_DECREF(i);
+       return NULL;
+    }
+    if (cmp_result == 1) {
+        Py_DECREF(i);
+        PyErr_SetString(PyExc_IndexError,
+                        "range object index out of range");
+        return NULL;
+    }
+
+    result = compute_item(r, i);
+    Py_DECREF(i);
     return result;
 }
 
 static PyObject *
-range_repr(rangeobject *r)
+range_item(rangeobject *r, Py_ssize_t i)
 {
-    Py_ssize_t istep;
+    PyObject *res, *arg = PyLong_FromLong(i);
+    if (!arg) {
+        return NULL;
+    }
+    res = compute_range_item(r, arg);
+    Py_DECREF(arg);
+    return res;
+}
 
-    /* Check for special case values for printing.  We don't always
-       need the step value.  We don't care about errors
-       (it means overflow), so clear the errors. */
-    istep = PyNumber_AsSsize_t(r->step, NULL);
-    if (istep != 1 || (istep == -1 && PyErr_Occurred())) {
-        PyErr_Clear();
+/* Additional helpers, since the standard slice helpers
+ * all clip to PY_SSIZE_T_MAX
+ */
+
+/* Replace _PyEval_SliceIndex */
+static PyObject *
+compute_slice_element(PyObject *obj)
+{
+    PyObject *result = NULL;
+    if (obj != NULL) {
+        if (PyIndex_Check(obj)) {
+            result = PyNumber_Index(obj);
+        }
+    }
+    if (result == NULL) {
+        PyErr_SetString(PyExc_TypeError,
+                        "slice indices must be integers or "
+                        "None or have an __index__ method");
     }
+    return result;
+}
 
-    if (istep == 1)
-        return PyUnicode_FromFormat("range(%R, %R)", r->start, r->stop);
-    else
-        return PyUnicode_FromFormat("range(%R, %R, %R)",
-                                    r->start, r->stop, r->step);
+/* Replace PySlice_GetIndicesEx
+ *   Result indicates whether or not the slice is empty
+ *    (-1 = error, 0 = empty slice, 1 = slice contains elements)
+ */
+static int
+compute_slice_indices(rangeobject *r, PySliceObject *slice,
+                      PyObject **start, PyObject **stop, PyObject **step)
+{
+    int cmp_result, has_elements;
+    Py_ssize_t clamped_step = 0;
+    PyObject *zero = NULL, *one = NULL, *neg_one = NULL, *candidate = NULL;
+    PyObject *tmp_start = NULL, *tmp_stop = NULL, *tmp_step = NULL;
+    zero = PyLong_FromLong(0);
+    if (zero == NULL) goto Fail;
+    one = PyLong_FromLong(1);
+    if (one == NULL) goto Fail;
+    neg_one = PyLong_FromLong(-1);
+    if (neg_one == NULL) goto Fail;
+
+    /* Calculate step value */
+    if (slice->step == Py_None) {
+        clamped_step = 1;
+        tmp_step = one;
+        Py_INCREF(tmp_step);
+    } else {
+        if (!_PyEval_SliceIndex(slice->step, &clamped_step)) goto Fail;
+        if (clamped_step == 0) {
+            PyErr_SetString(PyExc_ValueError,
+                            "slice step cannot be zero");
+            goto Fail;
+        }
+        tmp_step = compute_slice_element(slice->step);
+        if (tmp_step == NULL) goto Fail;
+    }
+
+    /* Calculate start value */
+    if (slice->start == Py_None) {
+        if (clamped_step < 0) {
+            tmp_start = PyNumber_Subtract(r->length, one);
+            if (tmp_start == NULL) goto Fail;
+        } else {
+            tmp_start = zero;
+            Py_INCREF(tmp_start);
+        }
+    } else {
+        candidate = compute_slice_element(slice->start);
+        if (candidate == NULL) goto Fail;
+        cmp_result = PyObject_RichCompareBool(candidate, zero, Py_LT);
+        if (cmp_result == -1) goto Fail;
+        if (cmp_result) {
+            /* candidate < 0 */
+            tmp_start = PyNumber_Add(r->length, candidate);
+            if (tmp_start == NULL) goto Fail;
+            Py_CLEAR(candidate);
+        } else {
+            /* candidate >= 0 */
+            tmp_start = candidate;
+            candidate = NULL;
+        }
+        cmp_result = PyObject_RichCompareBool(tmp_start, zero, Py_LT);
+        if (cmp_result == -1) goto Fail;
+        if (cmp_result) {
+            /* tmp_start < 0 */
+            Py_CLEAR(tmp_start);
+            if (clamped_step < 0) {
+                tmp_start = neg_one;
+            } else {
+                tmp_start = zero;
+            }
+            Py_INCREF(tmp_start);
+        } else {
+            /* tmp_start >= 0 */
+            cmp_result = PyObject_RichCompareBool(tmp_start, r->length, Py_GE);
+            if (cmp_result == -1) goto Fail;
+            if (cmp_result) {
+                /* tmp_start >= r->length */
+                Py_CLEAR(tmp_start);
+                if (clamped_step < 0) {
+                    tmp_start = PyNumber_Subtract(r->length, one);
+                    if (tmp_start == NULL) goto Fail;
+                } else {
+                    tmp_start = r->length;
+                    Py_INCREF(tmp_start);
+                }
+            }
+        }
+    }
+
+    /* Calculate stop value */
+    if (slice->stop == Py_None) {
+        if (clamped_step < 0) {
+            tmp_stop = neg_one;
+        } else {
+            tmp_stop = r->length;
+        }
+        Py_INCREF(tmp_stop);
+    } else {
+        candidate = compute_slice_element(slice->stop);
+        if (candidate == NULL) goto Fail;
+        cmp_result = PyObject_RichCompareBool(candidate, zero, Py_LT);
+        if (cmp_result == -1) goto Fail;
+        if (cmp_result) {
+            /* candidate < 0 */
+            tmp_stop = PyNumber_Add(r->length, candidate);
+            if (tmp_stop == NULL) goto Fail;
+            Py_CLEAR(candidate);
+        } else {
+            /* candidate >= 0 */
+            tmp_stop = candidate;
+            candidate = NULL;
+        }
+        cmp_result = PyObject_RichCompareBool(tmp_stop, zero, Py_LT);
+        if (cmp_result == -1) goto Fail;
+        if (cmp_result) {
+            /* tmp_stop < 0 */
+            Py_CLEAR(tmp_stop);
+            if (clamped_step < 0) {
+                tmp_stop = neg_one;
+            } else {
+                tmp_stop = zero;
+            }
+            Py_INCREF(tmp_stop);
+        } else {
+            /* tmp_stop >= 0 */
+            cmp_result = PyObject_RichCompareBool(tmp_stop, r->length, Py_GE);
+            if (cmp_result == -1) goto Fail;
+            if (cmp_result) {
+                /* tmp_stop >= r->length */
+                Py_CLEAR(tmp_stop);
+                if (clamped_step < 0) {
+                    tmp_stop = PyNumber_Subtract(r->length, one);
+                    if (tmp_stop == NULL) goto Fail;
+                } else {
+                    tmp_stop = r->length;
+                    Py_INCREF(tmp_start);
+                }
+            }
+        }
+    }
+
+    /* Check if the slice is empty or not */
+    if (clamped_step < 0) {
+        has_elements = PyObject_RichCompareBool(tmp_start, tmp_stop, Py_GT);
+    } else {
+        has_elements = PyObject_RichCompareBool(tmp_start, tmp_stop, Py_LT);
+    }
+    if (has_elements == -1) goto Fail;
+
+    *start = tmp_start;
+    *stop = tmp_stop;
+    *step = tmp_step;
+    Py_DECREF(neg_one);
+    Py_DECREF(one);
+    Py_DECREF(zero);
+    return has_elements;
+
+  Fail:
+    Py_XDECREF(tmp_start);
+    Py_XDECREF(tmp_stop);
+    Py_XDECREF(tmp_step);
+    Py_XDECREF(candidate);
+    Py_XDECREF(neg_one);
+    Py_XDECREF(one);
+    Py_XDECREF(zero);
+    return -1;
 }
 
-/* Pickling support */
 static PyObject *
-range_reduce(rangeobject *r, PyObject *args)
+compute_slice(rangeobject *r, PyObject *_slice)
 {
-        return Py_BuildValue("(O(OOO))", Py_TYPE(r),
-                         r->start, r->stop, r->step);
+    PySliceObject *slice = (PySliceObject *) _slice;
+    rangeobject *result;
+    PyObject *start = NULL, *stop = NULL, *step = NULL;
+    PyObject *substart = NULL, *substop = NULL, *substep = NULL;
+    int has_elements;
+
+    has_elements = compute_slice_indices(r, slice, &start, &stop, &step);
+    if (has_elements == -1) return NULL;
+
+    substep = PyNumber_Multiply(r->step, step);
+    if (substep == NULL) goto fail;
+    Py_CLEAR(step);
+
+    substart = compute_item(r, start);
+    if (substart == NULL) goto fail;
+    Py_CLEAR(start);
+
+    if (has_elements) {
+        substop = compute_item(r, stop);
+        if (substop == NULL) goto fail;
+    } else {
+        substop = substart;
+        Py_INCREF(substop);
+    }
+    Py_CLEAR(stop);
+
+    result = make_range_object(Py_TYPE(r), substart, substop, substep);
+    if (result != NULL) {
+        return (PyObject *) result;
+    }
+fail:
+    Py_XDECREF(start);
+    Py_XDECREF(stop);
+    Py_XDECREF(step);
+    Py_XDECREF(substart);
+    Py_XDECREF(substop);
+    Py_XDECREF(substep);
+    return NULL;
 }
 
 /* Assumes (PyLong_CheckExact(ob) || PyBool_Check(ob)) */
@@ -325,7 +600,8 @@
 }
 
 static int
-range_contains(rangeobject *r, PyObject *ob) {
+range_contains(rangeobject *r, PyObject *ob)
+{
     if (PyLong_CheckExact(ob) || PyBool_Check(ob))
         return range_contains_long(r, ob);
 
@@ -337,10 +613,13 @@
 range_count(rangeobject *r, PyObject *ob)
 {
     if (PyLong_CheckExact(ob) || PyBool_Check(ob)) {
-        if (range_contains_long(r, ob))
-            Py_RETURN_TRUE;
+        int result = range_contains_long(r, ob);
+        if (result == -1)
+            return NULL;
+        else if (result)
+            return PyLong_FromLong(1);
         else
-            Py_RETURN_FALSE;
+            return PyLong_FromLong(0);
     } else {
         Py_ssize_t count;
         count = _PySequence_IterSearch((PyObject*)r, ob, PY_ITERSEARCH_COUNT);
@@ -353,10 +632,7 @@
 static PyObject *
 range_index(rangeobject *r, PyObject *ob)
 {
-    PyObject *idx, *tmp;
     int contains;
-    PyObject *format_tuple, *err_string;
-    static PyObject *err_format = NULL;
 
     if (!PyLong_CheckExact(ob) && !PyBool_Check(ob)) {
         Py_ssize_t index;
@@ -370,49 +646,88 @@
     if (contains == -1)
         return NULL;
 
-    if (!contains)
-        goto value_error;
-
-    tmp = PyNumber_Subtract(ob, r->start);
-    if (tmp == NULL)
-        return NULL;
-
-    /* idx = (ob - r.start) // r.step */
-    idx = PyNumber_FloorDivide(tmp, r->step);
-    Py_DECREF(tmp);
-    return idx;
-
-value_error:
-
-    /* object is not in the range */
-    if (err_format == NULL) {
-        err_format = PyUnicode_FromString("%r is not in range");
-        if (err_format == NULL)
+    if (contains) {
+        PyObject *idx, *tmp = PyNumber_Subtract(ob, r->start);
+        if (tmp == NULL)
             return NULL;
+        /* idx = (ob - r.start) // r.step */
+        idx = PyNumber_FloorDivide(tmp, r->step);
+        Py_DECREF(tmp);
+        return idx;
     }
-    format_tuple = PyTuple_Pack(1, ob);
-    if (format_tuple == NULL)
-        return NULL;
-    err_string = PyUnicode_Format(err_format, format_tuple);
-    Py_DECREF(format_tuple);
-    if (err_string == NULL)
-        return NULL;
-    PyErr_SetObject(PyExc_ValueError, err_string);
-    Py_DECREF(err_string);
+
+    /* object is not in the range */
+    PyErr_Format(PyExc_ValueError, "%R is not in range", ob);
     return NULL;
 }
 
 static PySequenceMethods range_as_sequence = {
     (lenfunc)range_length,      /* sq_length */
-    0,                  /* sq_concat */
-    0,                  /* sq_repeat */
-    (ssizeargfunc)range_item, /* sq_item */
-    0,                  /* sq_slice */
-    0, /* sq_ass_item */
-    0, /* sq_ass_slice */
+    0,                          /* sq_concat */
+    0,                          /* sq_repeat */
+    (ssizeargfunc)range_item,   /* sq_item */
+    0,                          /* sq_slice */
+    0,                          /* sq_ass_item */
+    0,                          /* sq_ass_slice */
     (objobjproc)range_contains, /* sq_contains */
 };
 
+static PyObject *
+range_repr(rangeobject *r)
+{
+    Py_ssize_t istep;
+
+    /* Check for special case values for printing.  We don't always
+       need the step value.  We don't care about errors
+       (it means overflow), so clear the errors. */
+    istep = PyNumber_AsSsize_t(r->step, NULL);
+    if (istep != 1 || (istep == -1 && PyErr_Occurred())) {
+        PyErr_Clear();
+    }
+
+    if (istep == 1)
+        return PyUnicode_FromFormat("range(%R, %R)", r->start, r->stop);
+    else
+        return PyUnicode_FromFormat("range(%R, %R, %R)",
+                                    r->start, r->stop, r->step);
+}
+
+/* Pickling support */
+static PyObject *
+range_reduce(rangeobject *r, PyObject *args)
+{
+    return Py_BuildValue("(O(OOO))", Py_TYPE(r),
+                         r->start, r->stop, r->step);
+}
+
+static PyObject *
+range_subscript(rangeobject* self, PyObject* item)
+{
+    if (PyIndex_Check(item)) {
+        PyObject *i, *result;
+        i = PyNumber_Index(item);
+        if (!i)
+            return NULL;
+        result = compute_range_item(self, i);
+        Py_DECREF(i);
+        return result;
+    }
+    if (PySlice_Check(item)) {
+        return compute_slice(self, item);
+    }
+    PyErr_Format(PyExc_TypeError,
+                 "range indices must be integers or slices, not %.200s",
+                 item->ob_type->tp_name);
+    return NULL;
+}
+
+
+static PyMappingMethods range_as_mapping = {
+        (lenfunc)range_length,       /* mp_length */
+        (binaryfunc)range_subscript, /* mp_subscript */
+        (objobjargproc)0,            /* mp_ass_subscript */
+};
+
 static PyObject * range_iter(PyObject *seq);
 static PyObject * range_reverse(PyObject *seq);
 
@@ -447,7 +762,7 @@
         (reprfunc)range_repr,   /* tp_repr */
         0,                      /* tp_as_number */
         &range_as_sequence,     /* tp_as_sequence */
-        0,                      /* tp_as_mapping */
+        &range_as_mapping,      /* tp_as_mapping */
         0,                      /* tp_hash */
         0,                      /* tp_call */
         0,                      /* tp_str */
@@ -507,22 +822,6 @@
     return PyLong_FromLong(r->len - r->index);
 }
 
-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)).");
 
@@ -532,6 +831,8 @@
     {NULL,              NULL}           /* sentinel */
 };
 
+static PyObject *rangeiter_new(PyTypeObject *, PyObject *args, PyObject *kw);
+
 PyTypeObject PyRangeIter_Type = {
         PyVarObject_HEAD_INIT(&PyType_Type, 0)
         "range_iterator",                        /* tp_name */
@@ -606,7 +907,7 @@
    is not representable as a C long, OverflowError is raised. */
 
 static PyObject *
-int_range_iter(long start, long stop, long step)
+fast_range_iter(long start, long stop, long step)
 {
     rangeiterobject *it = PyObject_New(rangeiterobject, &PyRangeIter_Type);
     unsigned long ulen;
@@ -638,7 +939,21 @@
                           &start, &stop, &step))
         return NULL;
 
-    return int_range_iter(start, stop, step);
+    return fast_range_iter(start, stop, step);
+}
+
+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 PyMethodDef longrangeiter_methods[] = {
@@ -752,7 +1067,7 @@
         PyErr_Clear();
         goto long_range;
     }
-    int_it = int_range_iter(lstart, lstop, lstep);
+    int_it = fast_range_iter(lstart, lstop, lstep);
     if (int_it == NULL && PyErr_ExceptionMatches(PyExc_OverflowError)) {
         PyErr_Clear();
         goto long_range;
@@ -767,14 +1082,11 @@
     /* Do all initialization here, so we can DECREF on failure. */
     it->start = r->start;
     it->step = r->step;
+    it->len = r->length;
     Py_INCREF(it->start);
     Py_INCREF(it->step);
+    Py_INCREF(it->len);
 
-    it->len = it->index = NULL;
-
-    it->len = range_length_obj(r);
-    if (!it->len)
-        goto create_failure;
     it->index = PyLong_FromLong(0);
     if (!it->index)
         goto create_failure;
@@ -791,7 +1103,7 @@
 {
     rangeobject *range = (rangeobject*) seq;
     longrangeiterobject *it;
-    PyObject *one, *sum, *diff, *len = NULL, *product;
+    PyObject *one, *sum, *diff, *product;
     long lstart, lstop, lstep, new_start, new_stop;
     unsigned long ulen;
 
@@ -854,7 +1166,7 @@
 
     new_stop = lstart - lstep;
     new_start = (long)(new_stop + ulen * lstep);
-    return int_range_iter(new_start, new_stop, -lstep);
+    return fast_range_iter(new_start, new_stop, -lstep);
 
 long_range:
     it = PyObject_New(longrangeiterobject, &PyLongRangeIter_Type);
@@ -862,18 +1174,14 @@
         return NULL;
 
     /* start + (len - 1) * step */
-    len = range_length_obj(range);
-    if (!len)
-        goto create_failure;
-
-    /* Steal reference to len. */
-    it->len = len;
+    it->len = range->length;
+    Py_INCREF(it->len);
 
     one = PyLong_FromLong(1);
     if (!one)
         goto create_failure;
 
-    diff = PyNumber_Subtract(len, one);
+    diff = PyNumber_Subtract(it->len, one);
     Py_DECREF(one);
     if (!diff)
         goto create_failure;

Modified: python/branches/pep-3151/Objects/setobject.c
==============================================================================
--- python/branches/pep-3151/Objects/setobject.c	(original)
+++ python/branches/pep-3151/Objects/setobject.c	Sat Feb 26 08:16:32 2011
@@ -1525,6 +1525,20 @@
 "Remove all elements of another set from this set.");
 
 static PyObject *
+set_copy_and_difference(PySetObject *so, PyObject *other)
+{
+    PyObject *result;
+
+    result = set_copy(so);
+    if (result == NULL)
+        return NULL;
+    if (set_difference_update_internal((PySetObject *) result, other) != -1)
+        return result;
+    Py_DECREF(result);
+    return NULL;
+}
+
+static PyObject *
 set_difference(PySetObject *so, PyObject *other)
 {
     PyObject *result;
@@ -1532,13 +1546,13 @@
     Py_ssize_t pos = 0;
 
     if (!PyAnySet_Check(other)  && !PyDict_CheckExact(other)) {
-        result = set_copy(so);
-        if (result == NULL)
-            return NULL;
-        if (set_difference_update_internal((PySetObject *)result, other) != -1)
-            return result;
-        Py_DECREF(result);
-        return NULL;
+        return set_copy_and_difference(so, other);
+    }
+
+    /* If len(so) much more than len(other), it's more efficient to simply copy
+     * so and then iterate other looking for common elements. */
+    if ((PySet_GET_SIZE(so) >> 2) > PyObject_Size(other)) {
+        return set_copy_and_difference(so, other);
     }
 
     result = make_new_set_basetype(Py_TYPE(so), NULL);
@@ -1560,6 +1574,7 @@
         return result;
     }
 
+    /* Iterate over so, checking for common elements in other. */
     while (set_next(so, &pos, &entry)) {
         int rv = set_contains_entry((PySetObject *)other, entry);
         if (rv == -1) {

Modified: python/branches/pep-3151/Objects/sliceobject.c
==============================================================================
--- python/branches/pep-3151/Objects/sliceobject.c	(original)
+++ python/branches/pep-3151/Objects/sliceobject.c	Sat Feb 26 08:16:32 2011
@@ -99,9 +99,10 @@
 }
 
 int
-PySlice_GetIndices(PySliceObject *r, Py_ssize_t length,
+PySlice_GetIndices(PyObject *_r, Py_ssize_t length,
                    Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
 {
+    PySliceObject *r = (PySliceObject*)_r;
     /* XXX support long ints */
     if (r->step == Py_None) {
         *step = 1;
@@ -130,10 +131,11 @@
 }
 
 int
-PySlice_GetIndicesEx(PySliceObject *r, Py_ssize_t length,
+PySlice_GetIndicesEx(PyObject *_r, Py_ssize_t length,
                      Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step,
                      Py_ssize_t *slicelength)
 {
+    PySliceObject *r = (PySliceObject*)_r;
     /* this is harder to get right than you might think */
 
     Py_ssize_t defstart, defstop;
@@ -256,7 +258,7 @@
         return NULL;
     }
 
-    if (PySlice_GetIndicesEx(self, ilen, &start, &stop,
+    if (PySlice_GetIndicesEx((PyObject*)self, ilen, &start, &stop,
                              &step, &slicelength) < 0) {
         return NULL;
     }

Modified: python/branches/pep-3151/Objects/stringlib/formatter.h
==============================================================================
--- python/branches/pep-3151/Objects/stringlib/formatter.h	(original)
+++ python/branches/pep-3151/Objects/stringlib/formatter.h	Sat Feb 26 08:16:32 2011
@@ -941,13 +941,8 @@
        from a hard-code pseudo-locale */
     LocaleInfo locale;
 
-    /* Alternate is not allowed on floats. */
-    if (format->alternate) {
-        PyErr_SetString(PyExc_ValueError,
-                        "Alternate form (#) not allowed in float format "
-                        "specifier");
-        goto done;
-    }
+    if (format->alternate)
+        flags |= Py_DTSF_ALT;
 
     if (type == '\0') {
         /* Omitted type specifier.  Behaves in the same way as repr(x)
@@ -1104,15 +1099,7 @@
        from a hard-code pseudo-locale */
     LocaleInfo locale;
 
-    /* Alternate is not allowed on complex. */
-    if (format->alternate) {
-        PyErr_SetString(PyExc_ValueError,
-                        "Alternate form (#) not allowed in complex format "
-                        "specifier");
-        goto done;
-    }
-
-    /* Neither is zero pading. */
+    /* Zero padding is not allowed. */
     if (format->fill_char == '0') {
         PyErr_SetString(PyExc_ValueError,
                         "Zero padding is not allowed in complex format "
@@ -1135,6 +1122,9 @@
     if (im == -1.0 && PyErr_Occurred())
         goto done;
 
+    if (format->alternate)
+        flags |= Py_DTSF_ALT;
+
     if (type == '\0') {
         /* Omitted type specifier. Should be like str(self). */
         type = 'r';

Modified: python/branches/pep-3151/Objects/stringlib/string_format.h
==============================================================================
--- python/branches/pep-3151/Objects/stringlib/string_format.h	(original)
+++ python/branches/pep-3151/Objects/stringlib/string_format.h	Sat Feb 26 08:16:32 2011
@@ -1192,6 +1192,11 @@
 {
     formatteriterobject *it;
 
+    if (!PyUnicode_Check(self)) {
+        PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name);
+        return NULL;
+    }
+
     it = PyObject_New(formatteriterobject, &PyFormatterIter_Type);
     if (it == NULL)
         return NULL;
@@ -1332,6 +1337,11 @@
     PyObject *first_obj = NULL;
     PyObject *result = NULL;
 
+    if (!PyUnicode_Check(self)) {
+        PyErr_Format(PyExc_TypeError, "expected str, got %s", Py_TYPE(self)->tp_name);
+        return NULL;
+    }
+
     it = PyObject_New(fieldnameiterobject, &PyFieldNameIter_Type);
     if (it == NULL)
         return NULL;

Modified: python/branches/pep-3151/Objects/structseq.c
==============================================================================
--- python/branches/pep-3151/Objects/structseq.c	(original)
+++ python/branches/pep-3151/Objects/structseq.c	Sat Feb 26 08:16:32 2011
@@ -3,7 +3,6 @@
 
 #include "Python.h"
 #include "structmember.h"
-#include "structseq.h"
 
 static char visible_length_key[] = "n_sequence_fields";
 static char real_length_key[] = "n_fields";
@@ -44,6 +43,18 @@
     return (PyObject*)obj;
 }
 
+void
+PyStructSequence_SetItem(PyObject* op, Py_ssize_t i, PyObject* v)
+{
+    PyStructSequence_SET_ITEM(op, i, v);
+}
+
+PyObject*
+PyStructSequence_GetItem(PyObject* op, Py_ssize_t i)
+{
+    return PyStructSequence_GET_ITEM(op, i);
+}
+
 static void
 structseq_dealloc(PyStructSequence *obj)
 {
@@ -366,3 +377,11 @@
     SET_DICT_FROM_INT(real_length_key, n_members);
     SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members);
 }
+
+PyTypeObject*
+PyStructSequence_NewType(PyStructSequence_Desc *desc)
+{
+    PyTypeObject *result = (PyTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
+    PyStructSequence_InitType(result, desc);
+    return result;
+}

Modified: python/branches/pep-3151/Objects/tupleobject.c
==============================================================================
--- python/branches/pep-3151/Objects/tupleobject.c	(original)
+++ python/branches/pep-3151/Objects/tupleobject.c	Sat Feb 26 08:16:32 2011
@@ -86,7 +86,7 @@
         {
             return PyErr_NoMemory();
         }
-        nbytes += sizeof(PyTupleObject) - sizeof(PyObject *);
+        /* nbytes += sizeof(PyTupleObject) - sizeof(PyObject *); */
 
         op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size);
         if (op == NULL)
@@ -689,7 +689,7 @@
         PyObject* it;
         PyObject **src, **dest;
 
-        if (PySlice_GetIndicesEx((PySliceObject*)item,
+        if (PySlice_GetIndicesEx(item,
                          PyTuple_GET_SIZE(self),
                          &start, &stop, &step, &slicelength) < 0) {
             return NULL;

Modified: python/branches/pep-3151/Objects/typeobject.c
==============================================================================
--- python/branches/pep-3151/Objects/typeobject.c	(original)
+++ python/branches/pep-3151/Objects/typeobject.c	Sat Feb 26 08:16:32 2011
@@ -326,7 +326,7 @@
     if (type != &PyType_Type)
         mod = PyDict_GetItemString(type->tp_dict, "__abstractmethods__");
     if (!mod) {
-        PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
+        PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
         return NULL;
     }
     Py_XINCREF(mod);
@@ -340,8 +340,17 @@
        abc.ABCMeta.__new__, so this function doesn't do anything
        special to update subclasses.
     */
-    int res = PyDict_SetItemString(type->tp_dict,
-                                   "__abstractmethods__", value);
+    int res;
+    if (value != NULL) {
+        res = PyDict_SetItemString(type->tp_dict, "__abstractmethods__", value);
+    }
+    else {
+        res = PyDict_DelItemString(type->tp_dict, "__abstractmethods__");
+        if (res && PyErr_ExceptionMatches(PyExc_KeyError)) {
+            PyErr_SetString(PyExc_AttributeError, "__abstractmethods__");
+            return -1;
+        }
+    }
     if (res == 0) {
         PyType_Modified(type);
         if (value && PyObject_IsTrue(value)) {
@@ -893,7 +902,7 @@
 
     /* Find the nearest base with a different tp_dealloc */
     base = type;
-    while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
+    while ((/*basedealloc =*/ base->tp_dealloc) == subtype_dealloc) {
         base = base->tp_base;
         assert(base);
     }
@@ -1895,6 +1904,12 @@
     return res;
 }
 
+long
+PyType_GetFlags(PyTypeObject *type)
+{
+    return type->tp_flags;
+}
+
 static PyObject *
 type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
 {
@@ -2304,6 +2319,57 @@
     return (PyObject *)type;
 }
 
+static short slotoffsets[] = {
+    -1, /* invalid slot */
+#include "typeslots.inc"
+};
+
+PyObject* PyType_FromSpec(PyType_Spec *spec)
+{
+    PyHeapTypeObject *res = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);
+    char *res_start = (char*)res;
+    PyType_Slot *slot;
+
+    if (res == NULL)
+      return NULL;
+    res->ht_name = PyUnicode_FromString(spec->name);
+    if (!res->ht_name)
+	goto fail;
+    res->ht_type.tp_name = _PyUnicode_AsString(res->ht_name);
+    if (!res->ht_type.tp_name)
+	goto fail;
+
+    res->ht_type.tp_basicsize = spec->basicsize;
+    res->ht_type.tp_itemsize = spec->itemsize;
+    res->ht_type.tp_flags = spec->flags | Py_TPFLAGS_HEAPTYPE;
+
+    for (slot = spec->slots; slot->slot; slot++) {
+	if (slot->slot >= sizeof(slotoffsets)/sizeof(slotoffsets[0])) {
+	    PyErr_SetString(PyExc_RuntimeError, "invalid slot offset");
+	    goto fail;
+	}
+	*(void**)(res_start + slotoffsets[slot->slot]) = slot->pfunc;
+
+        /* need to make a copy of the docstring slot, which usually
+           points to a static string literal */
+        if (slot->slot == Py_tp_doc) {
+            ssize_t len = strlen(slot->pfunc)+1;
+            char *tp_doc = PyObject_MALLOC(len);
+            if (tp_doc == NULL)
+	    	goto fail;
+            memcpy(tp_doc, slot->pfunc, len);
+            res->ht_type.tp_doc = tp_doc;
+        }
+    }
+
+    return (PyObject*)res;
+
+ fail:
+    Py_DECREF(res);
+    return NULL;
+}
+
+
 /* Internal API to look for a name through the MRO.
    This returns a borrowed reference, and doesn't set an exception! */
 PyObject *
@@ -2898,10 +2964,7 @@
     Py_ssize_t size;
     PyObject *slots_a, *slots_b;
 
-    if (base != b->tp_base)
-        return 0;
-    if (equiv_structs(a, base) && equiv_structs(b, base))
-        return 1;
+    assert(base == b->tp_base);
     size = base->tp_basicsize;
     if (a->tp_dictoffset == size && b->tp_dictoffset == size)
         size += sizeof(PyObject *);
@@ -6164,7 +6227,7 @@
            and first local variable on the stack. */
         PyFrameObject *f = PyThreadState_GET()->frame;
         PyCodeObject *co = f->f_code;
-        int i, n;
+        Py_ssize_t i, n;
         if (co == NULL) {
             PyErr_SetString(PyExc_SystemError,
                             "super(): no code object");

Modified: python/branches/pep-3151/Objects/unicodectype.c
==============================================================================
--- python/branches/pep-3151/Objects/unicodectype.c	(original)
+++ python/branches/pep-3151/Objects/unicodectype.c	Sat Feb 26 08:16:32 2011
@@ -9,7 +9,6 @@
 */
 
 #include "Python.h"
-#include "unicodeobject.h"
 
 #define ALPHA_MASK 0x01
 #define DECIMAL_MASK 0x02

Modified: python/branches/pep-3151/Objects/unicodeobject.c
==============================================================================
--- python/branches/pep-3151/Objects/unicodeobject.c	(original)
+++ python/branches/pep-3151/Objects/unicodeobject.c	Sat Feb 26 08:16:32 2011
@@ -41,9 +41,6 @@
 
 #define PY_SSIZE_T_CLEAN
 #include "Python.h"
-#include "bytes_methods.h"
-
-#include "unicodeobject.h"
 #include "ucnhash.h"
 
 #ifdef MS_WINDOWS
@@ -145,16 +142,18 @@
     0, 0, 0, 0, 0, 0, 0, 0
 };
 
-static PyObject *unicode_encode_call_errorhandler(const char *errors,
+static PyObject *
+unicode_encode_call_errorhandler(const char *errors,
        PyObject **errorHandler,const char *encoding, const char *reason,
        const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
        Py_ssize_t startpos, Py_ssize_t endpos, Py_ssize_t *newpos);
 
-static void raise_encode_exception(PyObject **exceptionObject,
-                                   const char *encoding,
-                                   const Py_UNICODE *unicode, Py_ssize_t size,
-                                   Py_ssize_t startpos, Py_ssize_t endpos,
-                                   const char *reason);
+static void
+raise_encode_exception(PyObject **exceptionObject,
+		       const char *encoding,
+		       const Py_UNICODE *unicode, Py_ssize_t size,
+		       Py_ssize_t startpos, Py_ssize_t endpos,
+		       const char *reason);
 
 /* Same for linebreaks */
 static unsigned char ascii_linebreak[] = {
@@ -226,7 +225,8 @@
     ((ch) < 128U ? ascii_linebreak[(ch)] :                              \
      (BLOOM(bloom_linebreak, (ch)) && Py_UNICODE_ISLINEBREAK(ch)))
 
-Py_LOCAL_INLINE(BLOOM_MASK) make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
+Py_LOCAL_INLINE(BLOOM_MASK)
+make_bloom_mask(Py_UNICODE* ptr, Py_ssize_t len)
 {
     /* calculate simple bloom-style bitmask for a given unicode string */
 
@@ -240,7 +240,8 @@
     return mask;
 }
 
-Py_LOCAL_INLINE(int) unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
+Py_LOCAL_INLINE(int)
+unicode_member(Py_UNICODE chr, Py_UNICODE* set, Py_ssize_t setlen)
 {
     Py_ssize_t i;
 
@@ -256,9 +257,9 @@
 
 /* --- Unicode Object ----------------------------------------------------- */
 
-static
-int unicode_resize(register PyUnicodeObject *unicode,
-                   Py_ssize_t length)
+static int
+unicode_resize(register PyUnicodeObject *unicode,
+	       Py_ssize_t length)
 {
     void *oldstr;
 
@@ -314,8 +315,8 @@
 
 */
 
-static
-PyUnicodeObject *_PyUnicode_New(Py_ssize_t length)
+static PyUnicodeObject *
+_PyUnicode_New(Py_ssize_t length)
 {
     register PyUnicodeObject *unicode;
 
@@ -386,8 +387,8 @@
     return NULL;
 }
 
-static
-void unicode_dealloc(register PyUnicodeObject *unicode)
+static void
+unicode_dealloc(register PyUnicodeObject *unicode)
 {
     switch (PyUnicode_CHECK_INTERNED(unicode)) {
     case SSTATE_NOT_INTERNED:
@@ -431,8 +432,8 @@
     }
 }
 
-static
-int _PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
+static int
+_PyUnicode_Resize(PyUnicodeObject **unicode, Py_ssize_t length)
 {
     register PyUnicodeObject *v;
 
@@ -467,13 +468,14 @@
     return unicode_resize(v, length);
 }
 
-int PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
+int
+PyUnicode_Resize(PyObject **unicode, Py_ssize_t length)
 {
     return _PyUnicode_Resize((PyUnicodeObject **)unicode, length);
 }
 
-PyObject *PyUnicode_FromUnicode(const Py_UNICODE *u,
-                                Py_ssize_t size)
+PyObject *
+PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
 {
     PyUnicodeObject *unicode;
 
@@ -514,7 +516,8 @@
     return (PyObject *)unicode;
 }
 
-PyObject *PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
+PyObject *
+PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
 {
     PyUnicodeObject *unicode;
 
@@ -561,7 +564,8 @@
     return (PyObject *)unicode;
 }
 
-PyObject *PyUnicode_FromString(const char *u)
+PyObject *
+PyUnicode_FromString(const char *u)
 {
     size_t size = strlen(u);
     if (size > PY_SSIZE_T_MAX) {
@@ -583,8 +587,8 @@
 /* Here sizeof(wchar_t) is 4 but Py_UNICODE_SIZE == 2, so we need
    to convert from UTF32 to UTF16. */
 
-PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
-                                 Py_ssize_t size)
+PyObject *
+PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
 {
     PyUnicodeObject *unicode;
     register Py_ssize_t i;
@@ -634,8 +638,8 @@
 
 #else
 
-PyObject *PyUnicode_FromWideChar(register const wchar_t *w,
-                                 Py_ssize_t size)
+PyObject *
+PyUnicode_FromWideChar(register const wchar_t *w, Py_ssize_t size)
 {
     PyUnicodeObject *unicode;
 
@@ -816,8 +820,19 @@
 
             switch (*f) {
             case 'c':
+            {
+#ifndef Py_UNICODE_WIDE
+                int ordinal = va_arg(count, int);
+                if (ordinal > 0xffff)
+                    n += 2;
+                else
+                    n++;
+#else
                 (void)va_arg(count, int);
-                /* fall through... */
+                n++;
+#endif
+                break;
+            }
             case '%':
                 n++;
                 break;
@@ -995,8 +1010,18 @@
 
             switch (*f) {
             case 'c':
-                *s++ = va_arg(vargs, int);
+            {
+                int ordinal = va_arg(vargs, int);
+#ifndef Py_UNICODE_WIDE
+                if (ordinal > 0xffff) {
+                    ordinal -= 0x10000;
+                    *s++ = 0xD800 | (ordinal >> 10);
+                    *s++ = 0xDC00 | (ordinal & 0x3FF);
+                } else
+#endif
+                *s++ = ordinal;
                 break;
+            }
             case 'd':
                 makefmt(fmt, longflag, longlongflag, size_tflag, zeropad,
                         width, precision, 'd');
@@ -1264,7 +1289,7 @@
 }
 
 Py_ssize_t
-PyUnicode_AsWideChar(PyUnicodeObject *unicode,
+PyUnicode_AsWideChar(PyObject *unicode,
                      wchar_t *w,
                      Py_ssize_t size)
 {
@@ -1272,7 +1297,7 @@
         PyErr_BadInternalCall();
         return -1;
     }
-    return unicode_aswidechar(unicode, w, size);
+    return unicode_aswidechar((PyUnicodeObject*)unicode, w, size);
 }
 
 wchar_t*
@@ -1306,7 +1331,8 @@
 
 #endif
 
-PyObject *PyUnicode_FromOrdinal(int ordinal)
+PyObject *
+PyUnicode_FromOrdinal(int ordinal)
 {
     Py_UNICODE s[2];
 
@@ -1329,7 +1355,8 @@
     return PyUnicode_FromUnicode(s, 1);
 }
 
-PyObject *PyUnicode_FromObject(register PyObject *obj)
+PyObject *
+PyUnicode_FromObject(register PyObject *obj)
 {
     /* XXX Perhaps we should make this API an alias of
        PyObject_Str() instead ?! */
@@ -1349,9 +1376,10 @@
     return NULL;
 }
 
-PyObject *PyUnicode_FromEncodedObject(register PyObject *obj,
-                                      const char *encoding,
-                                      const char *errors)
+PyObject *
+PyUnicode_FromEncodedObject(register PyObject *obj,
+			    const char *encoding,
+			    const char *errors)
 {
     Py_buffer buffer;
     PyObject *v;
@@ -1434,23 +1462,26 @@
     return 1;
 }
 
-PyObject *PyUnicode_Decode(const char *s,
-                           Py_ssize_t size,
-                           const char *encoding,
-                           const char *errors)
+PyObject *
+PyUnicode_Decode(const char *s,
+		 Py_ssize_t size,
+		 const char *encoding,
+		 const char *errors)
 {
     PyObject *buffer = NULL, *unicode;
     Py_buffer info;
     char lower[11];  /* Enough for any encoding shortcut */
 
     if (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
+        return PyUnicode_DecodeUTF8(s, size, errors);
 
     /* Shortcuts for common default encodings */
     if (normalize_encoding(encoding, lower, sizeof(lower))) {
-        if (strcmp(lower, "utf-8") == 0)
+        if ((strcmp(lower, "utf-8") == 0) ||
+            (strcmp(lower, "utf8") == 0))
             return PyUnicode_DecodeUTF8(s, size, errors);
         else if ((strcmp(lower, "latin-1") == 0) ||
+                 (strcmp(lower, "latin1") == 0) ||
                  (strcmp(lower, "iso-8859-1") == 0))
             return PyUnicode_DecodeLatin1(s, size, errors);
 #if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
@@ -1490,9 +1521,10 @@
     return NULL;
 }
 
-PyObject *PyUnicode_AsDecodedObject(PyObject *unicode,
-                                    const char *encoding,
-                                    const char *errors)
+PyObject *
+PyUnicode_AsDecodedObject(PyObject *unicode,
+			  const char *encoding,
+			  const char *errors)
 {
     PyObject *v;
 
@@ -1514,9 +1546,10 @@
     return NULL;
 }
 
-PyObject *PyUnicode_AsDecodedUnicode(PyObject *unicode,
-                                     const char *encoding,
-                                     const char *errors)
+PyObject *
+PyUnicode_AsDecodedUnicode(PyObject *unicode,
+			   const char *encoding,
+			   const char *errors)
 {
     PyObject *v;
 
@@ -1545,10 +1578,11 @@
     return NULL;
 }
 
-PyObject *PyUnicode_Encode(const Py_UNICODE *s,
-                           Py_ssize_t size,
-                           const char *encoding,
-                           const char *errors)
+PyObject *
+PyUnicode_Encode(const Py_UNICODE *s,
+		 Py_ssize_t size,
+		 const char *encoding,
+		 const char *errors)
 {
     PyObject *v, *unicode;
 
@@ -1560,9 +1594,10 @@
     return v;
 }
 
-PyObject *PyUnicode_AsEncodedObject(PyObject *unicode,
-                                    const char *encoding,
-                                    const char *errors)
+PyObject *
+PyUnicode_AsEncodedObject(PyObject *unicode,
+			  const char *encoding,
+			  const char *errors)
 {
     PyObject *v;
 
@@ -1639,9 +1674,10 @@
 #endif
 }
 
-PyObject *PyUnicode_AsEncodedString(PyObject *unicode,
-                                    const char *encoding,
-                                    const char *errors)
+PyObject *
+PyUnicode_AsEncodedString(PyObject *unicode,
+			  const char *encoding,
+			  const char *errors)
 {
     PyObject *v;
     char lower[11];  /* Enough for any encoding shortcut */
@@ -1652,15 +1688,19 @@
     }
 
     if (encoding == NULL)
-        encoding = PyUnicode_GetDefaultEncoding();
+        return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
+                                    PyUnicode_GET_SIZE(unicode),
+                                    errors);
 
     /* Shortcuts for common default encodings */
     if (normalize_encoding(encoding, lower, sizeof(lower))) {
-        if (strcmp(lower, "utf-8") == 0)
+        if ((strcmp(lower, "utf-8") == 0) ||
+            (strcmp(lower, "utf8") == 0))
             return PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(unicode),
                                         PyUnicode_GET_SIZE(unicode),
                                         errors);
         else if ((strcmp(lower, "latin-1") == 0) ||
+                 (strcmp(lower, "latin1") == 0) ||
                  (strcmp(lower, "iso-8859-1") == 0))
             return PyUnicode_EncodeLatin1(PyUnicode_AS_UNICODE(unicode),
                                           PyUnicode_GET_SIZE(unicode),
@@ -1676,21 +1716,6 @@
                                          PyUnicode_GET_SIZE(unicode),
                                          errors);
     }
-    /* During bootstrap, we may need to find the encodings
-       package, to load the file system encoding, and require the
-       file system encoding in order to load the encodings
-       package.
-
-       Break out of this dependency by assuming that the path to
-       the encodings module is ASCII-only.  XXX could try wcstombs
-       instead, if the file system encoding is the locale's
-       encoding. */
-    if (Py_FileSystemDefaultEncoding &&
-             strcmp(encoding, Py_FileSystemDefaultEncoding) == 0 &&
-             !PyThreadState_GET()->interp->codecs_initialized)
-        return PyUnicode_EncodeASCII(PyUnicode_AS_UNICODE(unicode),
-                                     PyUnicode_GET_SIZE(unicode),
-                                     errors);
 
     /* Encode via the codec registry */
     v = PyCodec_Encode(unicode, encoding, errors);
@@ -1726,9 +1751,10 @@
     return NULL;
 }
 
-PyObject *PyUnicode_AsEncodedUnicode(PyObject *unicode,
-                                     const char *encoding,
-                                     const char *errors)
+PyObject *
+PyUnicode_AsEncodedUnicode(PyObject *unicode,
+			   const char *encoding,
+			   const char *errors)
 {
     PyObject *v;
 
@@ -1757,8 +1783,9 @@
     return NULL;
 }
 
-PyObject *_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
-                                            const char *errors)
+PyObject *
+_PyUnicode_AsDefaultEncodedString(PyObject *unicode,
+				  const char *errors)
 {
     PyObject *v = ((PyUnicodeObject *)unicode)->defenc;
     if (v)
@@ -1924,7 +1951,8 @@
     return _PyUnicode_AsStringAndSize(unicode, NULL);
 }
 
-Py_UNICODE *PyUnicode_AsUnicode(PyObject *unicode)
+Py_UNICODE *
+PyUnicode_AsUnicode(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
@@ -1936,7 +1964,8 @@
     return NULL;
 }
 
-Py_ssize_t PyUnicode_GetSize(PyObject *unicode)
+Py_ssize_t
+PyUnicode_GetSize(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
@@ -1948,7 +1977,8 @@
     return -1;
 }
 
-const char *PyUnicode_GetDefaultEncoding(void)
+const char *
+PyUnicode_GetDefaultEncoding(void)
 {
     return "utf-8";
 }
@@ -1987,12 +2017,12 @@
    return 0 on success, -1 on error
 */
 
-static
-int unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
-                                     const char *encoding, const char *reason,
-                                     const char **input, const char **inend, Py_ssize_t *startinpos,
-                                     Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
-                                     PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
+static int
+unicode_decode_call_errorhandler(const char *errors, PyObject **errorHandler,
+				 const char *encoding, const char *reason,
+				 const char **input, const char **inend, Py_ssize_t *startinpos,
+				 Py_ssize_t *endinpos, PyObject **exceptionObject, const char **inptr,
+				 PyUnicodeObject **output, Py_ssize_t *outpos, Py_UNICODE **outptr)
 {
     static char *argparse = "O!n;decoding error handler must return (str, int) tuple";
 
@@ -2162,9 +2192,10 @@
       (directWS && (utf7_category[(c)] == 2)) ||        \
       (directO && (utf7_category[(c)] == 1))))
 
-PyObject *PyUnicode_DecodeUTF7(const char *s,
-                               Py_ssize_t size,
-                               const char *errors)
+PyObject *
+PyUnicode_DecodeUTF7(const char *s,
+		     Py_ssize_t size,
+		     const char *errors)
 {
     return PyUnicode_DecodeUTF7Stateful(s, size, errors, NULL);
 }
@@ -2176,10 +2207,11 @@
  * all the shift state (seen bits, number of bits seen, high
  * surrogate). */
 
-PyObject *PyUnicode_DecodeUTF7Stateful(const char *s,
-                                       Py_ssize_t size,
-                                       const char *errors,
-                                       Py_ssize_t *consumed)
+PyObject *
+PyUnicode_DecodeUTF7Stateful(const char *s,
+			     Py_ssize_t size,
+			     const char *errors,
+			     Py_ssize_t *consumed)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -2366,11 +2398,12 @@
 }
 
 
-PyObject *PyUnicode_EncodeUTF7(const Py_UNICODE *s,
-                               Py_ssize_t size,
-                               int base64SetO,
-                               int base64WhiteSpace,
-                               const char *errors)
+PyObject *
+PyUnicode_EncodeUTF7(const Py_UNICODE *s,
+		     Py_ssize_t size,
+		     int base64SetO,
+		     int base64WhiteSpace,
+		     const char *errors)
 {
     PyObject *v;
     /* It might be possible to tighten this worst case */
@@ -2491,9 +2524,10 @@
     4, 4, 4, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0  /* F0-F4 + F5-FF */
 };
 
-PyObject *PyUnicode_DecodeUTF8(const char *s,
-                               Py_ssize_t size,
-                               const char *errors)
+PyObject *
+PyUnicode_DecodeUTF8(const char *s,
+		     Py_ssize_t size,
+		     const char *errors)
 {
     return PyUnicode_DecodeUTF8Stateful(s, size, errors, NULL);
 }
@@ -2511,10 +2545,11 @@
 # error C 'long' size should be either 4 or 8!
 #endif
 
-PyObject *PyUnicode_DecodeUTF8Stateful(const char *s,
-                                       Py_ssize_t size,
-                                       const char *errors,
-                                       Py_ssize_t *consumed)
+PyObject *
+PyUnicode_DecodeUTF8Stateful(const char *s,
+			     Py_ssize_t size,
+			     const char *errors,
+			     Py_ssize_t *consumed)
 {
     const char *starts = s;
     int n;
@@ -3020,7 +3055,8 @@
 #undef MAX_SHORT_UNICHARS
 }
 
-PyObject *PyUnicode_AsUTF8String(PyObject *unicode)
+PyObject *
+PyUnicode_AsUTF8String(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
@@ -3294,7 +3330,8 @@
 #undef STORECHAR
 }
 
-PyObject *PyUnicode_AsUTF32String(PyObject *unicode)
+PyObject *
+PyUnicode_AsUTF32String(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
@@ -3684,7 +3721,8 @@
 #undef STORECHAR
 }
 
-PyObject *PyUnicode_AsUTF16String(PyObject *unicode)
+PyObject *
+PyUnicode_AsUTF16String(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
@@ -3700,9 +3738,10 @@
 
 static _PyUnicode_Name_CAPI *ucnhash_CAPI = NULL;
 
-PyObject *PyUnicode_DecodeUnicodeEscape(const char *s,
-                                        Py_ssize_t size,
-                                        const char *errors)
+PyObject *
+PyUnicode_DecodeUnicodeEscape(const char *s,
+			      Py_ssize_t size,
+			      const char *errors)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -3958,8 +3997,9 @@
 
 static const char *hexdigits = "0123456789abcdef";
 
-PyObject *PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
-                                        Py_ssize_t size)
+PyObject *
+PyUnicode_EncodeUnicodeEscape(const Py_UNICODE *s,
+			      Py_ssize_t size)
 {
     PyObject *repr;
     char *p;
@@ -4099,7 +4139,8 @@
     return repr;
 }
 
-PyObject *PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
+PyObject *
+PyUnicode_AsUnicodeEscapeString(PyObject *unicode)
 {
     PyObject *s;
     if (!PyUnicode_Check(unicode)) {
@@ -4113,9 +4154,10 @@
 
 /* --- Raw Unicode Escape Codec ------------------------------------------- */
 
-PyObject *PyUnicode_DecodeRawUnicodeEscape(const char *s,
-                                           Py_ssize_t size,
-                                           const char *errors)
+PyObject *
+PyUnicode_DecodeRawUnicodeEscape(const char *s,
+				 Py_ssize_t size,
+				 const char *errors)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -4230,8 +4272,9 @@
     return NULL;
 }
 
-PyObject *PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
-                                           Py_ssize_t size)
+PyObject *
+PyUnicode_EncodeRawUnicodeEscape(const Py_UNICODE *s,
+				 Py_ssize_t size)
 {
     PyObject *repr;
     char *p;
@@ -4318,7 +4361,8 @@
     return repr;
 }
 
-PyObject *PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
+PyObject *
+PyUnicode_AsRawUnicodeEscapeString(PyObject *unicode)
 {
     PyObject *s;
     if (!PyUnicode_Check(unicode)) {
@@ -4333,9 +4377,10 @@
 
 /* --- Unicode Internal Codec ------------------------------------------- */
 
-PyObject *_PyUnicode_DecodeUnicodeInternal(const char *s,
-                                           Py_ssize_t size,
-                                           const char *errors)
+PyObject *
+_PyUnicode_DecodeUnicodeInternal(const char *s,
+				 Py_ssize_t size,
+				 const char *errors)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -4411,9 +4456,10 @@
 
 /* --- Latin-1 Codec ------------------------------------------------------ */
 
-PyObject *PyUnicode_DecodeLatin1(const char *s,
-                                 Py_ssize_t size,
-                                 const char *errors)
+PyObject *
+PyUnicode_DecodeLatin1(const char *s,
+		       Py_ssize_t size,
+		       const char *errors)
 {
     PyUnicodeObject *v;
     Py_UNICODE *p;
@@ -4453,11 +4499,12 @@
 }
 
 /* create or adjust a UnicodeEncodeError */
-static void make_encode_exception(PyObject **exceptionObject,
-                                  const char *encoding,
-                                  const Py_UNICODE *unicode, Py_ssize_t size,
-                                  Py_ssize_t startpos, Py_ssize_t endpos,
-                                  const char *reason)
+static void
+make_encode_exception(PyObject **exceptionObject,
+		      const char *encoding,
+		      const Py_UNICODE *unicode, Py_ssize_t size,
+		      Py_ssize_t startpos, Py_ssize_t endpos,
+		      const char *reason)
 {
     if (*exceptionObject == NULL) {
         *exceptionObject = PyUnicodeEncodeError_Create(
@@ -4478,11 +4525,12 @@
 }
 
 /* raises a UnicodeEncodeError */
-static void raise_encode_exception(PyObject **exceptionObject,
-                                   const char *encoding,
-                                   const Py_UNICODE *unicode, Py_ssize_t size,
-                                   Py_ssize_t startpos, Py_ssize_t endpos,
-                                   const char *reason)
+static void
+raise_encode_exception(PyObject **exceptionObject,
+		       const char *encoding,
+		       const Py_UNICODE *unicode, Py_ssize_t size,
+		       Py_ssize_t startpos, Py_ssize_t endpos,
+		       const char *reason)
 {
     make_encode_exception(exceptionObject,
                           encoding, unicode, size, startpos, endpos, reason);
@@ -4494,12 +4542,13 @@
    build arguments, call the callback and check the arguments,
    put the result into newpos and return the replacement string, which
    has to be freed by the caller */
-static PyObject *unicode_encode_call_errorhandler(const char *errors,
-                                                  PyObject **errorHandler,
-                                                  const char *encoding, const char *reason,
-                                                  const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
-                                                  Py_ssize_t startpos, Py_ssize_t endpos,
-                                                  Py_ssize_t *newpos)
+static PyObject *
+unicode_encode_call_errorhandler(const char *errors,
+				 PyObject **errorHandler,
+				 const char *encoding, const char *reason,
+				 const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
+				 Py_ssize_t startpos, Py_ssize_t endpos,
+				 Py_ssize_t *newpos)
 {
     static char *argparse = "On;encoding error handler must return (str/bytes, int) tuple";
 
@@ -4548,10 +4597,11 @@
     return resunicode;
 }
 
-static PyObject *unicode_encode_ucs1(const Py_UNICODE *p,
-                                     Py_ssize_t size,
-                                     const char *errors,
-                                     int limit)
+static PyObject *
+unicode_encode_ucs1(const Py_UNICODE *p,
+		    Py_ssize_t size,
+		    const char *errors,
+		    int limit)
 {
     /* output object */
     PyObject *res;
@@ -4744,14 +4794,16 @@
     return NULL;
 }
 
-PyObject *PyUnicode_EncodeLatin1(const Py_UNICODE *p,
-                                 Py_ssize_t size,
-                                 const char *errors)
+PyObject *
+PyUnicode_EncodeLatin1(const Py_UNICODE *p,
+		       Py_ssize_t size,
+		       const char *errors)
 {
     return unicode_encode_ucs1(p, size, errors, 256);
 }
 
-PyObject *PyUnicode_AsLatin1String(PyObject *unicode)
+PyObject *
+PyUnicode_AsLatin1String(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
@@ -4764,9 +4816,10 @@
 
 /* --- 7-bit ASCII Codec -------------------------------------------------- */
 
-PyObject *PyUnicode_DecodeASCII(const char *s,
-                                Py_ssize_t size,
-                                const char *errors)
+PyObject *
+PyUnicode_DecodeASCII(const char *s,
+                      Py_ssize_t size,
+                      const char *errors)
 {
     const char *starts = s;
     PyUnicodeObject *v;
@@ -4823,14 +4876,16 @@
     return NULL;
 }
 
-PyObject *PyUnicode_EncodeASCII(const Py_UNICODE *p,
-                                Py_ssize_t size,
-                                const char *errors)
+PyObject *
+PyUnicode_EncodeASCII(const Py_UNICODE *p,
+                      Py_ssize_t size,
+                      const char *errors)
 {
     return unicode_encode_ucs1(p, size, errors, 128);
 }
 
-PyObject *PyUnicode_AsASCIIString(PyObject *unicode)
+PyObject *
+PyUnicode_AsASCIIString(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
@@ -4854,7 +4909,8 @@
    b) IsDBCSLeadByte (probably) does not work for non-DBCS multi-byte
    encodings, see IsDBCSLeadByteEx documentation. */
 
-static int is_dbcs_lead_byte(const char *s, int offset)
+static int
+is_dbcs_lead_byte(const char *s, int offset)
 {
     const char *curr = s + offset;
 
@@ -4869,11 +4925,12 @@
  * Decode MBCS string into unicode object. If 'final' is set, converts
  * trailing lead-byte too. Returns consumed size if succeed, -1 otherwise.
  */
-static int decode_mbcs(PyUnicodeObject **v,
-                       const char *s, /* MBCS string */
-                       int size, /* sizeof MBCS string */
-                       int final,
-                       const char *errors)
+static int
+decode_mbcs(PyUnicodeObject **v,
+            const char *s, /* MBCS string */
+            int size, /* sizeof MBCS string */
+            int final,
+            const char *errors)
 {
     Py_UNICODE *p;
     Py_ssize_t n;
@@ -4952,10 +5009,11 @@
     return -1;
 }
 
-PyObject *PyUnicode_DecodeMBCSStateful(const char *s,
-                                       Py_ssize_t size,
-                                       const char *errors,
-                                       Py_ssize_t *consumed)
+PyObject *
+PyUnicode_DecodeMBCSStateful(const char *s,
+                             Py_ssize_t size,
+                             const char *errors,
+                             Py_ssize_t *consumed)
 {
     PyUnicodeObject *v = NULL;
     int done;
@@ -4990,9 +5048,10 @@
     return (PyObject *)v;
 }
 
-PyObject *PyUnicode_DecodeMBCS(const char *s,
-                               Py_ssize_t size,
-                               const char *errors)
+PyObject *
+PyUnicode_DecodeMBCS(const char *s,
+                     Py_ssize_t size,
+                     const char *errors)
 {
     return PyUnicode_DecodeMBCSStateful(s, size, errors, NULL);
 }
@@ -5001,10 +5060,11 @@
  * Convert unicode into string object (MBCS).
  * Returns 0 if succeed, -1 otherwise.
  */
-static int encode_mbcs(PyObject **repr,
-                       const Py_UNICODE *p, /* unicode */
-                       int size, /* size of unicode */
-                       const char* errors)
+static int
+encode_mbcs(PyObject **repr,
+            const Py_UNICODE *p, /* unicode */
+            int size, /* size of unicode */
+            const char* errors)
 {
     BOOL usedDefaultChar = FALSE;
     BOOL *pusedDefaultChar;
@@ -5077,9 +5137,10 @@
     return -1;
 }
 
-PyObject *PyUnicode_EncodeMBCS(const Py_UNICODE *p,
-                               Py_ssize_t size,
-                               const char *errors)
+PyObject *
+PyUnicode_EncodeMBCS(const Py_UNICODE *p,
+                     Py_ssize_t size,
+                     const char *errors)
 {
     PyObject *repr = NULL;
     int ret;
@@ -5108,7 +5169,8 @@
     return repr;
 }
 
-PyObject *PyUnicode_AsMBCSString(PyObject *unicode)
+PyObject *
+PyUnicode_AsMBCSString(PyObject *unicode)
 {
     if (!PyUnicode_Check(unicode)) {
         PyErr_BadArgument();
@@ -5125,10 +5187,11 @@
 
 /* --- Character Mapping Codec -------------------------------------------- */
 
-PyObject *PyUnicode_DecodeCharmap(const char *s,
-                                  Py_ssize_t size,
-                                  PyObject *mapping,
-                                  const char *errors)
+PyObject *
+PyUnicode_DecodeCharmap(const char *s,
+                        Py_ssize_t size,
+                        PyObject *mapping,
+                        const char *errors)
 {
     const char *starts = s;
     Py_ssize_t startinpos;
@@ -5288,7 +5351,7 @@
 
 /* Charmap encoding: the lookup table */
 
-struct encoding_map{
+struct encoding_map {
     PyObject_HEAD
     unsigned char level1[32];
     int count2, count3;
@@ -5415,7 +5478,6 @@
         if (!result)
             return NULL;
         for (i = 0; i < 256; i++) {
-            key = value = NULL;
             key = PyLong_FromLong(decode[i]);
             value = PyLong_FromLong(i);
             if (!key || !value)
@@ -5503,7 +5565,8 @@
 /* Lookup the character ch in the mapping. If the character
    can't be found, Py_None is returned (or NULL, if another
    error occurred). */
-static PyObject *charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
+static PyObject *
+charmapencode_lookup(Py_UNICODE c, PyObject *mapping)
 {
     PyObject *w = PyLong_FromLong((long)c);
     PyObject *x;
@@ -5560,16 +5623,16 @@
 
 typedef enum charmapencode_result {
     enc_SUCCESS, enc_FAILED, enc_EXCEPTION
-}charmapencode_result;
+} charmapencode_result;
 /* lookup the character, put the result in the output string and adjust
    various state variables. Resize the output bytes object if not enough
    space is available. Return a new reference to the object that
    was put in the output buffer, or Py_None, if the mapping was undefined
    (in which case no character was written) or NULL, if a
    reallocation error occurred. The caller must decref the result */
-static
-charmapencode_result charmapencode_output(Py_UNICODE c, PyObject *mapping,
-                                          PyObject **outobj, Py_ssize_t *outpos)
+static charmapencode_result
+charmapencode_output(Py_UNICODE c, PyObject *mapping,
+                     PyObject **outobj, Py_ssize_t *outpos)
 {
     PyObject *rep;
     char *outstart;
@@ -5625,8 +5688,8 @@
 
 /* handle an error in PyUnicode_EncodeCharmap
    Return 0 on success, -1 on error */
-static
-int charmap_encoding_error(
+static int
+charmap_encoding_error(
     const Py_UNICODE *p, Py_ssize_t size, Py_ssize_t *inpos, PyObject *mapping,
     PyObject **exceptionObject,
     int *known_errorHandler, PyObject **errorHandler, const char *errors,
@@ -5760,10 +5823,11 @@
     return 0;
 }
 
-PyObject *PyUnicode_EncodeCharmap(const Py_UNICODE *p,
-                                  Py_ssize_t size,
-                                  PyObject *mapping,
-                                  const char *errors)
+PyObject *
+PyUnicode_EncodeCharmap(const Py_UNICODE *p,
+                        Py_ssize_t size,
+                        PyObject *mapping,
+                        const char *errors)
 {
     /* output object */
     PyObject *res = NULL;
@@ -5824,8 +5888,9 @@
     return NULL;
 }
 
-PyObject *PyUnicode_AsCharmapString(PyObject *unicode,
-                                    PyObject *mapping)
+PyObject *
+PyUnicode_AsCharmapString(PyObject *unicode,
+                          PyObject *mapping)
 {
     if (!PyUnicode_Check(unicode) || mapping == NULL) {
         PyErr_BadArgument();
@@ -5838,10 +5903,11 @@
 }
 
 /* create or adjust a UnicodeTranslateError */
-static void make_translate_exception(PyObject **exceptionObject,
-                                     const Py_UNICODE *unicode, Py_ssize_t size,
-                                     Py_ssize_t startpos, Py_ssize_t endpos,
-                                     const char *reason)
+static void
+make_translate_exception(PyObject **exceptionObject,
+                         const Py_UNICODE *unicode, Py_ssize_t size,
+                         Py_ssize_t startpos, Py_ssize_t endpos,
+                         const char *reason)
 {
     if (*exceptionObject == NULL) {
         *exceptionObject = PyUnicodeTranslateError_Create(
@@ -5862,10 +5928,11 @@
 }
 
 /* raises a UnicodeTranslateError */
-static void raise_translate_exception(PyObject **exceptionObject,
-                                      const Py_UNICODE *unicode, Py_ssize_t size,
-                                      Py_ssize_t startpos, Py_ssize_t endpos,
-                                      const char *reason)
+static void
+raise_translate_exception(PyObject **exceptionObject,
+                          const Py_UNICODE *unicode, Py_ssize_t size,
+                          Py_ssize_t startpos, Py_ssize_t endpos,
+                          const char *reason)
 {
     make_translate_exception(exceptionObject,
                              unicode, size, startpos, endpos, reason);
@@ -5877,12 +5944,13 @@
    build arguments, call the callback and check the arguments,
    put the result into newpos and return the replacement string, which
    has to be freed by the caller */
-static PyObject *unicode_translate_call_errorhandler(const char *errors,
-                                                     PyObject **errorHandler,
-                                                     const char *reason,
-                                                     const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
-                                                     Py_ssize_t startpos, Py_ssize_t endpos,
-                                                     Py_ssize_t *newpos)
+static PyObject *
+unicode_translate_call_errorhandler(const char *errors,
+                                    PyObject **errorHandler,
+                                    const char *reason,
+                                    const Py_UNICODE *unicode, Py_ssize_t size, PyObject **exceptionObject,
+                                    Py_ssize_t startpos, Py_ssize_t endpos,
+                                    Py_ssize_t *newpos)
 {
     static char *argparse = "O!n;translating error handler must return (str, int) tuple";
 
@@ -5932,8 +6000,8 @@
 /* Lookup the character ch in the mapping and put the result in result,
    which must be decrefed by the caller.
    Return 0 on success, -1 on error */
-static
-int charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
+static int
+charmaptranslate_lookup(Py_UNICODE c, PyObject *mapping, PyObject **result)
 {
     PyObject *w = PyLong_FromLong((long)c);
     PyObject *x;
@@ -5982,8 +6050,8 @@
 /* ensure that *outobj is at least requiredsize characters long,
    if not reallocate and adjust various state variables.
    Return 0 on success, -1 on error */
-static
-int charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
+static int
+charmaptranslate_makespace(PyObject **outobj, Py_UNICODE **outp,
                                Py_ssize_t requiredsize)
 {
     Py_ssize_t oldsize = PyUnicode_GET_SIZE(*outobj);
@@ -6005,10 +6073,10 @@
    undefined (in which case no character was written).
    The called must decref result.
    Return 0 on success, -1 on error. */
-static
-int charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
-                            Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
-                            PyObject **res)
+static int
+charmaptranslate_output(const Py_UNICODE *startinp, const Py_UNICODE *curinp,
+                        Py_ssize_t insize, PyObject *mapping, PyObject **outobj, Py_UNICODE **outp,
+                        PyObject **res)
 {
     if (charmaptranslate_lookup(*curinp, mapping, res))
         return -1;
@@ -6044,10 +6112,11 @@
     return 0;
 }
 
-PyObject *PyUnicode_TranslateCharmap(const Py_UNICODE *p,
-                                     Py_ssize_t size,
-                                     PyObject *mapping,
-                                     const char *errors)
+PyObject *
+PyUnicode_TranslateCharmap(const Py_UNICODE *p,
+                           Py_ssize_t size,
+                           PyObject *mapping,
+                           const char *errors)
 {
     /* output object */
     PyObject *res = NULL;
@@ -6186,9 +6255,10 @@
     return NULL;
 }
 
-PyObject *PyUnicode_Translate(PyObject *str,
-                              PyObject *mapping,
-                              const char *errors)
+PyObject *
+PyUnicode_Translate(PyObject *str,
+                    PyObject *mapping,
+                    const char *errors)
 {
     PyObject *result;
 
@@ -6207,12 +6277,37 @@
     return NULL;
 }
 
+PyObject *
+PyUnicode_TransformDecimalToASCII(Py_UNICODE *s,
+                                  Py_ssize_t length)
+{
+    PyObject *result;
+    Py_UNICODE *p; /* write pointer into result */
+    Py_ssize_t i;
+    /* Copy to a new string */
+    result = (PyObject *)_PyUnicode_New(length);
+    Py_UNICODE_COPY(PyUnicode_AS_UNICODE(result), s, length);
+    if (result == NULL)
+        return result;
+    p = PyUnicode_AS_UNICODE(result);
+    /* Iterate over code points */
+    for (i = 0; i < length; i++) {
+        Py_UNICODE ch =s[i];
+        if (ch > 127) {
+            int decimal = Py_UNICODE_TODECIMAL(ch);
+            if (decimal >= 0)
+                p[i] = '0' + decimal;
+        }
+    }
+    return result;
+}
 /* --- Decimal Encoder ---------------------------------------------------- */
 
-int PyUnicode_EncodeDecimal(Py_UNICODE *s,
-                            Py_ssize_t length,
-                            char *output,
-                            const char *errors)
+int
+PyUnicode_EncodeDecimal(Py_UNICODE *s,
+                        Py_ssize_t length,
+                        char *output,
+                        const char *errors)
 {
     Py_UNICODE *p, *end;
     PyObject *errorHandler = NULL;
@@ -6373,10 +6468,11 @@
             start = 0;                          \
     }
 
-Py_ssize_t PyUnicode_Count(PyObject *str,
-                           PyObject *substr,
-                           Py_ssize_t start,
-                           Py_ssize_t end)
+Py_ssize_t
+PyUnicode_Count(PyObject *str,
+                PyObject *substr,
+                Py_ssize_t start,
+                Py_ssize_t end)
 {
     Py_ssize_t result;
     PyUnicodeObject* str_obj;
@@ -6403,11 +6499,12 @@
     return result;
 }
 
-Py_ssize_t PyUnicode_Find(PyObject *str,
-                          PyObject *sub,
-                          Py_ssize_t start,
-                          Py_ssize_t end,
-                          int direction)
+Py_ssize_t
+PyUnicode_Find(PyObject *str,
+               PyObject *sub,
+               Py_ssize_t start,
+               Py_ssize_t end,
+               int direction)
 {
     Py_ssize_t result;
 
@@ -6439,12 +6536,12 @@
     return result;
 }
 
-static
-int tailmatch(PyUnicodeObject *self,
-              PyUnicodeObject *substring,
-              Py_ssize_t start,
-              Py_ssize_t end,
-              int direction)
+static int
+tailmatch(PyUnicodeObject *self,
+          PyUnicodeObject *substring,
+          Py_ssize_t start,
+          Py_ssize_t end,
+          int direction)
 {
     if (substring->length == 0)
         return 1;
@@ -6465,11 +6562,12 @@
     return 0;
 }
 
-Py_ssize_t PyUnicode_Tailmatch(PyObject *str,
-                               PyObject *substr,
-                               Py_ssize_t start,
-                               Py_ssize_t end,
-                               int direction)
+Py_ssize_t
+PyUnicode_Tailmatch(PyObject *str,
+                    PyObject *substr,
+                    Py_ssize_t start,
+                    Py_ssize_t end,
+                    int direction)
 {
     Py_ssize_t result;
 
@@ -6493,9 +6591,9 @@
 /* Apply fixfct filter to the Unicode object self and return a
    reference to the modified object */
 
-static
-PyObject *fixup(PyUnicodeObject *self,
-                int (*fixfct)(PyUnicodeObject *s))
+static PyObject *
+fixup(PyUnicodeObject *self,
+      int (*fixfct)(PyUnicodeObject *s))
 {
 
     PyUnicodeObject *u;
@@ -6517,8 +6615,8 @@
     return (PyObject*) u;
 }
 
-static
-int fixupper(PyUnicodeObject *self)
+static int
+fixupper(PyUnicodeObject *self)
 {
     Py_ssize_t len = self->length;
     Py_UNICODE *s = self->str;
@@ -6538,8 +6636,8 @@
     return status;
 }
 
-static
-int fixlower(PyUnicodeObject *self)
+static int
+fixlower(PyUnicodeObject *self)
 {
     Py_ssize_t len = self->length;
     Py_UNICODE *s = self->str;
@@ -6559,8 +6657,8 @@
     return status;
 }
 
-static
-int fixswapcase(PyUnicodeObject *self)
+static int
+fixswapcase(PyUnicodeObject *self)
 {
     Py_ssize_t len = self->length;
     Py_UNICODE *s = self->str;
@@ -6580,8 +6678,8 @@
     return status;
 }
 
-static
-int fixcapitalize(PyUnicodeObject *self)
+static int
+fixcapitalize(PyUnicodeObject *self)
 {
     Py_ssize_t len = self->length;
     Py_UNICODE *s = self->str;
@@ -6604,8 +6702,8 @@
     return status;
 }
 
-static
-int fixtitle(PyUnicodeObject *self)
+static int
+fixtitle(PyUnicodeObject *self)
 {
     register Py_UNICODE *p = PyUnicode_AS_UNICODE(self);
     register Py_UNICODE *e;
@@ -6755,11 +6853,11 @@
     return NULL;
 }
 
-static
-PyUnicodeObject *pad(PyUnicodeObject *self,
-                     Py_ssize_t left,
-                     Py_ssize_t right,
-                     Py_UNICODE fill)
+static PyUnicodeObject *
+pad(PyUnicodeObject *self,
+    Py_ssize_t left,
+    Py_ssize_t right,
+    Py_UNICODE fill)
 {
     PyUnicodeObject *u;
 
@@ -6790,7 +6888,8 @@
     return u;
 }
 
-PyObject *PyUnicode_Splitlines(PyObject *string, int keepends)
+PyObject *
+PyUnicode_Splitlines(PyObject *string, int keepends)
 {
     PyObject *list;
 
@@ -6806,10 +6905,10 @@
     return list;
 }
 
-static
-PyObject *split(PyUnicodeObject *self,
-                PyUnicodeObject *substring,
-                Py_ssize_t maxcount)
+static PyObject *
+split(PyUnicodeObject *self,
+      PyUnicodeObject *substring,
+      Py_ssize_t maxcount)
 {
     if (maxcount < 0)
         maxcount = PY_SSIZE_T_MAX;
@@ -6826,10 +6925,10 @@
         );
 }
 
-static
-PyObject *rsplit(PyUnicodeObject *self,
-                 PyUnicodeObject *substring,
-                 Py_ssize_t maxcount)
+static PyObject *
+rsplit(PyUnicodeObject *self,
+       PyUnicodeObject *substring,
+       Py_ssize_t maxcount)
 {
     if (maxcount < 0)
         maxcount = PY_SSIZE_T_MAX;
@@ -6846,11 +6945,11 @@
         );
 }
 
-static
-PyObject *replace(PyUnicodeObject *self,
-                  PyUnicodeObject *str1,
-                  PyUnicodeObject *str2,
-                  Py_ssize_t maxcount)
+static PyObject *
+replace(PyUnicodeObject *self,
+        PyUnicodeObject *str1,
+        PyUnicodeObject *str2,
+        Py_ssize_t maxcount)
 {
     PyUnicodeObject *u;
 
@@ -6908,7 +7007,7 @@
         }
     } else {
 
-        Py_ssize_t n, i, j, e;
+        Py_ssize_t n, i, j;
         Py_ssize_t product, new_size, delta;
         Py_UNICODE *p;
 
@@ -6940,7 +7039,6 @@
             return NULL;
         i = 0;
         p = u->str;
-        e = self->length - str1->length;
         if (str1->length > 0) {
             while (n-- > 0) {
                 /* look for next match */
@@ -7185,8 +7283,8 @@
 
 #endif
 
-int PyUnicode_Compare(PyObject *left,
-                      PyObject *right)
+int
+PyUnicode_Compare(PyObject *left, PyObject *right)
 {
     if (PyUnicode_Check(left) && PyUnicode_Check(right))
         return unicode_compare((PyUnicodeObject *)left,
@@ -7222,9 +7320,8 @@
 #define TEST_COND(cond)                         \
     ((cond) ? Py_True : Py_False)
 
-PyObject *PyUnicode_RichCompare(PyObject *left,
-                                PyObject *right,
-                                int op)
+PyObject *
+PyUnicode_RichCompare(PyObject *left, PyObject *right, int op)
 {
     int result;
 
@@ -7279,8 +7376,8 @@
     return Py_NotImplemented;
 }
 
-int PyUnicode_Contains(PyObject *container,
-                       PyObject *element)
+int
+PyUnicode_Contains(PyObject *container, PyObject *element)
 {
     PyObject *str, *sub;
     int result;
@@ -7310,8 +7407,8 @@
 
 /* Concat to string or Unicode object giving a new Unicode object. */
 
-PyObject *PyUnicode_Concat(PyObject *left,
-                           PyObject *right)
+PyObject *
+PyUnicode_Concat(PyObject *left, PyObject *right)
 {
     PyUnicodeObject *u = NULL, *v = NULL, *w;
 
@@ -7425,26 +7522,11 @@
     static char *kwlist[] = {"encoding", "errors", 0};
     char *encoding = NULL;
     char *errors = NULL;
-    PyObject *v;
 
     if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
                                      kwlist, &encoding, &errors))
         return NULL;
-    v = PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
-    if (v == NULL)
-        goto onError;
-    if (!PyBytes_Check(v)) {
-        PyErr_Format(PyExc_TypeError,
-                     "encoder did not return a bytes object "
-                     "(type=%.400s)",
-                     Py_TYPE(v)->tp_name);
-        Py_DECREF(v);
-        return NULL;
-    }
-    return v;
-
-  onError:
-    return NULL;
+    return PyUnicode_AsEncodedString((PyObject *)self, encoding, errors);
 }
 
 PyDoc_STRVAR(expandtabs__doc__,
@@ -8242,10 +8324,11 @@
     return (PyObject*) u;
 }
 
-PyObject *PyUnicode_Replace(PyObject *obj,
-                            PyObject *subobj,
-                            PyObject *replobj,
-                            Py_ssize_t maxcount)
+PyObject *
+PyUnicode_Replace(PyObject *obj,
+                  PyObject *subobj,
+                  PyObject *replobj,
+                  Py_ssize_t maxcount)
 {
     PyObject *self;
     PyObject *str1;
@@ -8309,8 +8392,8 @@
     return result;
 }
 
-static
-PyObject *unicode_repr(PyObject *unicode)
+static PyObject *
+unicode_repr(PyObject *unicode)
 {
     PyObject *repr;
     Py_UNICODE *p;
@@ -8543,9 +8626,8 @@
     return (PyObject*) pad(self, width - self->length, 0, fillchar);
 }
 
-PyObject *PyUnicode_Split(PyObject *s,
-                          PyObject *sep,
-                          Py_ssize_t maxsplit)
+PyObject *
+PyUnicode_Split(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
 {
     PyObject *result;
 
@@ -8674,9 +8756,8 @@
     return PyUnicode_RPartition((PyObject *)self, separator);
 }
 
-PyObject *PyUnicode_RSplit(PyObject *s,
-                           PyObject *sep,
-                           Py_ssize_t maxsplit)
+PyObject *
+PyUnicode_RSplit(PyObject *s, PyObject *sep, Py_ssize_t maxsplit)
 {
     PyObject *result;
 
@@ -8945,6 +9026,13 @@
 {
     return PyLong_FromLong(numfree);
 }
+
+static PyObject *
+unicode__decimal2ascii(PyObject *self)
+{
+    return PyUnicode_TransformDecimalToASCII(PyUnicode_AS_UNICODE(self),
+                                             PyUnicode_GET_SIZE(self));
+}
 #endif
 
 PyDoc_STRVAR(startswith__doc__,
@@ -9086,7 +9174,6 @@
     return Py_BuildValue("(u#)", v->str, v->length);
 }
 
-
 static PyMethodDef unicode_methods[] = {
 
     /* Order is according to common usage: often used methods should
@@ -9143,8 +9230,9 @@
 #endif
 
 #if 0
-    /* This one is just used for debugging the implementation. */
+    /* These methods are just used for debugging the implementation. */
     {"freelistsize", (PyCFunction) unicode_freelistsize, METH_NOARGS},
+    {"_decimal2ascii", (PyCFunction) unicode__decimal2ascii, METH_NOARGS},
 #endif
 
     {"__getnewargs__",  (PyCFunction)unicode_getnewargs, METH_NOARGS},
@@ -9195,7 +9283,7 @@
         Py_UNICODE* result_buf;
         PyObject* result;
 
-        if (PySlice_GetIndicesEx((PySliceObject*)item, PyUnicode_GET_SIZE(self),
+        if (PySlice_GetIndicesEx(item, PyUnicode_GET_SIZE(self),
                                  &start, &stop, &step, &slicelength) < 0) {
             return NULL;
         }
@@ -9361,8 +9449,8 @@
 */
 #define FORMATBUFLEN (size_t)10
 
-PyObject *PyUnicode_Format(PyObject *format,
-                           PyObject *args)
+PyObject *
+PyUnicode_Format(PyObject *format, PyObject *args)
 {
     Py_UNICODE *fmt, *res;
     Py_ssize_t fmtcnt, rescnt, reslen, arglen, argidx;
@@ -10053,7 +10141,8 @@
     return s;
 }
 
-void _Py_ReleaseInternedUnicodeStrings(void)
+void
+_Py_ReleaseInternedUnicodeStrings(void)
 {
     PyObject *keys;
     PyUnicodeObject *s;

Modified: python/branches/pep-3151/Objects/weakrefobject.c
==============================================================================
--- python/branches/pep-3151/Objects/weakrefobject.c	(original)
+++ python/branches/pep-3151/Objects/weakrefobject.c	Sat Feb 26 08:16:32 2011
@@ -168,13 +168,20 @@
                 PyErr_Clear();
         else if (PyUnicode_Check(nameobj))
                 name = _PyUnicode_AsString(nameobj);
-        PyOS_snprintf(buffer, sizeof(buffer),
-                      name ? "<weakref at %p; to '%.50s' at %p (%s)>"
-                           : "<weakref at %p; to '%.50s' at %p>",
-                      self,
-                      Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name,
-                      PyWeakref_GET_OBJECT(self),
-                      name);
+        if (name)
+            PyOS_snprintf(buffer, sizeof(buffer),
+                          "<weakref at %p; to '%.50s' at %p (%s)>",
+                          self,
+                          Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name,
+                          PyWeakref_GET_OBJECT(self),
+                          name);
+        else
+            PyOS_snprintf(buffer, sizeof(buffer),
+                          "<weakref at %p; to '%.50s' at %p>",
+                          self,
+                          Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name,
+                          PyWeakref_GET_OBJECT(self));
+
         Py_XDECREF(nameobj);
     }
     return PyUnicode_FromString(buffer);

Modified: python/branches/pep-3151/PC/VC6/pythoncore.dsp
==============================================================================
--- python/branches/pep-3151/PC/VC6/pythoncore.dsp	(original)
+++ python/branches/pep-3151/PC/VC6/pythoncore.dsp	Sat Feb 26 08:16:32 2011
@@ -54,7 +54,7 @@
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /machine:I386
-# ADD LINK32 largeint.lib kernel32.lib user32.lib advapi32.lib shell32.lib /nologo /base:"0x1e000000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"libc" /out:"./python32.dll"
+# ADD LINK32 largeint.lib kernel32.lib user32.lib advapi32.lib shell32.lib /nologo /base:"0x1e000000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"libc" /out:"./python33.dll"
 # SUBTRACT LINK32 /pdb:none
 
 !ELSEIF  "$(CFG)" == "pythoncore - Win32 Debug"
@@ -82,7 +82,7 @@
 # ADD BSC32 /nologo
 LINK32=link.exe
 # ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /dll /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 largeint.lib kernel32.lib user32.lib advapi32.lib shell32.lib /nologo /base:"0x1e000000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"libc" /out:"./python32_d.dll" /pdbtype:sept
+# ADD LINK32 largeint.lib kernel32.lib user32.lib advapi32.lib shell32.lib /nologo /base:"0x1e000000" /subsystem:windows /dll /debug /machine:I386 /nodefaultlib:"libc" /out:"./python33_d.dll" /pdbtype:sept
 # SUBTRACT LINK32 /pdb:none
 
 !ENDIF 

Modified: python/branches/pep-3151/PC/VC6/readme.txt
==============================================================================
--- python/branches/pep-3151/PC/VC6/readme.txt	(original)
+++ python/branches/pep-3151/PC/VC6/readme.txt	Sat Feb 26 08:16:32 2011
@@ -12,7 +12,7 @@
 The proper order to build subprojects:
 
 1) pythoncore (this builds the main Python DLL and library files,
-               python32.{dll, lib} in Release mode)
+               python33.{dll, lib} in Release mode)
 
 2) python (this builds the main Python executable,
            python.exe in Release mode)
@@ -23,7 +23,7 @@
    to the subsystems they implement; see SUBPROJECTS below)
 
 When using the Debug setting, the output files have a _d added to
-their name:  python32_d.dll, python_d.exe, pyexpat_d.pyd, and so on.
+their name:  python33_d.dll, python_d.exe, pyexpat_d.pyd, and so on.
 
 SUBPROJECTS
 -----------
@@ -158,9 +158,17 @@
     You can (theoretically) use any version of OpenSSL you like - the
     build process will automatically select the latest version.
 
-    You must also install ActivePerl from
+    You can install the NASM assembler from
+        http://www.nasm.us/
+    for x86 builds.  Put nasmw.exe anywhere in your PATH.
+    Note: recent releases of nasm only have nasm.exe. Just rename it to 
+    nasmw.exe.
+
+    You can also install ActivePerl from
         http://www.activestate.com/activeperl/
-    as this is used by the OpenSSL build process.  Complain to them <wink>.
+    if you like to use the official sources instead of the files from 
+    python's subversion repository. The svn version contains pre-build
+    makefiles and assembly files.
 
     The MSVC project simply invokes PC/VC6/build_ssl.py to perform
     the build.  This Python script locates and builds your OpenSSL

Modified: python/branches/pep-3151/PC/VS7.1/build_ssl.bat
==============================================================================
--- python/branches/pep-3151/PC/VS7.1/build_ssl.bat	(original)
+++ python/branches/pep-3151/PC/VS7.1/build_ssl.bat	Sat Feb 26 08:16:32 2011
@@ -1,12 +1,12 @@
-if "%1" == "ReleaseAMD64" call "%MSSdk%\SetEnv" /XP64 /RETAIL
-
- at echo off
-if not defined HOST_PYTHON (
-  if %1 EQU Debug (
-    set HOST_PYTHON=python_d.exe
-  ) ELSE (
-    set HOST_PYTHON=python.exe
-  )
-)
-%HOST_PYTHON% build_ssl.py %1 %2
-
+if "%1" == "ReleaseAMD64" call "%MSSdk%\SetEnv" /XP64 /RETAIL
+
+ at echo off
+if not defined HOST_PYTHON (
+  if %1 EQU Debug (
+    set HOST_PYTHON=python_d.exe
+  ) ELSE (
+    set HOST_PYTHON=python.exe
+  )
+)
+%HOST_PYTHON% build_ssl.py %1 %2
+

Modified: python/branches/pep-3151/PC/VS7.1/pythoncore.vcproj
==============================================================================
--- python/branches/pep-3151/PC/VS7.1/pythoncore.vcproj	(original)
+++ python/branches/pep-3151/PC/VS7.1/pythoncore.vcproj	Sat Feb 26 08:16:32 2011
@@ -39,15 +39,15 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python32.dll"
+				OutputFile="./python33.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python32.pdb"
+				ProgramDatabaseFile=".\./python33.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python32.lib"
+				ImportLibrary=".\./python33.lib"
 				TargetMachine="1"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -99,15 +99,15 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python32_d.dll"
+				OutputFile="./python33_d.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python32_d.pdb"
+				ProgramDatabaseFile=".\./python33_d.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python32_d.lib"
+				ImportLibrary=".\./python33_d.lib"
 				TargetMachine="1"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -166,15 +166,15 @@
 				Name="VCLinkerTool"
 				AdditionalOptions=" /MACHINE:IA64 /USELINK:MS_SDK"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python32.dll"
+				OutputFile="./python33.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="FALSE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python32.pdb"
+				ProgramDatabaseFile=".\./python33.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python32.lib"
+				ImportLibrary=".\./python33.lib"
 				TargetMachine="0"/>
 			<Tool
 				Name="VCMIDLTool"/>
@@ -233,15 +233,15 @@
 				Name="VCLinkerTool"
 				AdditionalOptions=" /MACHINE:AMD64 /USELINK:MS_SDK"
 				AdditionalDependencies="getbuildinfo.o"
-				OutputFile="./python32.dll"
+				OutputFile="./python33.dll"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				IgnoreDefaultLibraryNames="libc"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./python32.pdb"
+				ProgramDatabaseFile=".\./python33.pdb"
 				SubSystem="2"
 				BaseAddress="0x1e000000"
-				ImportLibrary=".\./python32.lib"
+				ImportLibrary=".\./python33.lib"
 				TargetMachine="0"/>
 			<Tool
 				Name="VCMIDLTool"/>

Modified: python/branches/pep-3151/PC/VS7.1/readme.txt
==============================================================================
--- python/branches/pep-3151/PC/VS7.1/readme.txt	(original)
+++ python/branches/pep-3151/PC/VS7.1/readme.txt	Sat Feb 26 08:16:32 2011
@@ -12,7 +12,7 @@
 The proper order to build subprojects:
 
 1) pythoncore (this builds the main Python DLL and library files,
-               python26.{dll, lib} in Release mode)
+               python33.{dll, lib} in Release mode)
               NOTE:  in previous releases, this subproject was
               named after the release number, e.g. python20.
 
@@ -26,7 +26,7 @@
    test slave; see SUBPROJECTS below)
 
 When using the Debug setting, the output files have a _d added to
-their name:  python26_d.dll, python_d.exe, parser_d.pyd, and so on.
+their name:  python33_d.dll, python_d.exe, parser_d.pyd, and so on.
 
 SUBPROJECTS
 -----------

Modified: python/branches/pep-3151/PC/VS8.0/build.bat
==============================================================================
--- python/branches/pep-3151/PC/VS8.0/build.bat	(original)
+++ python/branches/pep-3151/PC/VS8.0/build.bat	Sat Feb 26 08:16:32 2011
@@ -1,17 +1,17 @@
- at echo off
-rem A batch program to build or rebuild a particular configuration.
-rem just for convenience.
-
-setlocal
-set platf=Win32
-set conf=Release
-set build=/build
-
-:CheckOpts
-if "%1"=="-c" (set conf=%2)     & shift & shift & goto CheckOpts
-if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts
-if "%1"=="-r" (set build=/rebuild)    & shift & goto CheckOpts
-
-set cmd=devenv pcbuild.sln %build% "%conf%|%platf%"
-echo %cmd%
-%cmd%
+ at echo off
+rem A batch program to build or rebuild a particular configuration.
+rem just for convenience.
+
+setlocal
+set platf=Win32
+set conf=Release
+set build=/build
+
+:CheckOpts
+if "%1"=="-c" (set conf=%2)     & shift & shift & goto CheckOpts
+if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts
+if "%1"=="-r" (set build=/rebuild)    & shift & goto CheckOpts
+
+set cmd=devenv pcbuild.sln %build% "%conf%|%platf%"
+echo %cmd%
+%cmd%

Modified: python/branches/pep-3151/PC/VS8.0/build_env.bat
==============================================================================
--- python/branches/pep-3151/PC/VS8.0/build_env.bat	(original)
+++ python/branches/pep-3151/PC/VS8.0/build_env.bat	Sat Feb 26 08:16:32 2011
@@ -1 +1 @@
-@%comspec% /k env.bat %*
+@%comspec% /k env.bat %*

Modified: python/branches/pep-3151/PC/VS8.0/build_pgo.bat
==============================================================================
--- python/branches/pep-3151/PC/VS8.0/build_pgo.bat	(original)
+++ python/branches/pep-3151/PC/VS8.0/build_pgo.bat	Sat Feb 26 08:16:32 2011
@@ -1,41 +1,41 @@
- at echo off
-rem A batch program to build PGO (Profile guided optimization) by first
-rem building instrumented binaries, then running the testsuite, and
-rem finally building the optimized code.
-rem Note, after the first instrumented run, one can just keep on
-rem building the PGUpdate configuration while developing.
-
-setlocal
-set platf=Win32
-
-rem use the performance testsuite.  This is quick and simple
-set job1=..\..\tools\pybench\pybench.py -n 1 -C 1 --with-gc
-set path1=..\..\tools\pybench
-
-rem or the whole testsuite for more thorough testing
-set job2=..\..\lib\test\regrtest.py
-set path2=..\..\lib
-
-set job=%job1%
-set clrpath=%path1%
-
-:CheckOpts
-if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts
-if "%1"=="-2" (set job=%job2%) & (set clrpath=%path2%) & shift & goto CheckOpts
-
-set PGI=%platf%-pgi
-set PGO=%platf%-pgo
-
- at echo on
-rem build the instrumented version
-call build -p %platf% -c PGInstrument
-
-rem remove .pyc files, .pgc files and execute the job
-%PGI%\python.exe rmpyc.py %clrpath%
-del %PGI%\*.pgc
-%PGI%\python.exe %job%
-
-rem finally build the optimized version
-if exist %PGO% del /s /q %PGO%
-call build -p %platf% -c PGUpdate
-
+ at echo off
+rem A batch program to build PGO (Profile guided optimization) by first
+rem building instrumented binaries, then running the testsuite, and
+rem finally building the optimized code.
+rem Note, after the first instrumented run, one can just keep on
+rem building the PGUpdate configuration while developing.
+
+setlocal
+set platf=Win32
+
+rem use the performance testsuite.  This is quick and simple
+set job1=..\..\tools\pybench\pybench.py -n 1 -C 1 --with-gc
+set path1=..\..\tools\pybench
+
+rem or the whole testsuite for more thorough testing
+set job2=..\..\lib\test\regrtest.py
+set path2=..\..\lib
+
+set job=%job1%
+set clrpath=%path1%
+
+:CheckOpts
+if "%1"=="-p" (set platf=%2) & shift & shift & goto CheckOpts
+if "%1"=="-2" (set job=%job2%) & (set clrpath=%path2%) & shift & goto CheckOpts
+
+set PGI=%platf%-pgi
+set PGO=%platf%-pgo
+
+ at echo on
+rem build the instrumented version
+call build -p %platf% -c PGInstrument
+
+rem remove .pyc files, .pgc files and execute the job
+%PGI%\python.exe rmpyc.py %clrpath%
+del %PGI%\*.pgc
+%PGI%\python.exe %job%
+
+rem finally build the optimized version
+if exist %PGO% del /s /q %PGO%
+call build -p %platf% -c PGUpdate
+

Modified: python/branches/pep-3151/PC/VS8.0/build_ssl.bat
==============================================================================
--- python/branches/pep-3151/PC/VS8.0/build_ssl.bat	(original)
+++ python/branches/pep-3151/PC/VS8.0/build_ssl.bat	Sat Feb 26 08:16:32 2011
@@ -1,12 +1,12 @@
- at echo off
-if not defined HOST_PYTHON (
-  if %1 EQU Debug (
-    set HOST_PYTHON=python_d.exe
-    if not exist python32_d.dll exit 1
-  ) ELSE (
-    set HOST_PYTHON=python.exe
-    if not exist python32.dll exit 1
-  )
-)
-%HOST_PYTHON% build_ssl.py %1 %2 %3
-
+ at echo off
+if not defined HOST_PYTHON (
+  if %1 EQU Debug (
+    set HOST_PYTHON=python_d.exe
+    if not exist python33_d.dll exit 1
+  ) ELSE (
+    set HOST_PYTHON=python.exe
+    if not exist python33.dll exit 1
+  )
+)
+%HOST_PYTHON% build_ssl.py %1 %2 %3
+

Modified: python/branches/pep-3151/PC/VS8.0/env.bat
==============================================================================
--- python/branches/pep-3151/PC/VS8.0/env.bat	(original)
+++ python/branches/pep-3151/PC/VS8.0/env.bat	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,5 @@
- at echo off
-set VS8=%ProgramFiles%\Microsoft Visual Studio 8
-echo Build environments: x86, ia64, amd64, x86_amd64, x86_ia64
-echo.
-call "%VS8%\VC\vcvarsall.bat" %1
+ at echo off
+set VS8=%ProgramFiles%\Microsoft Visual Studio 8
+echo Build environments: x86, ia64, amd64, x86_amd64, x86_ia64
+echo.
+call "%VS8%\VC\vcvarsall.bat" %1

Modified: python/branches/pep-3151/PC/VS8.0/idle.bat
==============================================================================
--- python/branches/pep-3151/PC/VS8.0/idle.bat	(original)
+++ python/branches/pep-3151/PC/VS8.0/idle.bat	Sat Feb 26 08:16:32 2011
@@ -1,15 +1,15 @@
- at echo off
-rem start idle
-rem Usage:  idle [-d]
-rem -d   Run Debug build (python_d.exe).  Else release build.
-
-setlocal
-set exe=python
-PATH %PATH%;..\..\..\tcltk\bin
-
-if "%1"=="-d" (set exe=python_d) & shift
-
-set cmd=%exe% ../../Lib/idlelib/idle.py %1 %2 %3 %4 %5 %6 %7 %8 %9
-
-echo on
-%cmd%
+ at echo off
+rem start idle
+rem Usage:  idle [-d]
+rem -d   Run Debug build (python_d.exe).  Else release build.
+
+setlocal
+set exe=python
+PATH %PATH%;..\..\..\tcltk\bin
+
+if "%1"=="-d" (set exe=python_d) & shift
+
+set cmd=%exe% ../../Lib/idlelib/idle.py %1 %2 %3 %4 %5 %6 %7 %8 %9
+
+echo on
+%cmd%

Modified: python/branches/pep-3151/PC/VS8.0/kill_python.c
==============================================================================
--- python/branches/pep-3151/PC/VS8.0/kill_python.c	(original)
+++ python/branches/pep-3151/PC/VS8.0/kill_python.c	Sat Feb 26 08:16:32 2011
@@ -106,7 +106,7 @@
         /*
          * XXX TODO: if we really wanted to be fancy, we could check the 
          * modules for all processes (not just the python[_d].exe ones)
-         * and see if any of our DLLs are loaded (i.e. python32[_d].dll),
+         * and see if any of our DLLs are loaded (i.e. python33[_d].dll),
          * as that would also inhibit our ability to rebuild the solution.
          * Not worth loosing sleep over though; for now, a simple check 
          * for just the python executable should be sufficient.

Modified: python/branches/pep-3151/PC/VS8.0/pyproject.vsprops
==============================================================================
--- python/branches/pep-3151/PC/VS8.0/pyproject.vsprops	(original)
+++ python/branches/pep-3151/PC/VS8.0/pyproject.vsprops	Sat Feb 26 08:16:32 2011
@@ -38,7 +38,7 @@
 	/>
 	<UserMacro
 		Name="PyDllName"
-		Value="python32"
+		Value="python33"
 	/>
 	<UserMacro
 		Name="PythonExe"

Modified: python/branches/pep-3151/PC/VS8.0/rt.bat
==============================================================================
--- python/branches/pep-3151/PC/VS8.0/rt.bat	(original)
+++ python/branches/pep-3151/PC/VS8.0/rt.bat	Sat Feb 26 08:16:32 2011
@@ -1,52 +1,52 @@
- at echo off
-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 -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/.
-rem      -q runs the tests just once, and without deleting .py[co] files.
-rem All leading instances of these switches are shifted off, and
-rem whatever remains is passed to regrtest.py.  For example,
-rem     rt -O -d -x test_thread
-rem runs
-rem     python_d -O ../lib/test/regrtest.py -x test_thread
-rem twice, and
-rem     rt -q -g test_binascii
-rem runs
-rem     python_d ../lib/test/regrtest.py -g test_binascii
-rem to generate the expected-output file for binascii quickly.
-rem
-rem Confusing:  if you want to pass a comma-separated list, like
-rem     -u network,largefile
-rem then you have to quote it on the rt line, like
-rem     rt -u "network,largefile"
-
-setlocal
-
-set exe=python
-set qmode=
-set dashO=
-PATH %PATH%;%~dp0..\..\..\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
-
-set cmd=%exe% %dashO% -E ../../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9
-if defined qmode goto Qmode
-
-echo Deleting .pyc/.pyo files ...
-%exe% rmpyc.py
-
-echo on
-%cmd%
- at echo off
-
-echo About to run again without deleting .pyc/.pyo first:
-pause
-
-:Qmode
-echo on
-%cmd%
+ at echo off
+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 -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/.
+rem      -q runs the tests just once, and without deleting .py[co] files.
+rem All leading instances of these switches are shifted off, and
+rem whatever remains is passed to regrtest.py.  For example,
+rem     rt -O -d -x test_thread
+rem runs
+rem     python_d -O ../lib/test/regrtest.py -x test_thread
+rem twice, and
+rem     rt -q -g test_binascii
+rem runs
+rem     python_d ../lib/test/regrtest.py -g test_binascii
+rem to generate the expected-output file for binascii quickly.
+rem
+rem Confusing:  if you want to pass a comma-separated list, like
+rem     -u network,largefile
+rem then you have to quote it on the rt line, like
+rem     rt -u "network,largefile"
+
+setlocal
+
+set exe=python
+set qmode=
+set dashO=
+PATH %PATH%;%~dp0..\..\..\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
+
+set cmd=%exe% %dashO% -E ../../lib/test/regrtest.py %1 %2 %3 %4 %5 %6 %7 %8 %9
+if defined qmode goto Qmode
+
+echo Deleting .pyc/.pyo files ...
+%exe% rmpyc.py
+
+echo on
+%cmd%
+ at echo off
+
+echo About to run again without deleting .pyc/.pyo first:
+pause
+
+:Qmode
+echo on
+%cmd%

Modified: python/branches/pep-3151/PC/bdist_wininst/wininst.dsp
==============================================================================
--- python/branches/pep-3151/PC/bdist_wininst/wininst.dsp	(original)
+++ python/branches/pep-3151/PC/bdist_wininst/wininst.dsp	Sat Feb 26 08:16:32 2011
@@ -1,123 +1,123 @@
-# Microsoft Developer Studio Project File - Name="wininst" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Win32 (x86) Application" 0x0101
-
-CFG=wininst - Win32 Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE 
-!MESSAGE NMAKE /f "wininst.mak".
-!MESSAGE 
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE 
-!MESSAGE NMAKE /f "wininst.mak" CFG="wininst - Win32 Debug"
-!MESSAGE 
-!MESSAGE Possible choices for configuration are:
-!MESSAGE 
-!MESSAGE "wininst - Win32 Release" (based on "Win32 (x86) Application")
-!MESSAGE "wininst - Win32 Debug" (based on "Win32 (x86) Application")
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-MTL=midl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "wininst - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "..\..\lib\distutils\command"
-# PROP Intermediate_Dir "temp-release"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /MD /W3 /O1 /I "..\..\Include" /I "..\..\..\zlib-1.2.3" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
-# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x407 /d "NDEBUG"
-# ADD RSC /l 0x407 /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
-# ADD LINK32 ..\..\..\zlib-1.2.3\zlib.lib imagehlp.lib comdlg32.lib ole32.lib comctl32.lib kernel32.lib user32.lib gdi32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"LIBC" /out:"..\..\lib\distutils\command/wininst-6.0.exe"
-
-!ELSEIF  "$(CFG)" == "wininst - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "."
-# PROP Intermediate_Dir "temp-debug"
-# PROP Ignore_Export_Lib 0
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /W3 /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
-# ADD CPP /nologo /MD /W3 /Z7 /Od /I "..\..\Include" /I "..\..\..\zlib-1.2.1" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /FR /YX /FD /c
-# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x407 /d "_DEBUG"
-# ADD RSC /l 0x407 /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 ..\..\..\zlib-1.2.3\zlib.lib imagehlp.lib comdlg32.lib ole32.lib comctl32.lib kernel32.lib user32.lib gdi32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /pdb:none /debug /machine:I386 /nodefaultlib:"LIBC" /out:"..\..\lib\distutils\command/wininst-6.0_d.exe"
-
-!ENDIF 
-
-# Begin Target
-
-# Name "wininst - Win32 Release"
-# Name "wininst - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE=.\extract.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\install.c
-# End Source File
-# Begin Source File
-
-SOURCE=.\install.rc
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# Begin Source File
-
-SOURCE=.\archive.h
-# End Source File
-# End Group
-# Begin Group "Resource Files"
-
-# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-# Begin Source File
-
-SOURCE=.\PythonPowered.bmp
-# End Source File
-# End Group
-# End Target
-# End Project
+# Microsoft Developer Studio Project File - Name="wininst" - Package Owner=<4>
+# Microsoft Developer Studio Generated Build File, Format Version 6.00
+# ** DO NOT EDIT **
+
+# TARGTYPE "Win32 (x86) Application" 0x0101
+
+CFG=wininst - Win32 Debug
+!MESSAGE This is not a valid makefile. To build this project using NMAKE,
+!MESSAGE use the Export Makefile command and run
+!MESSAGE 
+!MESSAGE NMAKE /f "wininst.mak".
+!MESSAGE 
+!MESSAGE You can specify a configuration when running NMAKE
+!MESSAGE by defining the macro CFG on the command line. For example:
+!MESSAGE 
+!MESSAGE NMAKE /f "wininst.mak" CFG="wininst - Win32 Debug"
+!MESSAGE 
+!MESSAGE Possible choices for configuration are:
+!MESSAGE 
+!MESSAGE "wininst - Win32 Release" (based on "Win32 (x86) Application")
+!MESSAGE "wininst - Win32 Debug" (based on "Win32 (x86) Application")
+!MESSAGE 
+
+# Begin Project
+# PROP AllowPerConfigDependencies 0
+# PROP Scc_ProjName ""
+# PROP Scc_LocalPath ""
+CPP=cl.exe
+MTL=midl.exe
+RSC=rc.exe
+
+!IF  "$(CFG)" == "wininst - Win32 Release"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 0
+# PROP BASE Output_Dir "Release"
+# PROP BASE Intermediate_Dir "Release"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 0
+# PROP Output_Dir "..\..\lib\distutils\command"
+# PROP Intermediate_Dir "temp-release"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
+# ADD CPP /nologo /MD /W3 /O1 /I "..\..\Include" /I "..\..\..\zlib-1.2.3" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /c
+# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x407 /d "NDEBUG"
+# ADD RSC /l 0x407 /d "NDEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /machine:I386
+# ADD LINK32 ..\..\..\zlib-1.2.3\zlib.lib imagehlp.lib comdlg32.lib ole32.lib comctl32.lib kernel32.lib user32.lib gdi32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /machine:I386 /nodefaultlib:"LIBC" /out:"..\..\lib\distutils\command/wininst-6.0.exe"
+
+!ELSEIF  "$(CFG)" == "wininst - Win32 Debug"
+
+# PROP BASE Use_MFC 0
+# PROP BASE Use_Debug_Libraries 1
+# PROP BASE Output_Dir "Debug"
+# PROP BASE Intermediate_Dir "Debug"
+# PROP BASE Target_Dir ""
+# PROP Use_MFC 0
+# PROP Use_Debug_Libraries 1
+# PROP Output_Dir "."
+# PROP Intermediate_Dir "temp-debug"
+# PROP Ignore_Export_Lib 0
+# PROP Target_Dir ""
+# ADD BASE CPP /nologo /W3 /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /YX /FD /GZ /c
+# ADD CPP /nologo /MD /W3 /Z7 /Od /I "..\..\Include" /I "..\..\..\zlib-1.2.1" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /FR /YX /FD /c
+# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
+# ADD BASE RSC /l 0x407 /d "_DEBUG"
+# ADD RSC /l 0x407 /d "_DEBUG"
+BSC32=bscmake.exe
+# ADD BASE BSC32 /nologo
+# ADD BSC32 /nologo
+LINK32=link.exe
+# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /subsystem:windows /debug /machine:I386 /pdbtype:sept
+# ADD LINK32 ..\..\..\zlib-1.2.3\zlib.lib imagehlp.lib comdlg32.lib ole32.lib comctl32.lib kernel32.lib user32.lib gdi32.lib advapi32.lib shell32.lib /nologo /subsystem:windows /pdb:none /debug /machine:I386 /nodefaultlib:"LIBC" /out:"..\..\lib\distutils\command/wininst-6.0_d.exe"
+
+!ENDIF 
+
+# Begin Target
+
+# Name "wininst - Win32 Release"
+# Name "wininst - Win32 Debug"
+# Begin Group "Source Files"
+
+# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
+# Begin Source File
+
+SOURCE=.\extract.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\install.c
+# End Source File
+# Begin Source File
+
+SOURCE=.\install.rc
+# End Source File
+# End Group
+# Begin Group "Header Files"
+
+# PROP Default_Filter "h;hpp;hxx;hm;inl"
+# Begin Source File
+
+SOURCE=.\archive.h
+# End Source File
+# End Group
+# Begin Group "Resource Files"
+
+# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
+# Begin Source File
+
+SOURCE=.\PythonPowered.bmp
+# End Source File
+# End Group
+# End Target
+# End Project

Modified: python/branches/pep-3151/PC/bdist_wininst/wininst.dsw
==============================================================================
--- python/branches/pep-3151/PC/bdist_wininst/wininst.dsw	(original)
+++ python/branches/pep-3151/PC/bdist_wininst/wininst.dsw	Sat Feb 26 08:16:32 2011
@@ -1,29 +1,29 @@
-Microsoft Developer Studio Workspace File, Format Version 6.00
-# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
-
-###############################################################################
-
-Project: "wininst"=.\wininst.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Global:
-
-Package=<5>
-{{{
-}}}
-
-Package=<3>
-{{{
-}}}
-
-###############################################################################
-
+Microsoft Developer Studio Workspace File, Format Version 6.00
+# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
+
+###############################################################################
+
+Project: "wininst"=.\wininst.dsp - Package Owner=<4>
+
+Package=<5>
+{{{
+}}}
+
+Package=<4>
+{{{
+}}}
+
+###############################################################################
+
+Global:
+
+Package=<5>
+{{{
+}}}
+
+Package=<3>
+{{{
+}}}
+
+###############################################################################
+

Modified: python/branches/pep-3151/PC/example_nt/example.vcproj
==============================================================================
--- python/branches/pep-3151/PC/example_nt/example.vcproj	(original)
+++ python/branches/pep-3151/PC/example_nt/example.vcproj	Sat Feb 26 08:16:32 2011
@@ -39,7 +39,7 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalOptions="/export:initexample"
-				AdditionalDependencies="odbc32.lib odbccp32.lib python26.lib"
+				AdditionalDependencies="odbc32.lib odbccp32.lib python33.lib"
 				OutputFile=".\Release/example.pyd"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
@@ -105,7 +105,7 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalOptions="/export:initexample"
-				AdditionalDependencies="odbc32.lib odbccp32.lib python26_d.lib"
+				AdditionalDependencies="odbc32.lib odbccp32.lib python33_d.lib"
 				OutputFile=".\Debug/example_d.pyd"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"

Modified: python/branches/pep-3151/PC/getpathp.c
==============================================================================
--- python/branches/pep-3151/PC/getpathp.c	(original)
+++ python/branches/pep-3151/PC/getpathp.c	Sat Feb 26 08:16:32 2011
@@ -707,3 +707,38 @@
         calculate_path();
     return progpath;
 }
+
+/* Load python3.dll before loading any extension module that might refer 
+   to it. That way, we can be sure that always the python3.dll corresponding 
+   to this python DLL is loaded, not a python3.dll that might be on the path
+   by chance.
+   Return whether the DLL was found.
+*/
+static int python3_checked = 0;
+static HANDLE hPython3;
+int
+_Py_CheckPython3()
+{
+    wchar_t py3path[MAXPATHLEN+1];
+    wchar_t *s;
+    if (python3_checked)
+        return hPython3 != NULL;
+    python3_checked = 1;
+
+    /* If there is a python3.dll next to the python3y.dll,
+       assume this is a build tree; use that DLL */
+    wcscpy(py3path, dllpath);
+    s = wcsrchr(py3path, L'\\');
+    if (!s)
+        s = py3path;
+    wcscpy(s, L"\\python3.dll");
+    hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
+    if (hPython3 != NULL)
+        return 1;
+
+    /* Check sys.prefix\DLLs\python3.dll */
+    wcscpy(py3path, Py_GetPrefix());
+    wcscat(py3path, L"\\DLLs\\python3.dll");
+    hPython3 = LoadLibraryExW(py3path, NULL, LOAD_WITH_ALTERED_SEARCH_PATH);
+    return hPython3 != NULL;
+}

Modified: python/branches/pep-3151/PC/import_nt.c
==============================================================================
--- python/branches/pep-3151/PC/import_nt.c	(original)
+++ python/branches/pep-3151/PC/import_nt.c	Sat Feb 26 08:16:32 2011
@@ -15,10 +15,10 @@
 /* a string loaded from the DLL at startup */
 extern const char *PyWin_DLLVersionString;
 
-FILE *PyWin_FindRegisteredModule(const char *moduleName,
-                                 struct filedescr **ppFileDesc,
-                                 char *pathBuf,
-                                 Py_ssize_t pathLen)
+FILE *_PyWin_FindRegisteredModule(const char *moduleName,
+                                  struct filedescr **ppFileDesc,
+                                  char *pathBuf,
+                                  Py_ssize_t pathLen)
 {
     char *moduleKey;
     const char keyPrefix[] = "Software\\Python\\PythonCore\\";

Modified: python/branches/pep-3151/PC/os2emx/Makefile
==============================================================================
--- python/branches/pep-3151/PC/os2emx/Makefile	(original)
+++ python/branches/pep-3151/PC/os2emx/Makefile	Sat Feb 26 08:16:32 2011
@@ -237,7 +237,7 @@
 
 # Output file names
 PYTHON_VER=	2.6
-PYTHON_LIB=	python26
+PYTHON_LIB=	python33
 PYTHON.LIB=	$(PYTHON_LIB)_s$A
 PYTHON.IMPLIB=	$(PYTHON_LIB)$A
 ifeq ($(EXEOMF),yes)

Modified: python/branches/pep-3151/PC/os2emx/README.os2emx
==============================================================================
--- python/branches/pep-3151/PC/os2emx/README.os2emx	(original)
+++ python/branches/pep-3151/PC/os2emx/README.os2emx	Sat Feb 26 08:16:32 2011
@@ -305,7 +305,7 @@
    to be installed in a directory other than the PYTHONHOME directory, set 
    the value of the Makefile variable EXE_DIR to the appropriate directory.
 
-3. If you wish the Python core DLL (python26.dll) to be installed in a 
+3. If you wish the Python core DLL (python33.dll) to be installed in a 
    directory other than the directory in which the Python executables are 
    installed (by default, the PYTHONHOME directory), set the value of the 
    Makefile variable DLL_DIR to the appropriate directory.  This DLL must 

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

Modified: python/branches/pep-3151/PC/pyconfig.h
==============================================================================
--- python/branches/pep-3151/PC/pyconfig.h	(original)
+++ python/branches/pep-3151/PC/pyconfig.h	Sat Feb 26 08:16:32 2011
@@ -318,10 +318,12 @@
 			/* So MSVC users need not specify the .lib file in
 			their Makefile (other compilers are generally
 			taken care of by distutils.) */
-#			ifdef _DEBUG
-#				pragma comment(lib,"python32_d.lib")
+#			if defined(_DEBUG)
+#				pragma comment(lib,"python33_d.lib")
+#			elif defined(Py_LIMITED_API)
+#				pragma comment(lib,"python3.lib")
 #			else
-#				pragma comment(lib,"python32.lib")
+#				pragma comment(lib,"python33.lib")
 #			endif /* _DEBUG */
 #		endif /* _MSC_VER */
 #	endif /* Py_BUILD_CORE */

Modified: python/branches/pep-3151/PC/python_nt.rc
==============================================================================
--- python/branches/pep-3151/PC/python_nt.rc	(original)
+++ python/branches/pep-3151/PC/python_nt.rc	Sat Feb 26 08:16:32 2011
@@ -61,7 +61,7 @@
             VALUE "FileDescription", "Python Core\0"
             VALUE "FileVersion", PYTHON_VERSION
             VALUE "InternalName", "Python DLL\0"
-            VALUE "LegalCopyright", "Copyright © 2001-2010 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.\0"
+            VALUE "LegalCopyright", "Copyright © 2001-2011 Python Software Foundation. Copyright © 2000 BeOpen.com. Copyright © 1995-2001 CNRI. Copyright © 1991-1995 SMC.\0"
             VALUE "OriginalFilename", PYTHON_DLL_NAME "\0"
             VALUE "ProductName", "Python\0"
             VALUE "ProductVersion", PYTHON_VERSION

Modified: python/branches/pep-3151/PCbuild/build_ssl.bat
==============================================================================
--- python/branches/pep-3151/PCbuild/build_ssl.bat	(original)
+++ python/branches/pep-3151/PCbuild/build_ssl.bat	Sat Feb 26 08:16:32 2011
@@ -2,10 +2,10 @@
 if not defined HOST_PYTHON (
   if %1 EQU Debug (
     set HOST_PYTHON=python_d.exe
-    if not exist python31_d.dll exit 1
+    if not exist python33_d.dll exit 1
   ) ELSE (
     set HOST_PYTHON=python.exe
-    if not exist python31.dll exit 1
+    if not exist python33.dll exit 1
   )
 )
 %HOST_PYTHON% build_ssl.py %1 %2 %3

Modified: python/branches/pep-3151/PCbuild/build_tkinter.py
==============================================================================
--- python/branches/pep-3151/PCbuild/build_tkinter.py	(original)
+++ python/branches/pep-3151/PCbuild/build_tkinter.py	Sat Feb 26 08:16:32 2011
@@ -11,8 +11,8 @@
 here = os.path.abspath(os.path.dirname(__file__))
 par = os.path.pardir
 
-TCL = "tcl8.5.2"
-TK = "tk8.5.2"
+TCL = "tcl8.5.9"
+TK = "tk8.5.9"
 TIX = "tix-8.4.3.x"
 
 ROOT = os.path.abspath(os.path.join(here, par, par))

Modified: python/branches/pep-3151/PCbuild/kill_python.c
==============================================================================
--- python/branches/pep-3151/PCbuild/kill_python.c	(original)
+++ python/branches/pep-3151/PCbuild/kill_python.c	Sat Feb 26 08:16:32 2011
@@ -106,7 +106,7 @@
         /*
          * XXX TODO: if we really wanted to be fancy, we could check the 
          * modules for all processes (not just the python[_d].exe ones)
-         * and see if any of our DLLs are loaded (i.e. python32[_d].dll),
+         * and see if any of our DLLs are loaded (i.e. python33[_d].dll),
          * as that would also inhibit our ability to rebuild the solution.
          * Not worth loosing sleep over though; for now, a simple check 
          * for just the python executable should be sufficient.

Modified: python/branches/pep-3151/PCbuild/make_buildinfo.c
==============================================================================
--- python/branches/pep-3151/PCbuild/make_buildinfo.c	(original)
+++ python/branches/pep-3151/PCbuild/make_buildinfo.c	Sat Feb 26 08:16:32 2011
@@ -52,9 +52,9 @@
     if (_stat(command+1, &st) < 0)
         /* subwcrev.exe not part of the release */
         return 0;
-    strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c ");
-    strcat_s(command, CMD_SIZE, tmppath);
-    strcat_s(command, CMD_SIZE, "getbuildinfo2.c");
+    strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c \"");
+    strcat_s(command, CMD_SIZE, tmppath); /* quoted tmppath */
+    strcat_s(command, CMD_SIZE, "getbuildinfo2.c\"");
     puts(command); fflush(stdout);
     if (system(command) < 0)
         return 0;
@@ -91,23 +91,36 @@
     if (argc > 2) {
         tmpdir = argv[2];
         strcat_s(tmppath, _countof(tmppath), tmpdir);
+        /* Hack fix for bad command line:  If the command is issued like this:
+         * $(SolutionDir)make_buildinfo.exe" Debug "$(IntDir)"
+         * we will get a trailing quote because IntDir ends with a backslash that then
+         * escapes the final ".  To simplify the life for developers, catch that problem
+         * here by cutting it off.
+         * The proper command line, btw is:
+         * $(SolutionDir)make_buildinfo.exe" Debug "$(IntDir)\"
+         * Hooray for command line parsing on windows.
+         */
+        if (strlen(tmppath) > 0 && tmppath[strlen(tmppath)-1] == '"')
+            tmppath[strlen(tmppath)-1] = '\0';
         strcat_s(tmppath, _countof(tmppath), "\\");
     }
 
     if ((do_unlink = make_buildinfo2(tmppath))) {
+        strcat_s(command, CMD_SIZE, "\"");
         strcat_s(command, CMD_SIZE, tmppath);
-        strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV ");
+        strcat_s(command, CMD_SIZE, "getbuildinfo2.c\" -DSUBWCREV ");
     } else
         strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c");
-    strcat_s(command, CMD_SIZE, " -Fo");
+    strcat_s(command, CMD_SIZE, " -Fo\"");
     strcat_s(command, CMD_SIZE, tmppath);
-    strcat_s(command, CMD_SIZE, "getbuildinfo.o -I..\\Include -I..\\PC");
+    strcat_s(command, CMD_SIZE, "getbuildinfo.o\" -I..\\Include -I..\\PC");
     puts(command); fflush(stdout);
     result = system(command);
     if (do_unlink) {
         command[0] = '\0';
+        strcat_s(command, CMD_SIZE, "\"");
         strcat_s(command, CMD_SIZE, tmppath);
-        strcat_s(command, CMD_SIZE, "getbuildinfo2.c");
+        strcat_s(command, CMD_SIZE, "getbuildinfo2.c\"");
         _unlink(command);
     }
     if (result < 0)

Modified: python/branches/pep-3151/PCbuild/pcbuild.sln
==============================================================================
--- python/branches/pep-3151/PCbuild/pcbuild.sln	(original)
+++ python/branches/pep-3151/PCbuild/pcbuild.sln	Sat Feb 26 08:16:32 2011
@@ -73,8 +73,8 @@
 	ProjectSection(ProjectDependencies) = postProject
 		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9} = {B11D750F-CD1F-4A96-85CE-E69A5C5259F9}
 		{86937F53-C189-40EF-8CE8-8759D8E7D480} = {86937F53-C189-40EF-8CE8-8759D8E7D480}
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
 		{E5B04CC0-EB4C-42AB-B4DC-18EF95F864B0} = {E5B04CC0-EB4C-42AB-B4DC-18EF95F864B0}
+		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_testcapi", "_testcapi.vcproj", "{6901D91C-6E48-4BB7-9FEC-700C8131DF1D}"
@@ -112,8 +112,8 @@
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "_hashlib", "_hashlib.vcproj", "{447F05A8-F581-4CAC-A466-5AC7936E207E}"
 	ProjectSection(ProjectDependencies) = postProject
 		{B11D750F-CD1F-4A96-85CE-E69A5C5259F9} = {B11D750F-CD1F-4A96-85CE-E69A5C5259F9}
-		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
 		{E5B04CC0-EB4C-42AB-B4DC-18EF95F864B0} = {E5B04CC0-EB4C-42AB-B4DC-18EF95F864B0}
+		{CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26} = {CF7AC3D1-E2DF-41D2-BEA6-1E2556CDEA26}
 	EndProjectSection
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sqlite3", "sqlite3.vcproj", "{A1A295E5-463C-437F-81CA-1F32367685DA}"
@@ -133,6 +133,10 @@
 EndProject
 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "kill_python", "kill_python.vcproj", "{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}"
 EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "python3dll", "python3dll.vcproj", "{885D4898-D08D-4091-9C40-C700CFE3FC5A}"
+EndProject
+Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "xxlimited", "xxlimited.vcproj", "{F749B822-B489-4CA5-A3AD-CE078F5F338A}"
+EndProject
 Global
 	GlobalSection(SolutionConfigurationPlatforms) = preSolution
 		Debug|Win32 = Debug|Win32
@@ -553,6 +557,37 @@
 		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|Win32.Build.0 = Release|Win32
 		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|x64.ActiveCfg = Release|x64
 		{6DE10744-E396-40A5-B4E2-1B69AA7C8D31}.Release|x64.Build.0 = Release|x64
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.Debug|Win32.ActiveCfg = PGInstrument|Win32
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.Debug|x64.ActiveCfg = Debug|x64
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.Debug|x64.Build.0 = Debug|x64
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.PGInstrument|Win32.ActiveCfg = PGInstrument|Win32
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.PGInstrument|Win32.Build.0 = PGInstrument|Win32
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.PGInstrument|x64.ActiveCfg = Release|x64
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.PGInstrument|x64.Build.0 = Release|x64
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.PGUpdate|Win32.ActiveCfg = PGUpdate|Win32
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.PGUpdate|Win32.Build.0 = PGUpdate|Win32
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.PGUpdate|x64.ActiveCfg = Release|x64
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.PGUpdate|x64.Build.0 = Release|x64
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.Release|Win32.ActiveCfg = Release|Win32
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.Release|Win32.Build.0 = Release|Win32
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.Release|x64.ActiveCfg = Release|x64
+		{885D4898-D08D-4091-9C40-C700CFE3FC5A}.Release|x64.Build.0 = Release|x64
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.Debug|Win32.ActiveCfg = Debug|Win32
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.Debug|Win32.Build.0 = Debug|Win32
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.Debug|x64.ActiveCfg = Debug|x64
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.Debug|x64.Build.0 = Debug|x64
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.PGInstrument|Win32.ActiveCfg = Release|Win32
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.PGInstrument|Win32.Build.0 = Release|Win32
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.PGInstrument|x64.ActiveCfg = Release|x64
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.PGInstrument|x64.Build.0 = Release|x64
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.PGUpdate|Win32.ActiveCfg = Release|Win32
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.PGUpdate|Win32.Build.0 = Release|Win32
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.PGUpdate|x64.ActiveCfg = Release|x64
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.PGUpdate|x64.Build.0 = Release|x64
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.Release|Win32.ActiveCfg = Release|Win32
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.Release|Win32.Build.0 = Release|Win32
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.Release|x64.ActiveCfg = Release|x64
+		{F749B822-B489-4CA5-A3AD-CE078F5F338A}.Release|x64.Build.0 = Release|x64
 	EndGlobalSection
 	GlobalSection(SolutionProperties) = preSolution
 		HideSolutionNode = FALSE

Modified: python/branches/pep-3151/PCbuild/pyproject.vsprops
==============================================================================
--- python/branches/pep-3151/PCbuild/pyproject.vsprops	(original)
+++ python/branches/pep-3151/PCbuild/pyproject.vsprops	Sat Feb 26 08:16:32 2011
@@ -38,7 +38,7 @@
 	/>
 	<UserMacro
 		Name="PyDllName"
-		Value="python32"
+		Value="python33"
 	/>
 	<UserMacro
 		Name="PythonExe"
@@ -50,7 +50,7 @@
 	/>
 	<UserMacro
 		Name="sqlite3Dir"
-		Value="$(externalsDir)\sqlite-3.6.21"
+		Value="$(externalsDir)\sqlite-3.7.4"
 	/>
 	<UserMacro
 		Name="bz2Dir"

Modified: python/branches/pep-3151/PCbuild/pythoncore.vcproj
==============================================================================
--- python/branches/pep-3151/PCbuild/pythoncore.vcproj	(original)
+++ python/branches/pep-3151/PCbuild/pythoncore.vcproj	Sat Feb 26 08:16:32 2011
@@ -59,11 +59,11 @@
 			<Tool
 				Name="VCPreLinkEventTool"
 				Description="Generate build information..."
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release $(IntDir)"
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release &quot;$(IntDir)\&quot;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(IntDir)\getbuildinfo.o"
+				AdditionalDependencies="&quot;$(IntDir)getbuildinfo.o&quot;"
 				OutputFile="$(OutDir)\$(PyDllName).dll"
 				IgnoreDefaultLibraryNames="libc"
 				ProgramDatabaseFile="$(OutDir)$(PyDllName).pdb"
@@ -134,11 +134,11 @@
 			<Tool
 				Name="VCPreLinkEventTool"
 				Description="Generate build information..."
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release $(IntDir)"
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release &quot;$(IntDir)\&quot;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(IntDir)\getbuildinfo.o"
+				AdditionalDependencies="&quot;$(IntDir)getbuildinfo.o&quot;"
 				OutputFile="$(OutDir)\$(PyDllName).dll"
 				IgnoreDefaultLibraryNames="libc"
 				ProgramDatabaseFile="$(OutDir)$(PyDllName).pdb"
@@ -212,11 +212,11 @@
 			<Tool
 				Name="VCPreLinkEventTool"
 				Description="Generate build information..."
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Debug $(IntDir)"
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Debug &quot;$(IntDir)\&quot;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(IntDir)\getbuildinfo.o"
+				AdditionalDependencies="&quot;$(IntDir)getbuildinfo.o&quot;"
 				OutputFile="$(OutDir)\$(PyDllName)_d.dll"
 				IgnoreDefaultLibraryNames="libc"
 				ProgramDatabaseFile="$(OutDir)$(PyDllName)_d.pdb"
@@ -290,11 +290,11 @@
 			<Tool
 				Name="VCPreLinkEventTool"
 				Description="Generate build information..."
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Debug $(IntDir)"
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Debug &quot;$(IntDir)\&quot;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(IntDir)\getbuildinfo.o"
+				AdditionalDependencies="&quot;$(IntDir)getbuildinfo.o&quot;"
 				OutputFile="$(OutDir)\$(PyDllName)_d.dll"
 				IgnoreDefaultLibraryNames="libc"
 				ProgramDatabaseFile="$(OutDir)$(PyDllName)_d.pdb"
@@ -364,11 +364,11 @@
 			<Tool
 				Name="VCPreLinkEventTool"
 				Description="Generate build information..."
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release $(IntDir)"
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release &quot;$(IntDir)\&quot;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(IntDir)\getbuildinfo.o"
+				AdditionalDependencies="&quot;$(IntDir)getbuildinfo.o&quot;"
 				OutputFile="$(OutDir)\$(PyDllName).dll"
 				IgnoreDefaultLibraryNames="libc"
 				ProgramDatabaseFile="$(OutDir)$(PyDllName).pdb"
@@ -439,11 +439,11 @@
 			<Tool
 				Name="VCPreLinkEventTool"
 				Description="Generate build information..."
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release $(IntDir)"
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release &quot;$(IntDir)\&quot;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(IntDir)\getbuildinfo.o"
+				AdditionalDependencies="&quot;$(IntDir)getbuildinfo.o&quot;"
 				OutputFile="$(OutDir)\$(PyDllName).dll"
 				IgnoreDefaultLibraryNames="libc"
 				ProgramDatabaseFile="$(OutDir)$(PyDllName).pdb"
@@ -514,11 +514,11 @@
 			<Tool
 				Name="VCPreLinkEventTool"
 				Description="Generate build information..."
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release ($IntDir)"
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release &quot;$(IntDir)\&quot;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(IntDir)\getbuildinfo.o"
+				AdditionalDependencies="&quot;$(IntDir)getbuildinfo.o&quot;"
 				OutputFile="$(OutDir)\$(PyDllName).dll"
 				IgnoreDefaultLibraryNames="libc"
 				ProgramDatabaseFile="$(OutDir)$(PyDllName).pdb"
@@ -589,11 +589,11 @@
 			<Tool
 				Name="VCPreLinkEventTool"
 				Description="Generate build information..."
-				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release $(IntDir)"
+				CommandLine="&quot;$(SolutionDir)make_buildinfo.exe&quot; Release &quot;$(IntDir)\&quot;"
 			/>
 			<Tool
 				Name="VCLinkerTool"
-				AdditionalDependencies="$(IntDir)\getbuildinfo.o"
+				AdditionalDependencies="&quot;$(IntDir)getbuildinfo.o&quot;"
 				OutputFile="$(OutDir)\$(PyDllName).dll"
 				IgnoreDefaultLibraryNames="libc"
 				ProgramDatabaseFile="$(OutDir)$(PyDllName).pdb"

Modified: python/branches/pep-3151/PCbuild/readme.txt
==============================================================================
--- python/branches/pep-3151/PCbuild/readme.txt	(original)
+++ python/branches/pep-3151/PCbuild/readme.txt	Sat Feb 26 08:16:32 2011
@@ -37,7 +37,7 @@
    running a Python core buildbot test slave; see SUBPROJECTS below)
 
 When using the Debug setting, the output files have a _d added to
-their name:  python32_d.dll, python_d.exe, parser_d.pyd, and so on. Both
+their name:  python33_d.dll, python_d.exe, parser_d.pyd, and so on. Both
 the build and rt batch files accept a -d option for debug builds.
 
 The 32bit builds end up in the solution folder PCbuild while the x64 builds
@@ -104,7 +104,7 @@
 
 Python-controlled subprojects that wrap external projects:
 _sqlite3
-    Wraps SQLite 3.6.21, which is currently built by sqlite3.vcproj (see below).
+    Wraps SQLite 3.7.4, which is currently built by sqlite3.vcproj (see below).
 _tkinter
     Wraps the Tk windowing system.  Unlike _sqlite3, there's no
     corresponding tcltk.vcproj-type project that builds Tcl/Tk from vcproj's

Modified: python/branches/pep-3151/Parser/asdl_c.py
==============================================================================
--- python/branches/pep-3151/Parser/asdl_c.py	(original)
+++ python/branches/pep-3151/Parser/asdl_c.py	Sat Feb 26 08:16:32 2011
@@ -365,20 +365,18 @@
         self.emit("int", 0)
         self.emit("obj2ast_%s(PyObject* obj, %s* out, PyArena* arena)" % (name, ctype), 0)
         self.emit("{", 0)
-        self.emit("PyObject* tmp = NULL;", 1)
         self.emit("int isinstance;", 1)
         self.emit("", 0)
 
-    def sumTrailer(self, name):
+    def sumTrailer(self, name, add_label=False):
         self.emit("", 0)
-        self.emit("tmp = PyObject_Repr(obj);", 1)
         # there's really nothing more we can do if this fails ...
-        self.emit("if (tmp == NULL) goto failed;", 1)
-        error = "expected some sort of %s, but got %%.400s" % name
-        format = "PyErr_Format(PyExc_TypeError, \"%s\", PyBytes_AS_STRING(tmp));"
+        error = "expected some sort of %s, but got %%R" % name
+        format = "PyErr_Format(PyExc_TypeError, \"%s\", obj);"
         self.emit(format % error, 1, reflow=False)
-        self.emit("failed:", 0)
-        self.emit("Py_XDECREF(tmp);", 1)
+        if add_label:
+            self.emit("failed:", 1)
+            self.emit("Py_XDECREF(tmp);", 1)
         self.emit("return 1;", 1)
         self.emit("}", 0)
         self.emit("", 0)
@@ -403,6 +401,7 @@
 
     def complexSum(self, sum, name):
         self.funcHeader(name)
+        self.emit("PyObject *tmp = NULL;", 1)
         for a in sum.attributes:
             self.visitAttributeDeclaration(a, name, sum=sum)
         self.emit("", 0)
@@ -430,7 +429,7 @@
             self.emit("if (*out == NULL) goto failed;", 2)
             self.emit("return 0;", 2)
             self.emit("}", 1)
-        self.sumTrailer(name)
+        self.sumTrailer(name, True)
 
     def visitAttributeDeclaration(self, a, name, sum=sum):
         ctype = get_c_type(a.type)

Modified: python/branches/pep-3151/Parser/parsetok.c
==============================================================================
--- python/branches/pep-3151/Parser/parsetok.c	(original)
+++ python/branches/pep-3151/Parser/parsetok.c	Sat Feb 26 08:16:32 2011
@@ -127,7 +127,7 @@
 {
     parser_state *ps;
     node *n;
-    int started = 0, handling_import = 0, handling_with = 0;
+    int started = 0;
 
     if ((ps = PyParser_New(g, start)) == NULL) {
         fprintf(stderr, "no mem for new parser\n");
@@ -154,7 +154,6 @@
         }
         if (type == ENDMARKER && started) {
             type = NEWLINE; /* Add an extra newline */
-            handling_with = handling_import = 0;
             started = 0;
             /* Add the right number of dedent tokens,
                except if a certain flag is given --

Modified: python/branches/pep-3151/Parser/pgenmain.c
==============================================================================
--- python/branches/pep-3151/Parser/pgenmain.c	(original)
+++ python/branches/pep-3151/Parser/pgenmain.c	Sat Feb 26 08:16:32 2011
@@ -13,6 +13,8 @@
    - check for duplicate definitions of names (instead of fatal err)
 */
 
+#define PGEN
+
 #include "Python.h"
 #include "pgenheaders.h"
 #include "grammar.h"
@@ -27,6 +29,8 @@
 /* Forward */
 grammar *getgrammar(char *filename);
 
+void Py_Exit(int) _Py_NO_RETURN;
+
 void
 Py_Exit(int sts)
 {

Modified: python/branches/pep-3151/Parser/printgrammar.c
==============================================================================
--- python/branches/pep-3151/Parser/printgrammar.c	(original)
+++ python/branches/pep-3151/Parser/printgrammar.c	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,8 @@
 
 /* Print a bunch of C initializers that represent a grammar */
 
+#define PGEN
+
 #include "pgenheaders.h"
 #include "grammar.h"
 

Modified: python/branches/pep-3151/Parser/tokenizer.c
==============================================================================
--- python/branches/pep-3151/Parser/tokenizer.c	(original)
+++ python/branches/pep-3151/Parser/tokenizer.c	Sat Feb 26 08:16:32 2011
@@ -545,6 +545,7 @@
 {
     char *line = NULL;
     int badchar = 0;
+    PyObject *filename;
     for (;;) {
         if (tok->decoding_state == STATE_NORMAL) {
             /* We already have a codec associated with
@@ -585,12 +586,16 @@
     if (badchar) {
         /* Need to add 1 to the line number, since this line
            has not been counted, yet.  */
-        PyErr_Format(PyExc_SyntaxError,
-            "Non-UTF-8 code starting with '\\x%.2x' "
-            "in file %.200s on line %i, "
-            "but no encoding declared; "
-            "see http://python.org/dev/peps/pep-0263/ for details",
-            badchar, tok->filename, tok->lineno + 1);
+        filename = PyUnicode_DecodeFSDefault(tok->filename);
+        if (filename != NULL) {
+            PyErr_Format(PyExc_SyntaxError,
+                    "Non-UTF-8 code starting with '\\x%.2x' "
+                    "in file %U on line %i, "
+                    "but no encoding declared; "
+                    "see http://python.org/dev/peps/pep-0263/ for details",
+                    badchar, filename, tok->lineno + 1);
+            Py_DECREF(filename);
+        }
         return error_ret(tok);
     }
 #endif
@@ -888,6 +893,13 @@
         if (tok->prompt != NULL) {
             char *newtok = PyOS_Readline(stdin, stdout, tok->prompt);
 #ifndef PGEN
+            if (newtok != NULL) {
+                char *translated = translate_newlines(newtok, 0, tok);
+                PyMem_FREE(newtok);
+                if (translated == NULL)
+                    return EOF;
+                newtok = translated;
+            }
             if (tok->encoding && newtok && *newtok) {
                 /* Recode to UTF-8 */
                 Py_ssize_t buflen;

Modified: python/branches/pep-3151/Python/Python-ast.c
==============================================================================
--- python/branches/pep-3151/Python/Python-ast.c	(original)
+++ python/branches/pep-3151/Python/Python-ast.c	Sat Feb 26 08:16:32 2011
@@ -3374,9 +3374,9 @@
 int
 obj2ast_mod(PyObject* obj, mod_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
+        PyObject *tmp = NULL;
 
         if (obj == Py_None) {
                 *out = NULL;
@@ -3514,10 +3514,8 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of mod, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
+        PyErr_Format(PyExc_TypeError, "expected some sort of mod, but got %R", obj);
+        failed:
         Py_XDECREF(tmp);
         return 1;
 }
@@ -3525,9 +3523,9 @@
 int
 obj2ast_stmt(PyObject* obj, stmt_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
+        PyObject *tmp = NULL;
         int lineno;
         int col_offset;
 
@@ -4712,10 +4710,8 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of stmt, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
+        PyErr_Format(PyExc_TypeError, "expected some sort of stmt, but got %R", obj);
+        failed:
         Py_XDECREF(tmp);
         return 1;
 }
@@ -4723,9 +4719,9 @@
 int
 obj2ast_expr(PyObject* obj, expr_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
+        PyObject *tmp = NULL;
         int lineno;
         int col_offset;
 
@@ -5830,10 +5826,8 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of expr, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
+        PyErr_Format(PyExc_TypeError, "expected some sort of expr, but got %R", obj);
+        failed:
         Py_XDECREF(tmp);
         return 1;
 }
@@ -5841,7 +5835,6 @@
 int
 obj2ast_expr_context(PyObject* obj, expr_context_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
         isinstance = PyObject_IsInstance(obj, (PyObject *)Load_type);
@@ -5893,20 +5886,16 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of expr_context, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
-        Py_XDECREF(tmp);
+        PyErr_Format(PyExc_TypeError, "expected some sort of expr_context, but got %R", obj);
         return 1;
 }
 
 int
 obj2ast_slice(PyObject* obj, slice_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
+        PyObject *tmp = NULL;
 
         if (obj == Py_None) {
                 *out = NULL;
@@ -6018,10 +6007,8 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of slice, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
+        PyErr_Format(PyExc_TypeError, "expected some sort of slice, but got %R", obj);
+        failed:
         Py_XDECREF(tmp);
         return 1;
 }
@@ -6029,7 +6016,6 @@
 int
 obj2ast_boolop(PyObject* obj, boolop_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
         isinstance = PyObject_IsInstance(obj, (PyObject *)And_type);
@@ -6049,18 +6035,13 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of boolop, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
-        Py_XDECREF(tmp);
+        PyErr_Format(PyExc_TypeError, "expected some sort of boolop, but got %R", obj);
         return 1;
 }
 
 int
 obj2ast_operator(PyObject* obj, operator_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
         isinstance = PyObject_IsInstance(obj, (PyObject *)Add_type);
@@ -6160,18 +6141,13 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of operator, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
-        Py_XDECREF(tmp);
+        PyErr_Format(PyExc_TypeError, "expected some sort of operator, but got %R", obj);
         return 1;
 }
 
 int
 obj2ast_unaryop(PyObject* obj, unaryop_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
         isinstance = PyObject_IsInstance(obj, (PyObject *)Invert_type);
@@ -6207,18 +6183,13 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of unaryop, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
-        Py_XDECREF(tmp);
+        PyErr_Format(PyExc_TypeError, "expected some sort of unaryop, but got %R", obj);
         return 1;
 }
 
 int
 obj2ast_cmpop(PyObject* obj, cmpop_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
         isinstance = PyObject_IsInstance(obj, (PyObject *)Eq_type);
@@ -6302,11 +6273,7 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of cmpop, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
-        Py_XDECREF(tmp);
+        PyErr_Format(PyExc_TypeError, "expected some sort of cmpop, but got %R", obj);
         return 1;
 }
 
@@ -6377,9 +6344,9 @@
 int
 obj2ast_excepthandler(PyObject* obj, excepthandler_ty* out, PyArena* arena)
 {
-        PyObject* tmp = NULL;
         int isinstance;
 
+        PyObject *tmp = NULL;
         int lineno;
         int col_offset;
 
@@ -6473,10 +6440,8 @@
                 return 0;
         }
 
-        tmp = PyObject_Repr(obj);
-        if (tmp == NULL) goto failed;
-        PyErr_Format(PyExc_TypeError, "expected some sort of excepthandler, but got %.400s", PyBytes_AS_STRING(tmp));
-failed:
+        PyErr_Format(PyExc_TypeError, "expected some sort of excepthandler, but got %R", obj);
+        failed:
         Py_XDECREF(tmp);
         return 1;
 }

Modified: python/branches/pep-3151/Python/_warnings.c
==============================================================================
--- python/branches/pep-3151/Python/_warnings.c	(original)
+++ python/branches/pep-3151/Python/_warnings.c	Sat Feb 26 08:16:32 2011
@@ -783,7 +783,7 @@
 {
     PyObject *res;
     PyObject *message = PyUnicode_FromString(text);
-    PyObject *filename = PyUnicode_FromString(filename_str);
+    PyObject *filename = PyUnicode_DecodeFSDefault(filename_str);
     PyObject *module = NULL;
     int ret = -1;
 

Modified: python/branches/pep-3151/Python/ast.c
==============================================================================
--- python/branches/pep-3151/Python/ast.c	(original)
+++ python/branches/pep-3151/Python/ast.c	Sat Feb 26 08:16:32 2011
@@ -7,7 +7,6 @@
 #include "Python-ast.h"
 #include "grammar.h"
 #include "node.h"
-#include "pyarena.h"
 #include "ast.h"
 #include "token.h"
 #include "parsetok.h"
@@ -3232,7 +3231,6 @@
     const char *end;
 
     if (encoding == NULL) {
-        buf = (char *)s;
         u = NULL;
     } else {
         /* check for integer overflow */

Modified: python/branches/pep-3151/Python/bltinmodule.c
==============================================================================
--- python/branches/pep-3151/Python/bltinmodule.c	(original)
+++ python/branches/pep-3151/Python/bltinmodule.c	Sat Feb 26 08:16:32 2011
@@ -5,7 +5,6 @@
 
 #include "node.h"
 #include "code.h"
-#include "eval.h"
 
 #include <ctype.h>
 
@@ -38,7 +37,7 @@
 {
     PyObject *func, *name, *bases, *mkw, *meta, *prep, *ns, *cell;
     PyObject *cls = NULL;
-    Py_ssize_t nargs, nbases;
+    Py_ssize_t nargs;
 
     assert(args != NULL);
     if (!PyTuple_Check(args)) {
@@ -62,7 +61,6 @@
     bases = PyTuple_GetSlice(args, 2, nargs);
     if (bases == NULL)
         return NULL;
-    nbases = nargs - 2;
 
     if (kwds == NULL) {
         meta = NULL;
@@ -311,6 +309,20 @@
 Return the binary representation of an integer or long integer.");
 
 
+static PyObject *
+builtin_callable(PyObject *self, PyObject *v)
+{
+    return PyBool_FromLong((long)PyCallable_Check(v));
+}
+
+PyDoc_STRVAR(callable_doc,
+"callable(object) -> bool\n\
+\n\
+Return whether the object is callable (i.e., some kind of function).\n\
+Note that classes are callable, as are instances of classes with a\n\
+__call__() method.");
+
+
 typedef struct {
     PyObject_HEAD
     PyObject *func;
@@ -530,19 +542,20 @@
     int mode = -1;
     int dont_inherit = 0;
     int supplied_flags = 0;
+    int optimize = -1;
     int is_ast;
     PyCompilerFlags cf;
     PyObject *cmd;
     static char *kwlist[] = {"source", "filename", "mode", "flags",
-                             "dont_inherit", NULL};
+                             "dont_inherit", "optimize", NULL};
     int start[] = {Py_file_input, Py_eval_input, Py_single_input};
     PyObject *result;
 
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|ii:compile",  kwlist,
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO&s|iii:compile",  kwlist,
                                      &cmd,
                                      PyUnicode_FSConverter, &filename_obj,
                                      &startstr, &supplied_flags,
-                                     &dont_inherit))
+                                     &dont_inherit, &optimize))
         return NULL;
 
     filename = PyBytes_AS_STRING(filename_obj);
@@ -557,6 +570,12 @@
     }
     /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
 
+    if (optimize < -1 || optimize > 2) {
+        PyErr_SetString(PyExc_ValueError,
+                        "compile(): invalid optimize value");
+        goto error;
+    }
+
     if (!dont_inherit) {
         PyEval_MergeCompilerFlags(&cf);
     }
@@ -591,8 +610,8 @@
                 PyArena_Free(arena);
                 goto error;
             }
-            result = (PyObject*)PyAST_Compile(mod, filename,
-                                              &cf, arena);
+            result = (PyObject*)PyAST_CompileEx(mod, filename,
+                                                &cf, optimize, arena);
             PyArena_Free(arena);
         }
         goto finally;
@@ -602,7 +621,7 @@
     if (str == NULL)
         goto error;
 
-    result = Py_CompileStringFlags(str, filename, start[mode], &cf);
+    result = Py_CompileStringExFlags(str, filename, start[mode], &cf, optimize);
     goto finally;
 
 error:
@@ -714,7 +733,7 @@
         "code object passed to eval() may not contain free variables");
             return NULL;
         }
-        return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
+        return PyEval_EvalCode(cmd, globals, locals);
     }
 
     cf.cf_flags = PyCF_SOURCE_IS_UTF8;
@@ -746,7 +765,6 @@
 {
     PyObject *v;
     PyObject *prog, *globals = Py_None, *locals = Py_None;
-    int plain = 0;
 
     if (!PyArg_UnpackTuple(args, "exec", 1, 3, &prog, &globals, &locals))
         return NULL;
@@ -755,7 +773,6 @@
         globals = PyEval_GetGlobals();
         if (locals == Py_None) {
             locals = PyEval_GetLocals();
-            plain = 1;
         }
         if (!globals || !locals) {
             PyErr_SetString(PyExc_SystemError,
@@ -790,7 +807,7 @@
                 "contain free variables");
             return NULL;
         }
-        v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
+        v = PyEval_EvalCode(prog, globals, locals);
     }
     else {
         char *str;
@@ -1601,6 +1618,7 @@
         PyObject *stdin_encoding;
         char *stdin_encoding_str;
         PyObject *result;
+        size_t len;
 
         stdin_encoding = PyObject_GetAttrString(fin, "encoding");
         if (!stdin_encoding)
@@ -1665,19 +1683,23 @@
             Py_DECREF(stdin_encoding);
             return NULL;
         }
-        if (*s == '\0') {
+
+        len = strlen(s);
+        if (len == 0) {
             PyErr_SetNone(PyExc_EOFError);
             result = NULL;
         }
-        else { /* strip trailing '\n' */
-            size_t len = strlen(s);
+        else {
             if (len > PY_SSIZE_T_MAX) {
                 PyErr_SetString(PyExc_OverflowError,
                                 "input: input too long");
                 result = NULL;
             }
             else {
-                result = PyUnicode_Decode(s, len-1, stdin_encoding_str, NULL);
+                len--;   /* strip trailing '\n' */
+                if (len != 0 && s[len-1] == '\r')
+                    len--;   /* strip trailing '\r' */
+                result = PyUnicode_Decode(s, len, stdin_encoding_str, NULL);
             }
         }
         Py_DECREF(stdin_encoding);
@@ -2242,6 +2264,7 @@
     {"any",             builtin_any,        METH_O, any_doc},
     {"ascii",           builtin_ascii,      METH_O, ascii_doc},
     {"bin",             builtin_bin,        METH_O, bin_doc},
+    {"callable",        builtin_callable,   METH_O, callable_doc},
     {"chr",             builtin_chr,        METH_VARARGS, chr_doc},
     {"compile",         (PyCFunction)builtin_compile,    METH_VARARGS | METH_KEYWORDS, compile_doc},
     {"delattr",         builtin_delattr,    METH_VARARGS, delattr_doc},

Modified: python/branches/pep-3151/Python/ceval.c
==============================================================================
--- python/branches/pep-3151/Python/ceval.c	(original)
+++ python/branches/pep-3151/Python/ceval.c	Sat Feb 26 08:16:32 2011
@@ -13,7 +13,6 @@
 
 #include "code.h"
 #include "frameobject.h"
-#include "eval.h"
 #include "opcode.h"
 #include "structmember.h"
 
@@ -27,10 +26,11 @@
 
 typedef unsigned long long uint64;
 
-#if defined(__ppc__) /* <- Don't know if this is the correct symbol; this
-                           section should work for GCC on any PowerPC
-                           platform, irrespective of OS.
-                           POWER?  Who knows :-) */
+/* PowerPC suppport.
+   "__ppc__" appears to be the preprocessor definition to detect on OS X, whereas
+   "__powerpc__" appears to be the correct one for Linux with GCC
+*/
+#if defined(__ppc__) || defined (__powerpc__)
 
 #define READ_TIMESTAMP(var) ppc_getcounter(&var)
 
@@ -756,7 +756,7 @@
 
 
 PyObject *
-PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
+PyEval_EvalCode(PyObject *co, PyObject *globals, PyObject *locals)
 {
     return PyEval_EvalCodeEx(co,
                       globals, locals,
@@ -811,10 +811,6 @@
     unsigned char *first_instr;
     PyObject *names;
     PyObject *consts;
-#if defined(Py_DEBUG) || defined(LLTRACE)
-    /* Make it easier to find out where we are with a debugger */
-    char *filename;
-#endif
 
 /* Computed GOTOs, or
        the-optimization-commonly-but-improperly-known-as-"threaded code"
@@ -1227,18 +1223,6 @@
 #ifdef LLTRACE
     lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
 #endif
-#if defined(Py_DEBUG) || defined(LLTRACE)
-    {
-        PyObject *error_type, *error_value, *error_traceback;
-        PyErr_Fetch(&error_type, &error_value, &error_traceback);
-        filename = _PyUnicode_AsString(co->co_filename);
-        if (filename == NULL && tstate->overflowed) {
-            /* maximum recursion depth exceeded */
-            goto exit_eval_frame;
-        }
-        PyErr_Restore(error_type, error_value, error_traceback);
-    }
-#endif
 
     why = WHY_NOT;
     err = 0;
@@ -2706,7 +2690,7 @@
                 Py_DECREF(*pfunc);
                 *pfunc = self;
                 na++;
-                n++;
+                /* n++; */
             } else
                 Py_INCREF(func);
             sp = stack_pointer;
@@ -3042,7 +3026,7 @@
                                 PyTrace_RETURN, retval)) {
                 Py_XDECREF(retval);
                 retval = NULL;
-                why = WHY_EXCEPTION;
+                /* why = WHY_EXCEPTION; */
             }
         }
     }
@@ -3060,10 +3044,11 @@
    the test in the if statements in Misc/gdbinit (pystack and pystackv). */
 
 PyObject *
-PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals,
+PyEval_EvalCodeEx(PyObject *_co, PyObject *globals, PyObject *locals,
            PyObject **args, int argcount, PyObject **kws, int kwcount,
            PyObject **defs, int defcount, PyObject *kwdefs, PyObject *closure)
 {
+    PyCodeObject* co = (PyCodeObject*)_co;
     register PyFrameObject *f;
     register PyObject *retval = NULL;
     register PyObject **fastlocals, **freevars;
@@ -3969,7 +3954,7 @@
         d = &PyTuple_GET_ITEM(argdefs, 0);
         nd = Py_SIZE(argdefs);
     }
-    return PyEval_EvalCodeEx(co, globals,
+    return PyEval_EvalCodeEx((PyObject*)co, globals,
                              (PyObject *)NULL, (*pp_stack)-n, na,
                              (*pp_stack)-2*nk, nk, d, nd, kwdefs,
                              PyFunction_GET_CLOSURE(func));

Modified: python/branches/pep-3151/Python/ceval_gil.h
==============================================================================
--- python/branches/pep-3151/Python/ceval_gil.h	(original)
+++ python/branches/pep-3151/Python/ceval_gil.h	Sat Feb 26 08:16:32 2011
@@ -334,12 +334,15 @@
 
 static void drop_gil(PyThreadState *tstate)
 {
-    /* NOTE: tstate is allowed to be NULL. */
     if (!_Py_atomic_load_relaxed(&gil_locked))
         Py_FatalError("drop_gil: GIL is not locked");
-    if (tstate != NULL &&
-        tstate != _Py_atomic_load_relaxed(&gil_last_holder))
-        Py_FatalError("drop_gil: wrong thread state");
+    /* tstate is allowed to be NULL (early interpreter init) */
+    if (tstate != NULL) {
+        /* Sub-interpreter support: threads might have been switched
+           under our feet using PyThreadState_Swap(). Fix the GIL last
+           holder variable so that our heuristics work. */
+        _Py_atomic_store_relaxed(&gil_last_holder, tstate);
+    }
 
     MUTEX_LOCK(gil_mutex);
     _Py_ANNOTATE_RWLOCK_RELEASED(&gil_locked, /*is_write=*/1);

Modified: python/branches/pep-3151/Python/compile.c
==============================================================================
--- python/branches/pep-3151/Python/compile.c	(original)
+++ python/branches/pep-3151/Python/compile.c	Sat Feb 26 08:16:32 2011
@@ -25,10 +25,8 @@
 
 #include "Python-ast.h"
 #include "node.h"
-#include "pyarena.h"
 #include "ast.h"
 #include "code.h"
-#include "compile.h"
 #include "symtable.h"
 #include "opcode.h"
 
@@ -141,6 +139,7 @@
     PyFutureFeatures *c_future; /* pointer to module's __future__ */
     PyCompilerFlags *c_flags;
 
+    int c_optimize;              /* optimization level */
     int c_interactive;           /* true if in interactive mode */
     int c_nestlevel;
 
@@ -177,7 +176,7 @@
 static int compiler_in_loop(struct compiler *);
 
 static int inplace_binop(struct compiler *, operator_ty);
-static int expr_constant(expr_ty e);
+static int expr_constant(struct compiler *, expr_ty);
 
 static int compiler_with(struct compiler *, stmt_ty);
 static int compiler_call_helper(struct compiler *c, int n,
@@ -256,8 +255,8 @@
 }
 
 PyCodeObject *
-PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
-              PyArena *arena)
+PyAST_CompileEx(mod_ty mod, const char *filename, PyCompilerFlags *flags,
+                int optimize, PyArena *arena)
 {
     struct compiler c;
     PyCodeObject *co = NULL;
@@ -285,6 +284,7 @@
     c.c_future->ff_features = merged;
     flags->cf_flags = merged;
     c.c_flags = flags;
+    c.c_optimize = (optimize == -1) ? Py_OptimizeFlag : optimize;
     c.c_nestlevel = 0;
 
     c.c_st = PySymtable_Build(mod, filename, c.c_future);
@@ -1151,7 +1151,7 @@
     if (!asdl_seq_LEN(stmts))
         return 1;
     st = (stmt_ty)asdl_seq_GET(stmts, 0);
-    if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
+    if (compiler_isdocstring(st) && c->c_optimize < 2) {
         /* don't generate docstrings if -OO */
         i = 1;
         VISIT(c, expr, st->v.Expr.value);
@@ -1465,7 +1465,7 @@
 
     st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
     docstring = compiler_isdocstring(st);
-    if (docstring && Py_OptimizeFlag < 2)
+    if (docstring && c->c_optimize < 2)
         first_const = st->v.Expr.value->v.Str.s;
     if (compiler_add_o(c, c->u->u_consts, first_const) < 0)      {
         compiler_exit_scope(c);
@@ -1699,7 +1699,7 @@
     if (end == NULL)
         return 0;
 
-    constant = expr_constant(s->v.If.test);
+    constant = expr_constant(c, s->v.If.test);
     /* constant = 0: "if 0"
      * constant = 1: "if 1", "if 2", ...
      * constant = -1: rest */
@@ -1761,7 +1761,7 @@
 compiler_while(struct compiler *c, stmt_ty s)
 {
     basicblock *loop, *orelse, *end, *anchor = NULL;
-    int constant = expr_constant(s->v.While.test);
+    int constant = expr_constant(c, s->v.While.test);
 
     if (constant == 0) {
         if (s->v.While.orelse)
@@ -2213,7 +2213,7 @@
     static PyObject *assertion_error = NULL;
     basicblock *end;
 
-    if (Py_OptimizeFlag)
+    if (c->c_optimize)
         return 1;
     if (assertion_error == NULL) {
         assertion_error = PyUnicode_InternFromString("AssertionError");
@@ -3013,7 +3013,7 @@
  */
 
 static int
-expr_constant(expr_ty e)
+expr_constant(struct compiler *c, expr_ty e)
 {
     char *id;
     switch (e->kind) {
@@ -3031,7 +3031,7 @@
         if (strcmp(id, "False") == 0) return 0;
         if (strcmp(id, "None") == 0) return 0;
         if (strcmp(id, "__debug__") == 0)
-            return ! Py_OptimizeFlag;
+            return ! c->c_optimize;
         /* fall through */
     default:
         return -1;
@@ -4082,3 +4082,13 @@
     assemble_free(&a);
     return co;
 }
+
+#undef PyAST_Compile
+PyAPI_FUNC(PyCodeObject *)
+PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
+              PyArena *arena)
+{
+    return PyAST_CompileEx(mod, filename, flags, -1, arena);
+}
+
+

Modified: python/branches/pep-3151/Python/dtoa.c
==============================================================================
--- python/branches/pep-3151/Python/dtoa.c	(original)
+++ python/branches/pep-3151/Python/dtoa.c	Sat Feb 26 08:16:32 2011
@@ -2055,7 +2055,7 @@
                         + Exp_msk1
                         ;
                     word1(&rv) = 0;
-                    dsign = 0;
+                    /* dsign = 0; */
                     break;
                 }
             }
@@ -2092,7 +2092,7 @@
                     goto undfl;
                 }
             }
-            dsign = 1 - dsign;
+            /* dsign = 1 - dsign; */
             break;
         }
         if ((aadj = ratio(delta, bs)) <= 2.) {

Modified: python/branches/pep-3151/Python/dynload_aix.c
==============================================================================
--- python/branches/pep-3151/Python/dynload_aix.c	(original)
+++ python/branches/pep-3151/Python/dynload_aix.c	Sat Feb 26 08:16:32 2011
@@ -12,7 +12,7 @@
 
 
 #ifdef AIX_GENUINE_CPLUSPLUS
-#include "/usr/lpp/xlC/include/load.h"
+#include <load.h>
 #define aix_load loadAndInit
 #else
 #define aix_load load
@@ -154,7 +154,7 @@
 }
 
 
-dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
+dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname,
                                     const char *pathname, FILE *fp)
 {
     dl_funcptr p;

Modified: python/branches/pep-3151/Python/dynload_dl.c
==============================================================================
--- python/branches/pep-3151/Python/dynload_dl.c	(original)
+++ python/branches/pep-3151/Python/dynload_dl.c	Sat Feb 26 08:16:32 2011
@@ -10,17 +10,17 @@
 extern char *Py_GetProgramName(void);
 
 const struct filedescr _PyImport_DynLoadFiletab[] = {
-	{".o", "rb", C_EXTENSION},
-	{"module.o", "rb", C_EXTENSION},
-	{0, 0}
+    {".o", "rb", C_EXTENSION},
+    {"module.o", "rb", C_EXTENSION},
+    {0, 0}
 };
 
 
-dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
-				    const char *pathname, FILE *fp)
+dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname,
+                                    const char *pathname, FILE *fp)
 {
-	char funcname[258];
+    char funcname[258];
 
-	PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname);
-	return dl_loadmod(Py_GetProgramName(), pathname, funcname);
+    PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname);
+    return dl_loadmod(Py_GetProgramName(), pathname, funcname);
 }

Modified: python/branches/pep-3151/Python/dynload_hpux.c
==============================================================================
--- python/branches/pep-3151/Python/dynload_hpux.c	(original)
+++ python/branches/pep-3151/Python/dynload_hpux.c	Sat Feb 26 08:16:32 2011
@@ -19,7 +19,7 @@
     {0, 0}
 };
 
-dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
+dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname,
                                     const char *pathname, FILE *fp)
 {
     dl_funcptr p;

Modified: python/branches/pep-3151/Python/dynload_next.c
==============================================================================
--- python/branches/pep-3151/Python/dynload_next.c	(original)
+++ python/branches/pep-3151/Python/dynload_next.c	Sat Feb 26 08:16:32 2011
@@ -31,8 +31,8 @@
 #define LINKOPTIONS NSLINKMODULE_OPTION_BINDNOW| \
     NSLINKMODULE_OPTION_RETURN_ON_ERROR|NSLINKMODULE_OPTION_PRIVATE
 #endif
-dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
-                                        const char *pathname, FILE *fp)
+dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname,
+                                    const char *pathname, FILE *fp)
 {
     dl_funcptr p = NULL;
     char funcname[258];

Modified: python/branches/pep-3151/Python/dynload_os2.c
==============================================================================
--- python/branches/pep-3151/Python/dynload_os2.c	(original)
+++ python/branches/pep-3151/Python/dynload_os2.c	Sat Feb 26 08:16:32 2011
@@ -15,7 +15,7 @@
     {0, 0}
 };
 
-dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
+dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname,
                                     const char *pathname, FILE *fp)
 {
     dl_funcptr p;

Modified: python/branches/pep-3151/Python/dynload_shlib.c
==============================================================================
--- python/branches/pep-3151/Python/dynload_shlib.c	(original)
+++ python/branches/pep-3151/Python/dynload_shlib.c	Sat Feb 26 08:16:32 2011
@@ -53,6 +53,8 @@
 #else  /* !__VMS */
     {"." SOABI ".so", "rb", C_EXTENSION},
     {"module." SOABI ".so", "rb", C_EXTENSION},
+    {".abi" PYTHON_ABI_STRING ".so", "rb", C_EXTENSION},
+    {"module.abi" PYTHON_ABI_STRING ".so", "rb", C_EXTENSION},
     {".so", "rb", C_EXTENSION},
     {"module.so", "rb", C_EXTENSION},
 #endif  /* __VMS */
@@ -73,7 +75,7 @@
 static int nhandles = 0;
 
 
-dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
+dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname,
                                     const char *pathname, FILE *fp)
 {
     dl_funcptr p;

Modified: python/branches/pep-3151/Python/dynload_win.c
==============================================================================
--- python/branches/pep-3151/Python/dynload_win.c	(original)
+++ python/branches/pep-3151/Python/dynload_win.c	Sat Feb 26 08:16:32 2011
@@ -134,6 +134,15 @@
                 !strncmp(import_name,"python",6)) {
                 char *pch;
 
+#ifndef _DEBUG
+                /* In a release version, don't claim that python3.dll is
+                   a Python DLL. */
+                if (strcmp(import_name, "python3.dll") == 0) {
+                    import_data += 20;
+                    continue;
+                }
+#endif
+
                 /* Ensure python prefix is followed only
                    by numbers to the end of the basename */
                 pch = import_name + 6;
@@ -162,13 +171,16 @@
     return NULL;
 }
 
-
-dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
+dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname,
                                     const char *pathname, FILE *fp)
 {
     dl_funcptr p;
     char funcname[258], *import_python;
 
+#ifndef _DEBUG
+    _Py_CheckPython3();
+#endif
+
     PyOS_snprintf(funcname, sizeof(funcname), "PyInit_%.200s", shortname);
 
     {

Modified: python/branches/pep-3151/Python/errors.c
==============================================================================
--- python/branches/pep-3151/Python/errors.c	(original)
+++ python/branches/pep-3151/Python/errors.c	Sat Feb 26 08:16:32 2011
@@ -520,7 +520,7 @@
     int ierr,
     const char *filename)
 {
-    PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
+    PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
     PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
                                                                  ierr,
                                                                  name);
@@ -557,7 +557,7 @@
     int ierr,
     const char *filename)
 {
-    PyObject *name = filename ? PyUnicode_FromString(filename) : NULL;
+    PyObject *name = filename ? PyUnicode_DecodeFSDefault(filename) : NULL;
     PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
                                                   PyExc_WindowsError,
                                                   ierr, name);

Modified: python/branches/pep-3151/Python/future.c
==============================================================================
--- python/branches/pep-3151/Python/future.c	(original)
+++ python/branches/pep-3151/Python/future.c	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,6 @@
 #include "token.h"
 #include "graminit.h"
 #include "code.h"
-#include "compile.h"
 #include "symtable.h"
 
 #define UNDEFINED_FUTURE_FEATURE "future feature %.100s is not defined"

Modified: python/branches/pep-3151/Python/getargs.c
==============================================================================
--- python/branches/pep-3151/Python/getargs.c	(original)
+++ python/branches/pep-3151/Python/getargs.c	Sat Feb 26 08:16:32 2011
@@ -146,10 +146,19 @@
 }
 
 static int
-addcleanup(void *ptr, PyObject **freelist, PyCapsule_Destructor destr)
+addcleanup(void *ptr, PyObject **freelist, int is_buffer)
 {
     PyObject *cobj;
     const char *name;
+    PyCapsule_Destructor destr;
+
+    if (is_buffer) {
+        destr = cleanup_buffer;
+        name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER;
+    } else {
+        destr = cleanup_ptr;
+        name = GETARGS_CAPSULE_NAME_CLEANUP_PTR;
+    }
 
     if (!*freelist) {
         *freelist = PyList_New(0);
@@ -159,13 +168,6 @@
         }
     }
 
-    if (destr == cleanup_ptr) {
-        name = GETARGS_CAPSULE_NAME_CLEANUP_PTR;
-    } else if (destr == cleanup_buffer) {
-        name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER;
-    } else {
-        return -1;
-    }
     cobj = PyCapsule_New(ptr, name, destr);
     if (!cobj) {
         destr(ptr);
@@ -597,8 +599,19 @@
 #define FETCH_SIZE      int *q=NULL;Py_ssize_t *q2=NULL;\
     if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \
     else q=va_arg(*p_va, int*);
-#define STORE_SIZE(s)   if (flags & FLAG_SIZE_T) *q2=s; else *q=s;
+#define STORE_SIZE(s)   \
+    if (flags & FLAG_SIZE_T) \
+        *q2=s; \
+    else { \
+        if (INT_MAX < s) { \
+            PyErr_SetString(PyExc_OverflowError, \
+                "size does not fit in an int"); \
+            return converterr("", arg, msgbuf, bufsize); \
+        } \
+        *q=s; \
+    }
 #define BUFFER_LEN      ((flags & FLAG_SIZE_T) ? *q2:*q)
+#define RETURN_ERR_OCCURRED return msgbuf
 
     const char *format = *p_format;
     char c = *format++;
@@ -610,19 +623,19 @@
         char *p = va_arg(*p_va, char *);
         long ival;
         if (float_argument_error(arg))
-            return converterr("integer<b>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         ival = PyLong_AsLong(arg);
         if (ival == -1 && PyErr_Occurred())
-            return converterr("integer<b>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else if (ival < 0) {
             PyErr_SetString(PyExc_OverflowError,
-            "unsigned byte integer is less than minimum");
-            return converterr("integer<b>", arg, msgbuf, bufsize);
+                            "unsigned byte integer is less than minimum");
+            RETURN_ERR_OCCURRED;
         }
         else if (ival > UCHAR_MAX) {
             PyErr_SetString(PyExc_OverflowError,
-            "unsigned byte integer is greater than maximum");
-            return converterr("integer<b>", arg, msgbuf, bufsize);
+                            "unsigned byte integer is greater than maximum");
+            RETURN_ERR_OCCURRED;
         }
         else
             *p = (unsigned char) ival;
@@ -634,10 +647,10 @@
         char *p = va_arg(*p_va, char *);
         long ival;
         if (float_argument_error(arg))
-            return converterr("integer<B>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         ival = PyLong_AsUnsignedLongMask(arg);
         if (ival == -1 && PyErr_Occurred())
-            return converterr("integer<B>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else
             *p = (unsigned char) ival;
         break;
@@ -647,19 +660,19 @@
         short *p = va_arg(*p_va, short *);
         long ival;
         if (float_argument_error(arg))
-            return converterr("integer<h>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         ival = PyLong_AsLong(arg);
         if (ival == -1 && PyErr_Occurred())
-            return converterr("integer<h>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else if (ival < SHRT_MIN) {
             PyErr_SetString(PyExc_OverflowError,
-            "signed short integer is less than minimum");
-            return converterr("integer<h>", arg, msgbuf, bufsize);
+                            "signed short integer is less than minimum");
+            RETURN_ERR_OCCURRED;
         }
         else if (ival > SHRT_MAX) {
             PyErr_SetString(PyExc_OverflowError,
-            "signed short integer is greater than maximum");
-            return converterr("integer<h>", arg, msgbuf, bufsize);
+                            "signed short integer is greater than maximum");
+            RETURN_ERR_OCCURRED;
         }
         else
             *p = (short) ival;
@@ -671,10 +684,10 @@
         unsigned short *p = va_arg(*p_va, unsigned short *);
         long ival;
         if (float_argument_error(arg))
-            return converterr("integer<H>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         ival = PyLong_AsUnsignedLongMask(arg);
         if (ival == -1 && PyErr_Occurred())
-            return converterr("integer<H>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else
             *p = (unsigned short) ival;
         break;
@@ -684,19 +697,19 @@
         int *p = va_arg(*p_va, int *);
         long ival;
         if (float_argument_error(arg))
-            return converterr("integer<i>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         ival = PyLong_AsLong(arg);
         if (ival == -1 && PyErr_Occurred())
-            return converterr("integer<i>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else if (ival > INT_MAX) {
             PyErr_SetString(PyExc_OverflowError,
-                "signed integer is greater than maximum");
-            return converterr("integer<i>", arg, msgbuf, bufsize);
+                            "signed integer is greater than maximum");
+            RETURN_ERR_OCCURRED;
         }
         else if (ival < INT_MIN) {
             PyErr_SetString(PyExc_OverflowError,
-                "signed integer is less than minimum");
-            return converterr("integer<i>", arg, msgbuf, bufsize);
+                            "signed integer is less than minimum");
+            RETURN_ERR_OCCURRED;
         }
         else
             *p = ival;
@@ -708,10 +721,10 @@
         unsigned int *p = va_arg(*p_va, unsigned int *);
         unsigned int ival;
         if (float_argument_error(arg))
-            return converterr("integer<I>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         ival = (unsigned int)PyLong_AsUnsignedLongMask(arg);
         if (ival == (unsigned int)-1 && PyErr_Occurred())
-            return converterr("integer<I>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else
             *p = ival;
         break;
@@ -723,14 +736,14 @@
         Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *);
         Py_ssize_t ival = -1;
         if (float_argument_error(arg))
-            return converterr("integer<n>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         iobj = PyNumber_Index(arg);
         if (iobj != NULL) {
             ival = PyLong_AsSsize_t(iobj);
             Py_DECREF(iobj);
         }
         if (ival == -1 && PyErr_Occurred())
-            return converterr("integer<n>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         *p = ival;
         break;
     }
@@ -738,10 +751,10 @@
         long *p = va_arg(*p_va, long *);
         long ival;
         if (float_argument_error(arg))
-            return converterr("integer<l>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         ival = PyLong_AsLong(arg);
         if (ival == -1 && PyErr_Occurred())
-            return converterr("integer<l>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else
             *p = ival;
         break;
@@ -763,10 +776,10 @@
         PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * );
         PY_LONG_LONG ival;
         if (float_argument_error(arg))
-            return converterr("long<L>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         ival = PyLong_AsLongLong(arg);
         if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred())
-            return converterr("long<L>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else
             *p = ival;
         break;
@@ -788,7 +801,7 @@
         float *p = va_arg(*p_va, float *);
         double dval = PyFloat_AsDouble(arg);
         if (PyErr_Occurred())
-            return converterr("float<f>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else
             *p = (float) dval;
         break;
@@ -798,7 +811,7 @@
         double *p = va_arg(*p_va, double *);
         double dval = PyFloat_AsDouble(arg);
         if (PyErr_Occurred())
-            return converterr("float<d>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else
             *p = dval;
         break;
@@ -809,7 +822,7 @@
         Py_complex cval;
         cval = PyComplex_AsCComplex(arg);
         if (PyErr_Occurred())
-            return converterr("complex<D>", arg, msgbuf, bufsize);
+            RETURN_ERR_OCCURRED;
         else
             *p = cval;
         break;
@@ -845,7 +858,7 @@
             if (getbuffer(arg, (Py_buffer*)p, &buf) < 0)
                 return converterr(buf, arg, msgbuf, bufsize);
             format++;
-            if (addcleanup(p, freelist, cleanup_buffer)) {
+            if (addcleanup(p, freelist, 1)) {
                 return converterr(
                     "(cleanup problem)",
                     arg, msgbuf, bufsize);
@@ -891,7 +904,7 @@
                 if (getbuffer(arg, p, &buf) < 0)
                     return converterr(buf, arg, msgbuf, bufsize);
             }
-            if (addcleanup(p, freelist, cleanup_buffer)) {
+            if (addcleanup(p, freelist, 1)) {
                 return converterr(
                     "(cleanup problem)",
                     arg, msgbuf, bufsize);
@@ -953,9 +966,10 @@
     case 'u': /* raw unicode buffer (Py_UNICODE *) */
     case 'Z': /* raw unicode buffer or None */
     {
+        Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
+
         if (*format == '#') { /* any buffer-like object */
             /* "s#" or "Z#" */
-            Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
             FETCH_SIZE;
 
             if (c == 'Z' && arg == Py_None) {
@@ -971,8 +985,6 @@
             format++;
         } else {
             /* "s" or "Z" */
-            Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
-
             if (c == 'Z' && arg == Py_None)
                 *p = NULL;
             else if (PyUnicode_Check(arg)) {
@@ -1095,11 +1107,9 @@
                 if (*buffer == NULL) {
                     Py_DECREF(s);
                     PyErr_NoMemory();
-                    return converterr(
-                        "(memory error)",
-                        arg, msgbuf, bufsize);
+                    RETURN_ERR_OCCURRED;
                 }
-                if (addcleanup(*buffer, freelist, cleanup_ptr)) {
+                if (addcleanup(*buffer, freelist, 0)) {
                     Py_DECREF(s);
                     return converterr(
                         "(cleanup problem)",
@@ -1139,10 +1149,9 @@
             if (*buffer == NULL) {
                 Py_DECREF(s);
                 PyErr_NoMemory();
-                return converterr("(memory error)",
-                                  arg, msgbuf, bufsize);
+                RETURN_ERR_OCCURRED;
             }
-            if (addcleanup(*buffer, freelist, cleanup_ptr)) {
+            if (addcleanup(*buffer, freelist, 0)) {
                 Py_DECREF(s);
                 return converterr("(cleanup problem)",
                                 arg, msgbuf, bufsize);
@@ -1234,7 +1243,7 @@
             PyBuffer_Release((Py_buffer*)p);
             return converterr("contiguous buffer", arg, msgbuf, bufsize);
         }
-        if (addcleanup(p, freelist, cleanup_buffer)) {
+        if (addcleanup(p, freelist, 1)) {
             return converterr(
                 "(cleanup problem)",
                 arg, msgbuf, bufsize);
@@ -1249,6 +1258,11 @@
 
     *p_format = format;
     return NULL;
+
+#undef FETCH_SIZE
+#undef STORE_SIZE
+#undef BUFFER_LEN
+#undef RETURN_ERR_OCCURRED
 }
 
 static Py_ssize_t
@@ -1394,7 +1408,7 @@
 int
 PyArg_ValidateKeywordArguments(PyObject *kwargs)
 {
-    if (!PyDict_CheckExact(kwargs)) {
+    if (!PyDict_Check(kwargs)) {
         PyErr_BadInternalCall();
         return 0;
     }

Modified: python/branches/pep-3151/Python/getcopyright.c
==============================================================================
--- python/branches/pep-3151/Python/getcopyright.c	(original)
+++ python/branches/pep-3151/Python/getcopyright.c	Sat Feb 26 08:16:32 2011
@@ -4,7 +4,7 @@
 
 static char cprt[] =
 "\
-Copyright (c) 2001-2010 Python Software Foundation.\n\
+Copyright (c) 2001-2011 Python Software Foundation.\n\
 All Rights Reserved.\n\
 \n\
 Copyright (c) 2000 BeOpen.com.\n\

Modified: python/branches/pep-3151/Python/import.c
==============================================================================
--- python/branches/pep-3151/Python/import.c	(original)
+++ python/branches/pep-3151/Python/import.c	Sat Feb 26 08:16:32 2011
@@ -5,13 +5,9 @@
 
 #include "Python-ast.h"
 #undef Yield /* undefine macro conflicting with winbase.h */
-#include "pyarena.h"
-#include "pythonrun.h"
 #include "errcode.h"
 #include "marshal.h"
 #include "code.h"
-#include "compile.h"
-#include "eval.h"
 #include "osdefs.h"
 #include "importdl.h"
 
@@ -329,8 +325,17 @@
 {
     if (import_lock != NULL)
         import_lock = PyThread_allocate_lock();
-    import_lock_thread = -1;
-    import_lock_level = 0;
+    if (import_lock_level > 1) {
+        /* Forked as a side effect of import */
+        long me = PyThread_get_thread_ident();
+        PyThread_acquire_lock(import_lock, 0);
+	/* XXX: can the previous line fail? */
+        import_lock_thread = me;
+        import_lock_level--;
+    } else {
+        import_lock_thread = -1;
+        import_lock_level = 0;
+    }
 }
 
 #endif
@@ -631,7 +636,7 @@
 }
 
 PyObject *
-_PyImport_FindExtensionUnicode(char *name, PyObject *filename)
+_PyImport_FindExtensionUnicode(const char *name, PyObject *filename)
 {
     PyObject *mod, *mdict;
     PyModuleDef* def;
@@ -675,7 +680,7 @@
 }
 
 PyObject *
-_PyImport_FindBuiltin(char *name)
+_PyImport_FindBuiltin(const char *name)
 {
     PyObject *res, *filename;
     filename = PyUnicode_FromString(name);
@@ -801,7 +806,7 @@
         PyErr_Clear(); /* Not important enough to report */
     Py_DECREF(v);
 
-    v = PyEval_EvalCode((PyCodeObject *)co, d, d);
+    v = PyEval_EvalCode(co, d, d);
     if (v == NULL)
         goto error;
     Py_DECREF(v);
@@ -1542,8 +1547,8 @@
    pathname and an open file.  Return NULL if the module is not found. */
 
 #ifdef MS_COREDLL
-extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
-                                        char *, Py_ssize_t);
+extern FILE *_PyWin_FindRegisteredModule(const char *, struct filedescr **,
+                                         char *, Py_ssize_t);
 #endif
 
 static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
@@ -1626,7 +1631,7 @@
             return &fd_builtin;
         }
 #ifdef MS_COREDLL
-        fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
+        fp = _PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
         if (fp != NULL) {
             *p_fp = fp;
             return fdp;
@@ -3201,14 +3206,14 @@
 static PyObject *
 imp_find_module(PyObject *self, PyObject *args)
 {
-    char *name;
+    PyObject *name;
     PyObject *ret, *path = NULL;
-    if (!PyArg_ParseTuple(args, "es|O:find_module",
-                          Py_FileSystemDefaultEncoding, &name,
+    if (!PyArg_ParseTuple(args, "O&|O:find_module",
+                          PyUnicode_FSConverter, &name,
                           &path))
         return NULL;
-    ret = call_find_module(name, path);
-    PyMem_Free(name);
+    ret = call_find_module(PyBytes_AS_STRING(name), path);
+    Py_DECREF(name);
     return ret;
 }
 
@@ -3326,23 +3331,23 @@
 imp_load_compiled(PyObject *self, PyObject *args)
 {
     char *name;
-    char *pathname;
+    PyObject *pathname;
     PyObject *fob = NULL;
     PyObject *m;
     FILE *fp;
-    if (!PyArg_ParseTuple(args, "ses|O:load_compiled",
+    if (!PyArg_ParseTuple(args, "sO&|O:load_compiled",
                           &name,
-                          Py_FileSystemDefaultEncoding, &pathname,
+                          PyUnicode_FSConverter, &pathname,
                           &fob))
         return NULL;
-    fp = get_file(pathname, fob, "rb");
+    fp = get_file(PyBytes_AS_STRING(pathname), fob, "rb");
     if (fp == NULL) {
-        PyMem_Free(pathname);
+        Py_DECREF(pathname);
         return NULL;
     }
-    m = load_compiled_module(name, pathname, fp);
+    m = load_compiled_module(name, PyBytes_AS_STRING(pathname), fp);
     fclose(fp);
-    PyMem_Free(pathname);
+    Py_DECREF(pathname);
     return m;
 }
 
@@ -3381,22 +3386,22 @@
 imp_load_source(PyObject *self, PyObject *args)
 {
     char *name;
-    char *pathname;
+    PyObject *pathname;
     PyObject *fob = NULL;
     PyObject *m;
     FILE *fp;
-    if (!PyArg_ParseTuple(args, "ses|O:load_source",
+    if (!PyArg_ParseTuple(args, "sO&|O:load_source",
                           &name,
-                          Py_FileSystemDefaultEncoding, &pathname,
+                          PyUnicode_FSConverter, &pathname,
                           &fob))
         return NULL;
-    fp = get_file(pathname, fob, "r");
+    fp = get_file(PyBytes_AS_STRING(pathname), fob, "r");
     if (fp == NULL) {
-        PyMem_Free(pathname);
+        Py_DECREF(pathname);
         return NULL;
     }
-    m = load_source_module(name, pathname, fp);
-    PyMem_Free(pathname);
+    m = load_source_module(name, PyBytes_AS_STRING(pathname), fp);
+    Py_DECREF(pathname);
     fclose(fp);
     return m;
 }
@@ -3450,13 +3455,13 @@
 imp_load_package(PyObject *self, PyObject *args)
 {
     char *name;
-    char *pathname;
+    PyObject *pathname;
     PyObject * ret;
-    if (!PyArg_ParseTuple(args, "ses:load_package",
-                          &name, Py_FileSystemDefaultEncoding, &pathname))
+    if (!PyArg_ParseTuple(args, "sO&:load_package",
+                          &name, PyUnicode_FSConverter, &pathname))
         return NULL;
-    ret = load_package(name, pathname);
-    PyMem_Free(pathname);
+    ret = load_package(name, PyBytes_AS_STRING(pathname));
+    Py_DECREF(pathname);
     return ret;
 }
 
@@ -3529,21 +3534,23 @@
 {
     static char *kwlist[] = {"path", NULL};
 
+    PyObject *pathname_obj;
     char *pathname;
     char buf[MAXPATHLEN+1];
 
     if (!PyArg_ParseTupleAndKeywords(
-                args, kws, "es", kwlist,
-                Py_FileSystemDefaultEncoding, &pathname))
+                args, kws, "O&", kwlist,
+                PyUnicode_FSConverter, &pathname_obj))
         return NULL;
 
+    pathname = PyBytes_AS_STRING(pathname_obj);
     if (make_source_pathname(pathname, buf) == NULL) {
         PyErr_Format(PyExc_ValueError, "Not a PEP 3147 pyc path: %s",
                      pathname);
-        PyMem_Free(pathname);
+        Py_DECREF(pathname_obj);
         return NULL;
     }
-    PyMem_Free(pathname);
+    Py_DECREF(pathname_obj);
     return PyUnicode_FromString(buf);
 }
 

Modified: python/branches/pep-3151/Python/importdl.c
==============================================================================
--- python/branches/pep-3151/Python/importdl.c	(original)
+++ python/branches/pep-3151/Python/importdl.c	Sat Feb 26 08:16:32 2011
@@ -12,8 +12,7 @@
 
 #include "importdl.h"
 
-extern dl_funcptr _PyImport_GetDynLoadFunc(const char *name,
-                                           const char *shortname,
+extern dl_funcptr _PyImport_GetDynLoadFunc(const char *shortname,
                                            const char *pathname, FILE *fp);
 
 
@@ -48,7 +47,7 @@
         shortname = lastdot+1;
     }
 
-    p0 = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp);
+    p0 = _PyImport_GetDynLoadFunc(shortname, pathname, fp);
     p = (PyObject*(*)(void))p0;
     if (PyErr_Occurred())
         goto error;

Modified: python/branches/pep-3151/Python/peephole.c
==============================================================================
--- python/branches/pep-3151/Python/peephole.c	(original)
+++ python/branches/pep-3151/Python/peephole.c	Sat Feb 26 08:16:32 2011
@@ -4,10 +4,8 @@
 
 #include "Python-ast.h"
 #include "node.h"
-#include "pyarena.h"
 #include "ast.h"
 #include "code.h"
-#include "compile.h"
 #include "symtable.h"
 #include "opcode.h"
 

Modified: python/branches/pep-3151/Python/pyarena.c
==============================================================================
--- python/branches/pep-3151/Python/pyarena.c	(original)
+++ python/branches/pep-3151/Python/pyarena.c	Sat Feb 26 08:16:32 2011
@@ -1,5 +1,4 @@
 #include "Python.h"
-#include "pyarena.h"
 
 /* A simple arena block structure.
 

Modified: python/branches/pep-3151/Python/pystrtod.c
==============================================================================
--- python/branches/pep-3151/Python/pystrtod.c	(original)
+++ python/branches/pep-3151/Python/pystrtod.c	Sat Feb 26 08:16:32 2011
@@ -954,7 +954,7 @@
             /* shouldn't get here: Gay's code should always return
                something starting with a digit, an 'I',  or 'N' */
             strncpy(p, "ERR", 3);
-            p += 3;
+            /* p += 3; */
             assert(0);
         }
         goto exit;

Modified: python/branches/pep-3151/Python/pythonrun.c
==============================================================================
--- python/branches/pep-3151/Python/pythonrun.c	(original)
+++ python/branches/pep-3151/Python/pythonrun.c	Sat Feb 26 08:16:32 2011
@@ -11,14 +11,10 @@
 #include "parsetok.h"
 #include "errcode.h"
 #include "code.h"
-#include "compile.h"
 #include "symtable.h"
-#include "pyarena.h"
 #include "ast.h"
-#include "eval.h"
 #include "marshal.h"
 #include "osdefs.h"
-#include "abstract.h"
 
 #ifdef HAVE_SIGNAL_H
 #include <signal.h>
@@ -82,6 +78,7 @@
 
 int Py_DebugFlag; /* Needed by parser.c */
 int Py_VerboseFlag; /* Needed by import.c */
+int Py_QuietFlag; /* Needed by sysmodule.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' */
@@ -781,6 +778,7 @@
 {
     PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
     const char* mode;
+    const char* newline;
     PyObject *line_buffering;
     int buffering, isatty;
 
@@ -831,9 +829,17 @@
     Py_CLEAR(raw);
     Py_CLEAR(text);
 
+    newline = "\n";
+#ifdef MS_WINDOWS
+    if (!write_mode) {
+        /* translate \r\n to \n for sys.stdin on Windows */
+        newline = NULL;
+    }
+#endif
+
     stream = PyObject_CallMethod(io, "TextIOWrapper", "OsssO",
                                  buf, encoding, errors,
-                                 "\n", line_buffering);
+                                 newline, line_buffering);
     Py_CLEAR(buf);
     if (stream == NULL)
         goto error;
@@ -893,8 +899,10 @@
 
     /* Set builtins.open */
     if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
+        Py_DECREF(wrapper);
         goto error;
     }
+    Py_DECREF(wrapper);
 
     encoding = Py_GETENV("PYTHONIOENCODING");
     errors = NULL;
@@ -1203,7 +1211,8 @@
 {
     PyObject *m, *d, *v;
     const char *ext;
-    int set_file_name = 0, ret, len;
+    int set_file_name = 0, ret;
+    size_t len;
 
     m = PyImport_AddModule("__main__");
     if (m == NULL)
@@ -1757,7 +1766,7 @@
     co = PyAST_Compile(mod, filename, flags, arena);
     if (co == NULL)
         return NULL;
-    v = PyEval_EvalCode(co, globals, locals);
+    v = PyEval_EvalCode((PyObject*)co, globals, locals);
     Py_DECREF(co);
     return v;
 }
@@ -1787,7 +1796,7 @@
         return NULL;
     }
     co = (PyCodeObject *)v;
-    v = PyEval_EvalCode(co, globals, locals);
+    v = PyEval_EvalCode((PyObject*)co, globals, locals);
     if (v && flags)
         flags->cf_flags |= (co->co_flags & PyCF_MASK);
     Py_DECREF(co);
@@ -1795,8 +1804,8 @@
 }
 
 PyObject *
-Py_CompileStringFlags(const char *str, const char *filename, int start,
-                      PyCompilerFlags *flags)
+Py_CompileStringExFlags(const char *str, const char *filename, int start,
+                        PyCompilerFlags *flags, int optimize)
 {
     PyCodeObject *co;
     mod_ty mod;
@@ -1814,11 +1823,19 @@
         PyArena_Free(arena);
         return result;
     }
-    co = PyAST_Compile(mod, filename, flags, arena);
+    co = PyAST_CompileEx(mod, filename, flags, optimize, arena);
     PyArena_Free(arena);
     return (PyObject *)co;
 }
 
+/* For use in Py_LIMITED_API */
+#undef Py_CompileString
+PyObject *
+PyCompileString(const char *str, const char *filename, int start)
+{
+    return Py_CompileStringFlags(str, filename, start, NULL);
+}
+
 struct symtable *
 Py_SymtableString(const char *str, const char *filename, int start)
 {
@@ -2444,7 +2461,15 @@
 PyAPI_FUNC(PyObject *)
 Py_CompileString(const char *str, const char *p, int s)
 {
-    return Py_CompileStringFlags(str, p, s, NULL);
+    return Py_CompileStringExFlags(str, p, s, NULL, -1);
+}
+
+#undef Py_CompileStringFlags
+PyAPI_FUNC(PyObject *)
+Py_CompileStringFlags(const char *str, const char *p, int s,
+                      PyCompilerFlags *flags)
+{
+    return Py_CompileStringExFlags(str, p, s, flags, -1);
 }
 
 #undef PyRun_InteractiveOne

Modified: python/branches/pep-3151/Python/sysmodule.c
==============================================================================
--- python/branches/pep-3151/Python/sysmodule.c	(original)
+++ python/branches/pep-3151/Python/sysmodule.c	Sat Feb 26 08:16:32 2011
@@ -15,10 +15,8 @@
 */
 
 #include "Python.h"
-#include "structseq.h"
 #include "code.h"
 #include "frameobject.h"
-#include "eval.h"
 
 #include "osdefs.h"
 
@@ -67,6 +65,68 @@
         return PyDict_SetItemString(sd, name, v);
 }
 
+/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
+   error handler. If sys.stdout has a buffer attribute, use
+   sys.stdout.buffer.write(encoded), otherwise redecode the string and use
+   sys.stdout.write(redecoded).
+
+   Helper function for sys_displayhook(). */
+static int
+sys_displayhook_unencodable(PyObject *outf, PyObject *o)
+{
+    PyObject *stdout_encoding = NULL;
+    PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
+    char *stdout_encoding_str;
+    int ret;
+
+    stdout_encoding = PyObject_GetAttrString(outf, "encoding");
+    if (stdout_encoding == NULL)
+        goto error;
+    stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
+    if (stdout_encoding_str == NULL)
+        goto error;
+
+    repr_str = PyObject_Repr(o);
+    if (repr_str == NULL)
+        goto error;
+    encoded = PyUnicode_AsEncodedString(repr_str,
+                                        stdout_encoding_str,
+                                        "backslashreplace");
+    Py_DECREF(repr_str);
+    if (encoded == NULL)
+        goto error;
+
+    buffer = PyObject_GetAttrString(outf, "buffer");
+    if (buffer) {
+        result = PyObject_CallMethod(buffer, "write", "(O)", encoded);
+        Py_DECREF(buffer);
+        Py_DECREF(encoded);
+        if (result == NULL)
+            goto error;
+        Py_DECREF(result);
+    }
+    else {
+        PyErr_Clear();
+        escaped_str = PyUnicode_FromEncodedObject(encoded,
+                                                  stdout_encoding_str,
+                                                  "strict");
+        Py_DECREF(encoded);
+        if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
+            Py_DECREF(escaped_str);
+            goto error;
+        }
+        Py_DECREF(escaped_str);
+    }
+    ret = 0;
+    goto finally;
+
+error:
+    ret = -1;
+finally:
+    Py_XDECREF(stdout_encoding);
+    return ret;
+}
+
 static PyObject *
 sys_displayhook(PyObject *self, PyObject *o)
 {
@@ -74,6 +134,7 @@
     PyInterpreterState *interp = PyThreadState_GET()->interp;
     PyObject *modules = interp->modules;
     PyObject *builtins = PyDict_GetItemString(modules, "builtins");
+    int err;
 
     if (builtins == NULL) {
         PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
@@ -94,8 +155,19 @@
         PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
         return NULL;
     }
-    if (PyFile_WriteObject(o, outf, 0) != 0)
-        return NULL;
+    if (PyFile_WriteObject(o, outf, 0) != 0) {
+        if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
+            /* repr(o) is not encodable to sys.stdout.encoding with
+             * sys.stdout.errors error handler (which is probably 'strict') */
+            PyErr_Clear();
+            err = sys_displayhook_unencodable(outf, o);
+            if (err)
+                return NULL;
+        }
+        else {
+            return NULL;
+        }
+    }
     if (PyFile_WriteString("\n", outf) != 0)
         return NULL;
     if (PyObject_SetAttrString(builtins, "_", o) != 0)
@@ -1104,7 +1176,6 @@
     PyObject *opts;
     PyObject *name = NULL, *value = NULL;
     const wchar_t *name_end;
-    int r;
 
     opts = get_xoptions();
     if (opts == NULL)
@@ -1122,7 +1193,7 @@
     }
     if (name == NULL || value == NULL)
         goto error;
-    r = PyDict_SetItem(opts, name, value);
+    PyDict_SetItem(opts, name, value);
     Py_DECREF(name);
     Py_DECREF(value);
     return;
@@ -1345,7 +1416,8 @@
 #endif
     /* {"unbuffered",                   "-u"}, */
     /* {"skip_first",                   "-x"}, */
-    {"bytes_warning", "-b"},
+    {"bytes_warning",           "-b"},
+    {"quiet",                   "-q"},
     {0}
 };
 
@@ -1354,9 +1426,9 @@
     flags__doc__,       /* doc */
     flags_fields,       /* fields */
 #ifdef RISCOS
-    12
+    13
 #else
-    11
+    12
 #endif
 };
 
@@ -1389,6 +1461,7 @@
     /* SetFlag(saw_unbuffered_flag); */
     /* SetFlag(skipfirstline); */
     SetFlag(Py_BytesWarningFlag);
+    SetFlag(Py_QuietFlag);
 #undef SetFlag
 
     if (PyErr_Occurred()) {

Modified: python/branches/pep-3151/Python/thread_nt.h
==============================================================================
--- python/branches/pep-3151/Python/thread_nt.h	(original)
+++ python/branches/pep-3151/Python/thread_nt.h	Sat Feb 26 08:16:32 2011
@@ -238,10 +238,13 @@
  * and 0 if the lock was not acquired. This means a 0 is returned
  * if the lock has already been acquired by this thread!
  */
-int
-PyThread_acquire_lock_timed(PyThread_type_lock aLock, PY_TIMEOUT_T microseconds)
+PyLockStatus
+PyThread_acquire_lock_timed(PyThread_type_lock aLock,
+                            PY_TIMEOUT_T microseconds, int intr_flag)
 {
-    int success ;
+    /* Fow now, intr_flag does nothing on Windows, and lock acquires are
+     * uninterruptible.  */
+    PyLockStatus success;
     PY_TIMEOUT_T milliseconds;
 
     if (microseconds >= 0) {
@@ -258,7 +261,13 @@
     dprintf(("%ld: PyThread_acquire_lock_timed(%p, %lld) called\n",
              PyThread_get_thread_ident(), aLock, microseconds));
 
-    success = aLock && EnterNonRecursiveMutex((PNRMUTEX) aLock, (DWORD) milliseconds) == WAIT_OBJECT_0 ;
+    if (aLock && EnterNonRecursiveMutex((PNRMUTEX)aLock,
+                                        (DWORD)milliseconds) == WAIT_OBJECT_0) {
+        success = PY_LOCK_ACQUIRED;
+    }
+    else {
+        success = PY_LOCK_FAILURE;
+    }
 
     dprintf(("%ld: PyThread_acquire_lock(%p, %lld) -> %d\n",
              PyThread_get_thread_ident(), aLock, microseconds, success));
@@ -268,7 +277,7 @@
 int
 PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag)
 {
-    return PyThread_acquire_lock_timed(aLock, waitflag ? -1 : 0);
+    return PyThread_acquire_lock_timed(aLock, waitflag ? -1 : 0, 0);
 }
 
 void

Modified: python/branches/pep-3151/Python/thread_pthread.h
==============================================================================
--- python/branches/pep-3151/Python/thread_pthread.h	(original)
+++ python/branches/pep-3151/Python/thread_pthread.h	Sat Feb 26 08:16:32 2011
@@ -316,16 +316,17 @@
     return (status == -1) ? errno : status;
 }
 
-int
-PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds)
+PyLockStatus
+PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds,
+                            int intr_flag)
 {
-    int success;
+    PyLockStatus success;
     sem_t *thelock = (sem_t *)lock;
     int status, error = 0;
     struct timespec ts;
 
-    dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n",
-             lock, microseconds));
+    dprintf(("PyThread_acquire_lock_timed(%p, %lld, %d) called\n",
+             lock, microseconds, intr_flag));
 
     if (microseconds > 0)
         MICROSECONDS_TO_TIMESPEC(microseconds, ts);
@@ -336,33 +337,38 @@
             status = fix_status(sem_trywait(thelock));
         else
             status = fix_status(sem_wait(thelock));
-    } while (status == EINTR); /* Retry if interrupted by a signal */
-
-    if (microseconds > 0) {
-        if (status != ETIMEDOUT)
-            CHECK_STATUS("sem_timedwait");
-    }
-    else if (microseconds == 0) {
-        if (status != EAGAIN)
-            CHECK_STATUS("sem_trywait");
-    }
-    else {
-        CHECK_STATUS("sem_wait");
+        /* Retry if interrupted by a signal, unless the caller wants to be
+           notified.  */
+    } while (!intr_flag && status == EINTR);
+
+    /* Don't check the status if we're stopping because of an interrupt.  */
+    if (!(intr_flag && status == EINTR)) {
+        if (microseconds > 0) {
+            if (status != ETIMEDOUT)
+                CHECK_STATUS("sem_timedwait");
+        }
+        else if (microseconds == 0) {
+            if (status != EAGAIN)
+                CHECK_STATUS("sem_trywait");
+        }
+        else {
+            CHECK_STATUS("sem_wait");
+        }
     }
 
-    success = (status == 0) ? 1 : 0;
+    if (status == 0) {
+        success = PY_LOCK_ACQUIRED;
+    } else if (intr_flag && status == EINTR) {
+        success = PY_LOCK_INTR;
+    } else {
+        success = PY_LOCK_FAILURE;
+    }
 
-    dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n",
-             lock, microseconds, success));
+    dprintf(("PyThread_acquire_lock_timed(%p, %lld, %d) -> %d\n",
+             lock, microseconds, intr_flag, success));
     return success;
 }
 
-int
-PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
-{
-    return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0);
-}
-
 void
 PyThread_release_lock(PyThread_type_lock lock)
 {
@@ -436,21 +442,25 @@
     free((void *)thelock);
 }
 
-int
-PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds)
+PyLockStatus
+PyThread_acquire_lock_timed(PyThread_type_lock lock, PY_TIMEOUT_T microseconds,
+                            int intr_flag)
 {
-    int success;
+    PyLockStatus success;
     pthread_lock *thelock = (pthread_lock *)lock;
     int status, error = 0;
 
-    dprintf(("PyThread_acquire_lock_timed(%p, %lld) called\n",
-             lock, microseconds));
+    dprintf(("PyThread_acquire_lock_timed(%p, %lld, %d) called\n",
+             lock, microseconds, intr_flag));
 
     status = pthread_mutex_lock( &thelock->mut );
     CHECK_STATUS("pthread_mutex_lock[1]");
-    success = thelock->locked == 0;
 
-    if (!success && microseconds != 0) {
+    if (thelock->locked == 0) {
+        success = PY_LOCK_ACQUIRED;
+    } else if (microseconds == 0) {
+        success = PY_LOCK_FAILURE;
+    } else {
         struct timespec ts;
         if (microseconds > 0)
             MICROSECONDS_TO_TIMESPEC(microseconds, ts);
@@ -458,7 +468,8 @@
 
         /* mut must be locked by me -- part of the condition
          * protocol */
-        while (thelock->locked) {
+        success = PY_LOCK_FAILURE;
+        while (success == PY_LOCK_FAILURE) {
             if (microseconds > 0) {
                 status = pthread_cond_timedwait(
                     &thelock->lock_released,
@@ -473,25 +484,30 @@
                     &thelock->mut);
                 CHECK_STATUS("pthread_cond_wait");
             }
+
+            if (intr_flag && status == 0 && thelock->locked) {
+                /* We were woken up, but didn't get the lock.  We probably received
+                 * a signal.  Return PY_LOCK_INTR to allow the caller to handle
+                 * it and retry.  */
+                success = PY_LOCK_INTR;
+                break;
+            } else if (status == 0 && !thelock->locked) {
+                success = PY_LOCK_ACQUIRED;
+            } else {
+                success = PY_LOCK_FAILURE;
+            }
         }
-        success = (status == 0);
     }
-    if (success) thelock->locked = 1;
+    if (success == PY_LOCK_ACQUIRED) thelock->locked = 1;
     status = pthread_mutex_unlock( &thelock->mut );
     CHECK_STATUS("pthread_mutex_unlock[1]");
 
-    if (error) success = 0;
-    dprintf(("PyThread_acquire_lock_timed(%p, %lld) -> %d\n",
-             lock, microseconds, success));
+    if (error) success = PY_LOCK_FAILURE;
+    dprintf(("PyThread_acquire_lock_timed(%p, %lld, %d) -> %d\n",
+             lock, microseconds, intr_flag, success));
     return success;
 }
 
-int
-PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
-{
-    return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0);
-}
-
 void
 PyThread_release_lock(PyThread_type_lock lock)
 {
@@ -515,6 +531,12 @@
 
 #endif /* USE_SEMAPHORES */
 
+int
+PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
+{
+    return PyThread_acquire_lock_timed(lock, waitflag ? -1 : 0, /*intr_flag=*/0);
+}
+
 /* set the thread stack size.
  * Return 0 if size is valid, -1 if size is invalid,
  * -2 if setting stack size is not supported.

Modified: python/branches/pep-3151/Python/traceback.c
==============================================================================
--- python/branches/pep-3151/Python/traceback.c	(original)
+++ python/branches/pep-3151/Python/traceback.c	Sat Feb 26 08:16:32 2011
@@ -7,7 +7,6 @@
 #include "frameobject.h"
 #include "structmember.h"
 #include "osdefs.h"
-#include "traceback.h"
 #ifdef HAVE_FCNTL_H
 #include <fcntl.h>
 #endif

Modified: python/branches/pep-3151/README
==============================================================================
--- python/branches/pep-3151/README	(original)
+++ python/branches/pep-3151/README	Sat Feb 26 08:16:32 2011
@@ -1,9 +1,8 @@
-This is Python version 3.2 alpha 3
+This is Python version 3.3 alpha 0
 ==================================
 
-Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
-Python Software Foundation.
-All rights reserved.
+Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
+Python Software Foundation.  All rights reserved.
 
 Python 3.x is a new version of the language, which is incompatible with the 2.x
 line of releases.  The language is mostly the same, but many details, especially
@@ -51,9 +50,9 @@
 ----------
 
 We try to have a comprehensive overview of the changes in the "What's New in
-Python 3.2" document, found at
+Python 3.3" document, found at
 
-    http://docs.python.org/3.2/whatsnew/3.2.html
+    http://docs.python.org/3.3/whatsnew/3.3.html
 
 For a more detailed change log, read Misc/NEWS (though this file, too, is
 incomplete, and also doesn't list anything merged in from the 2.7 release under
@@ -66,9 +65,9 @@
 Documentation
 -------------
 
-Documentation for Python 3.2 is online, updated daily:
+Documentation for Python 3.3 is online, updated daily:
 
-    http://docs.python.org/3.2/
+    http://docs.python.org/3.3/
 
 It can also be downloaded in many formats for faster access.  The documentation
 is downloadable in HTML, PDF, and reStructuredText formats; the latter version
@@ -86,7 +85,7 @@
 A source-to-source translation tool, "2to3", can take care of the mundane task
 of converting large amounts of source code.  It is not a complete solution but
 is complemented by the deprecation warnings in 2.6.  See
-http://docs.python.org/3.2/library/2to3.html for more information.
+http://docs.python.org/3.3/library/2to3.html for more information.
 
 
 Testing
@@ -97,10 +96,7 @@
 left by the previous test run).  The test set produces some output.  You can
 generally ignore the messages about skipped tests due to optional features which
 can't be imported.  If a message is printed about a failed test or a traceback
-or core dump is produced, something is wrong.  On some Linux systems (those that
-are not yet using glibc 6), test_strftime fails due to a non-standard
-implementation of strftime() in the C library. Please ignore this, or upgrade to
-glibc version 6.
+or core dump is produced, something is wrong.
 
 By default, tests are prevented from overusing resources like disk space and
 memory.  To enable these tests, run "make testall".
@@ -109,7 +105,7 @@
 include the output of "make test".  It is useless.  Run the failing test
 manually, as follows:
 
-        ./python Lib/test/regrtest.py -v test_whatever
+        ./python -m test -v test_whatever
 
 (substituting the top of the source tree for '.' if you built in a different
 directory).  This runs the test in verbose mode.
@@ -129,8 +125,8 @@
 Install that version using "make install".  Install all other versions using
 "make altinstall".
 
-For example, if you want to install Python 2.5, 2.6 and 3.2 with 2.6 being the
-primary version, you would execute "make install" in your 2.6 build directory
+For example, if you want to install Python 2.6, 2.7 and 3.3 with 2.7 being the
+primary version, you would execute "make install" in your 2.7 build directory
 and "make altinstall" in the others.
 
 
@@ -156,8 +152,8 @@
 -------------------------
 
 If you have a proposal to change Python, you may want to send an email to the
-comp.lang.python or python-ideas mailing lists for inital feedback. A Python
-Enhancement Proposal (PEP) may be submitted if your idea gains ground. All
+comp.lang.python or python-ideas mailing lists for inital feedback.  A Python
+Enhancement Proposal (PEP) may be submitted if your idea gains ground.  All
 current PEPs, as well as guidelines for submitting a new PEP, are listed at
 http://www.python.org/dev/peps/.
 
@@ -165,32 +161,27 @@
 Release Schedule
 ----------------
 
-See PEP 392 for release details: http://www.python.org/dev/peps/pep-0392/
+See PEP XXX for release details: http://www.python.org/dev/peps/pep-0XXX/
 
 
 Copyright and License Information
 ---------------------------------
 
-Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
-Python Software Foundation.
-All rights reserved.
+Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
+Python Software Foundation.  All rights reserved.
 
-Copyright (c) 2000 BeOpen.com.
-All rights reserved.
+Copyright (c) 2000 BeOpen.com.  All rights reserved.
 
-Copyright (c) 1995-2001 Corporation for National Research Initiatives.
-All rights reserved.
+Copyright (c) 1995-2001 Corporation for National Research Initiatives.  All
+rights reserved.
 
-Copyright (c) 1991-1995 Stichting Mathematisch Centrum.
-All rights reserved.
+Copyright (c) 1991-1995 Stichting Mathematisch Centrum.  All rights reserved.
 
-See the file "LICENSE" for information on the history of this
-software, terms & conditions for usage, and a DISCLAIMER OF ALL
-WARRANTIES.
+See the file "LICENSE" for information on the history of this software, terms &
+conditions for usage, and a DISCLAIMER OF ALL WARRANTIES.
 
-This Python distribution contains *no* GNU General Public License
-(GPL) code, so it may be used in proprietary projects.  There are
-interfaces to some GNU code but these are entirely optional.
+This Python distribution contains *no* GNU General Public License (GPL) code, so
+it may be used in proprietary projects.  There are interfaces to some GNU code
+but these are entirely optional.
 
-All trademarks referenced herein are property of their respective
-holders.
+All trademarks referenced herein are property of their respective holders.

Modified: python/branches/pep-3151/Tools/README
==============================================================================
--- python/branches/pep-3151/Tools/README	(original)
+++ python/branches/pep-3151/Tools/README	Sat Feb 26 08:16:32 2011
@@ -5,7 +5,7 @@
 
 ccbench         A Python concurrency benchmark.
 
-framer          Generate boilerplate code for C extension types.
+demo            Several Python programming demos.
 
 freeze          Create a stand-alone executable from a Python program.
 
@@ -21,6 +21,8 @@
 
 msi             Support for packaging Python as an MSI package on Windows.
 
+parser          Un-parsing tool to generate code from an AST.
+
 pybench         Comprehensive Python benchmarking suite.
 
 pynche          A Tkinter-based color editor.
@@ -30,10 +32,14 @@
                 tabs and spaces, and 2to3, which converts Python 2 code
                 to Python 3 code.
 
-ssl             Currently, a tool to fetch server certificates.
+test2to3        A demonstration of how to use 2to3 transparently in setup.py.
+
+unicode         Tools for generating unicodedata and codecs from unicode.org
+                and other mapping files (by Fredrik Lundh, Marc-Andre Lemburg
+                and Martin von Loewis).
 
-unicode         Tools used to generate unicode database files for
-                Python 2.0 (by Fredrik Lundh).
+unittestgui     A Tkinter based GUI test runner for unittest, with test
+                discovery.
 
 world           Script to take a list of Internet addresses and print
                 out where in the world those addresses originate from,

Modified: python/branches/pep-3151/Tools/buildbot/build-amd64.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/build-amd64.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/build-amd64.bat	Sat Feb 26 08:16:32 2011
@@ -1,6 +1,6 @@
- at rem Used by the buildbot "compile" step.
-cmd /c Tools\buildbot\external-amd64.bat
-call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
-cmd /c Tools\buildbot\clean-amd64.bat
-vcbuild /useenv PCbuild\kill_python.vcproj "Debug|x64" && PCbuild\amd64\kill_python_d.exe
-vcbuild PCbuild\pcbuild.sln "Debug|x64"
+ at rem Used by the buildbot "compile" step.
+cmd /c Tools\buildbot\external-amd64.bat
+call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
+cmd /c Tools\buildbot\clean-amd64.bat
+vcbuild /useenv PCbuild\kill_python.vcproj "Debug|x64" && PCbuild\amd64\kill_python_d.exe
+vcbuild PCbuild\pcbuild.sln "Debug|x64"

Modified: python/branches/pep-3151/Tools/buildbot/build.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/build.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/build.bat	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,7 @@
- at rem Used by the buildbot "compile" step.
-cmd /c Tools\buildbot\external.bat
-call "%VS90COMNTOOLS%vsvars32.bat"
-cmd /c Tools\buildbot\clean.bat
-vcbuild /useenv PCbuild\kill_python.vcproj "Debug|Win32" && PCbuild\kill_python_d.exe
-vcbuild /useenv PCbuild\pcbuild.sln "Debug|Win32"
-
+ at rem Used by the buildbot "compile" step.
+cmd /c Tools\buildbot\external.bat
+call "%VS90COMNTOOLS%vsvars32.bat"
+cmd /c Tools\buildbot\clean.bat
+vcbuild /useenv PCbuild\kill_python.vcproj "Debug|Win32" && PCbuild\kill_python_d.exe
+vcbuild /useenv PCbuild\pcbuild.sln "Debug|Win32"
+

Modified: python/branches/pep-3151/Tools/buildbot/buildmsi.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/buildmsi.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/buildmsi.bat	Sat Feb 26 08:16:32 2011
@@ -1,21 +1,21 @@
- at rem Used by the buildbot "buildmsi" step.
-
-cmd /c Tools\buildbot\external.bat
- at rem build release versions of things
-call "%VS90COMNTOOLS%vsvars32.bat"
-
- at rem build Python
-vcbuild /useenv PCbuild\pcbuild.sln "Release|Win32"
-
- at rem build the documentation
-bash.exe -c 'cd Doc;make PYTHON=python2.5 update htmlhelp'
-"%ProgramFiles%\HTML Help Workshop\hhc.exe" Doc\build\htmlhelp\python26a3.hhp
-
- at rem build the MSI file
-cd PC
-nmake /f icons.mak
-cd ..\Tools\msi
-del *.msi
-nmake /f msisupport.mak
-%HOST_PYTHON% msi.py
-
+ at rem Used by the buildbot "buildmsi" step.
+
+cmd /c Tools\buildbot\external.bat
+ at rem build release versions of things
+call "%VS90COMNTOOLS%vsvars32.bat"
+
+ at rem build Python
+vcbuild /useenv PCbuild\pcbuild.sln "Release|Win32"
+
+ at rem build the documentation
+bash.exe -c 'cd Doc;make PYTHON=python2.5 update htmlhelp'
+"%ProgramFiles%\HTML Help Workshop\hhc.exe" Doc\build\htmlhelp\python26a3.hhp
+
+ at rem build the MSI file
+cd PC
+nmake /f icons.mak
+cd ..\Tools\msi
+del *.msi
+nmake /f msisupport.mak
+%HOST_PYTHON% msi.py
+

Modified: python/branches/pep-3151/Tools/buildbot/clean-amd64.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/clean-amd64.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/clean-amd64.bat	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,7 @@
- at rem Used by the buildbot "clean" step.
-call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
-cd PCbuild
- at echo Deleting .pyc/.pyo files ...
-del /s Lib\*.pyc Lib\*.pyo
-vcbuild /clean pcbuild.sln "Release|x64"
-vcbuild /clean pcbuild.sln "Debug|x64"
+ at rem Used by the buildbot "clean" step.
+call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
+cd PCbuild
+ at echo Deleting .pyc/.pyo files ...
+del /s Lib\*.pyc Lib\*.pyo
+vcbuild /clean pcbuild.sln "Release|x64"
+vcbuild /clean pcbuild.sln "Debug|x64"

Modified: python/branches/pep-3151/Tools/buildbot/clean.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/clean.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/clean.bat	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,7 @@
- at rem Used by the buildbot "clean" step.
-call "%VS90COMNTOOLS%vsvars32.bat"
- at echo Deleting .pyc/.pyo files ...
-del /s Lib\*.pyc Lib\*.pyo
-cd PCbuild
-vcbuild /clean pcbuild.sln "Release|Win32"
-vcbuild /clean pcbuild.sln "Debug|Win32"
+ at rem Used by the buildbot "clean" step.
+call "%VS90COMNTOOLS%vsvars32.bat"
+ at echo Deleting .pyc/.pyo files ...
+del /s Lib\*.pyc Lib\*.pyo
+cd PCbuild
+vcbuild /clean pcbuild.sln "Release|Win32"
+vcbuild /clean pcbuild.sln "Debug|Win32"

Modified: python/branches/pep-3151/Tools/buildbot/external-amd64.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/external-amd64.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/external-amd64.bat	Sat Feb 26 08:16:32 2011
@@ -1,21 +1,21 @@
- at rem Fetches (and builds if necessary) external dependencies
-
- at rem Assume we start inside the Python source directory
-call "Tools\buildbot\external-common.bat"
-call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
-
-if not exist tcltk64\bin\tcl85g.dll (
-    cd tcl-8.5.2.1\win
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 install
-    cd ..\..
-)
-
-if not exist tcltk64\bin\tk85g.dll (
-    cd tk-8.5.2.0\win    
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.2.1 clean
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.2.1 all
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.2.1 install
-    cd ..\..
-)
-
+ at rem Fetches (and builds if necessary) external dependencies
+
+ at rem Assume we start inside the Python source directory
+call "Tools\buildbot\external-common.bat"
+call "%VS90COMNTOOLS%\..\..\VC\vcvarsall.bat" x86_amd64
+
+if not exist tcltk64\bin\tcl85g.dll (
+    cd tcl-8.5.9.0\win
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 clean all
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 install
+    cd ..\..
+)
+
+if not exist tcltk64\bin\tk85g.dll (
+    cd tk-8.5.9.0\win    
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.9.0 clean
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.9.0 all
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 MACHINE=AMD64 INSTALLDIR=..\..\tcltk64 TCLDIR=..\..\tcl-8.5.9.0 install
+    cd ..\..
+)
+

Modified: python/branches/pep-3151/Tools/buildbot/external-common.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/external-common.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/external-common.bat	Sat Feb 26 08:16:32 2011
@@ -1,43 +1,43 @@
- at rem Common file shared between external.bat and external-amd64.bat.  Responsible for
- at rem fetching external components into the root\.. buildbot directories.
-
-cd ..
- at rem XXX: If you need to force the buildbots to start from a fresh environment, uncomment
- at rem the following, check it in, then check it out, comment it out, then check it back in.
- at rem if exist bzip2-1.0.5 rd /s/q bzip2-1.0.5
- at rem if exist tcltk rd /s/q tcltk
- at rem if exist tcltk64 rd /s/q tcltk64
- at rem if exist tcl8.4.12 rd /s/q tcl8.4.12
- at rem if exist tcl8.4.16 rd /s/q tcl8.4.16
- at rem if exist tcl-8.4.18.1 rd /s/q tcl-8.4.18.1
- at rem if exist tk8.4.12 rd /s/q tk8.4.12
- at rem if exist tk8.4.16 rd /s/q tk8.4.16
- at rem if exist tk-8.4.18.1 rd /s/q tk-8.4.18.1
- at rem if exist db-4.4.20 rd /s/q db-4.4.20
- at rem if exist openssl-1.0.0a rd /s/q openssl-1.0.0a
- at rem if exist sqlite-3.6.21 rd /s/q sqlite-3.6.21    
-
- at rem bzip
-if not exist bzip2-1.0.5 (
-   rd /s/q bzip2-1.0.3
-  svn export http://svn.python.org/projects/external/bzip2-1.0.5
-)
-
- at rem Sleepycat db
-if not exist db-4.4.20 svn export http://svn.python.org/projects/external/db-4.4.20-vs9 db-4.4.20
-
- at rem OpenSSL
-if not exist openssl-1.0.0a svn export http://svn.python.org/projects/external/openssl-1.0.0a
-
- at rem tcl/tk
-if not exist tcl-8.5.2.1 (
-   rd /s/q tcltk tcltk64
-   svn export http://svn.python.org/projects/external/tcl-8.5.2.1
-)
-if not exist tk-8.5.2.0 svn export http://svn.python.org/projects/external/tk-8.5.2.0
-
- at rem sqlite3
-if not exist sqlite-3.6.21 (
-  rd /s/q sqlite-source-3.3.4
-  svn export http://svn.python.org/projects/external/sqlite-3.6.21
-)
+ at rem Common file shared between external.bat and external-amd64.bat.  Responsible for
+ at rem fetching external components into the root\.. buildbot directories.
+
+cd ..
+ at rem XXX: If you need to force the buildbots to start from a fresh environment, uncomment
+ at rem the following, check it in, then check it out, comment it out, then check it back in.
+ at rem if exist bzip2-1.0.5 rd /s/q bzip2-1.0.5
+ at rem if exist tcltk rd /s/q tcltk
+ at rem if exist tcltk64 rd /s/q tcltk64
+ at rem if exist tcl8.4.12 rd /s/q tcl8.4.12
+ at rem if exist tcl8.4.16 rd /s/q tcl8.4.16
+ at rem if exist tcl-8.4.18.1 rd /s/q tcl-8.4.18.1
+ at rem if exist tk8.4.12 rd /s/q tk8.4.12
+ at rem if exist tk8.4.16 rd /s/q tk8.4.16
+ at rem if exist tk-8.4.18.1 rd /s/q tk-8.4.18.1
+ at rem if exist db-4.4.20 rd /s/q db-4.4.20
+ at rem if exist openssl-1.0.0a rd /s/q openssl-1.0.0a
+ at rem if exist sqlite-3.7.4 rd /s/q sqlite-3.7.4    
+
+ at rem bzip
+if not exist bzip2-1.0.5 (
+   rd /s/q bzip2-1.0.3
+  svn export http://svn.python.org/projects/external/bzip2-1.0.5
+)
+
+ at rem Sleepycat db
+if not exist db-4.4.20 svn export http://svn.python.org/projects/external/db-4.4.20-vs9 db-4.4.20
+
+ at rem OpenSSL
+if not exist openssl-1.0.0a svn export http://svn.python.org/projects/external/openssl-1.0.0a
+
+ at rem tcl/tk
+if not exist tcl-8.5.9.0 (
+   rd /s/q tcltk tcltk64
+   svn export http://svn.python.org/projects/external/tcl-8.5.9.0
+)
+if not exist tk-8.5.9.0 svn export http://svn.python.org/projects/external/tk-8.5.9.0
+
+ at rem sqlite3
+if not exist sqlite-3.7.4 (
+  rd /s/q sqlite-source-3.6.21
+  svn export http://svn.python.org/projects/external/sqlite-3.7.4
+)

Modified: python/branches/pep-3151/Tools/buildbot/external.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/external.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/external.bat	Sat Feb 26 08:16:32 2011
@@ -1,21 +1,21 @@
- at rem Fetches (and builds if necessary) external dependencies
-
- at rem Assume we start inside the Python source directory
-call "Tools\buildbot\external-common.bat"
-call "%VS90COMNTOOLS%\vsvars32.bat"
-
-if not exist tcltk\bin\tcl85g.dll (
-    @rem all and install need to be separate invocations, otherwise nmakehlp is not found on install
-    cd tcl-8.5.2.1\win
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 INSTALLDIR=..\..\tcltk clean all 
-    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk install
-    cd ..\..
-)
-
-if not exist tcltk\bin\tk85g.dll (
-    cd tk-8.5.2.0\win    
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.2.1 clean
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.2.1 all
-    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.2.1 install
-    cd ..\..
-)
+ at rem Fetches (and builds if necessary) external dependencies
+
+ at rem Assume we start inside the Python source directory
+call "Tools\buildbot\external-common.bat"
+call "%VS90COMNTOOLS%\vsvars32.bat"
+
+if not exist tcltk\bin\tcl85g.dll (
+    @rem all and install need to be separate invocations, otherwise nmakehlp is not found on install
+    cd tcl-8.5.9.0\win
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 DEBUG=1 INSTALLDIR=..\..\tcltk clean all 
+    nmake -f makefile.vc DEBUG=1 INSTALLDIR=..\..\tcltk install
+    cd ..\..
+)
+
+if not exist tcltk\bin\tk85g.dll (
+    cd tk-8.5.9.0\win    
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.9.0 clean
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.9.0 all
+    nmake -f makefile.vc COMPILERFLAGS=-DWINVER=0x0500 OPTS=noxp DEBUG=1 INSTALLDIR=..\..\tcltk TCLDIR=..\..\tcl-8.5.9.0 install
+    cd ..\..
+)

Modified: python/branches/pep-3151/Tools/buildbot/test-amd64.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/test-amd64.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/test-amd64.bat	Sat Feb 26 08:16:32 2011
@@ -1,3 +1,3 @@
- at rem Used by the buildbot "test" step.
-cd PCbuild
-call rt.bat -q -d -x64 -uall -rw
+ at rem Used by the buildbot "test" step.
+cd PCbuild
+call rt.bat -q -d -x64 -uall -rw

Modified: python/branches/pep-3151/Tools/buildbot/test.bat
==============================================================================
--- python/branches/pep-3151/Tools/buildbot/test.bat	(original)
+++ python/branches/pep-3151/Tools/buildbot/test.bat	Sat Feb 26 08:16:32 2011
@@ -1,4 +1,4 @@
- at rem Used by the buildbot "test" step.
-cd PCbuild
-call rt.bat -d -q -uall -rw -n
-
+ at rem Used by the buildbot "test" step.
+cd PCbuild
+call rt.bat -d -q -uall -rwW -n
+

Modified: python/branches/pep-3151/Tools/ccbench/ccbench.py
==============================================================================
--- python/branches/pep-3151/Tools/ccbench/ccbench.py	(original)
+++ python/branches/pep-3151/Tools/ccbench/ccbench.py	Sat Feb 26 08:16:32 2011
@@ -276,19 +276,19 @@
     return sock.recv(n).decode('ascii')
 
 def latency_client(addr, nb_pings, interval):
-    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
-    _time = time.time
-    _sleep = time.sleep
-    def _ping():
-        _sendto(sock, "%r\n" % _time(), addr)
-    # The first ping signals the parent process that we are ready.
-    _ping()
-    # We give the parent a bit of time to notice.
-    _sleep(1.0)
-    for i in range(nb_pings):
-        _sleep(interval)
+    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
+        _time = time.time
+        _sleep = time.sleep
+        def _ping():
+            _sendto(sock, "%r\n" % _time(), addr)
+        # The first ping signals the parent process that we are ready.
         _ping()
-    _sendto(sock, LAT_END + "\n", addr)
+        # We give the parent a bit of time to notice.
+        _sleep(1.0)
+        for i in range(nb_pings):
+            _sleep(interval)
+            _ping()
+        _sendto(sock, LAT_END + "\n", addr)
 
 def run_latency_client(**kwargs):
     cmd_line = [sys.executable, '-E', os.path.abspath(__file__)]
@@ -363,6 +363,7 @@
     for t in threads:
         t.join()
     process.wait()
+    sock.close()
 
     for recv_time, chunk in chunks:
         # NOTE: it is assumed that a line sent by a client wasn't received

Modified: python/branches/pep-3151/Tools/msi/msi.py
==============================================================================
--- python/branches/pep-3151/Tools/msi/msi.py	(original)
+++ python/branches/pep-3151/Tools/msi/msi.py	Sat Feb 26 08:16:32 2011
@@ -1025,6 +1025,7 @@
             lib.glob("*.pem")
             lib.glob("*.pck")
             lib.glob("cfgparser.*")
+            lib.add_file("zip_cp437_header.zip")
             lib.add_file("zipdir.zip")
         if dir=='capath':
             lib.glob("*.0")
@@ -1054,6 +1055,10 @@
         if dir=="macholib":
             lib.add_file("README.ctypes")
             lib.glob("fetch_macholib*")
+        if dir=='turtledemo':
+            lib.add_file("turtle.cfg")
+        if dir=="pydoc_data":
+            lib.add_file("_pydoc.css")
         if dir=="data" and parent.physical=="test" and parent.basedir.physical=="email":
             # This should contain all non-.svn files listed in subversion
             for f in os.listdir(lib.absolute):
@@ -1082,6 +1087,7 @@
             continue
         dlls.append(f)
         lib.add_file(f)
+    lib.add_file('python3.dll')
     # Add sqlite
     if msilib.msi_type=="Intel64;1033":
         sqlite_arch = "/ia64"
@@ -1118,6 +1124,7 @@
     for f in dlls:
         lib.add_file(f.replace('pyd','lib'))
     lib.add_file('python%s%s.lib' % (major, minor))
+    lib.add_file('python3.lib')
     # Add the mingw-format library
     if have_mingw:
         lib.add_file('libpython%s%s.a' % (major, minor))

Modified: python/branches/pep-3151/Tools/msi/uuids.py
==============================================================================
--- python/branches/pep-3151/Tools/msi/uuids.py	(original)
+++ python/branches/pep-3151/Tools/msi/uuids.py	Sat Feb 26 08:16:32 2011
@@ -80,9 +80,11 @@
     '3.2.101' :'{b411f168-7a36-4fff-902c-a554d1c78a4f}', # 3.2a1
     '3.2.102' :'{79ff73b7-8359-410f-b9c5-152d2026f8c8}', # 3.2a2
     '3.2.103' :'{e7635c65-c221-4b9b-b70a-5611b8369d77}', # 3.2a3
+    '3.2.104' :'{748cd139-75b8-4ca8-98a7-58262298181e}', # 3.2a4
     '3.2.111' :'{20bfc16f-c7cd-4fc0-8f96-9914614a3c50}', # 3.2b1
     '3.2.112' :'{0e350c98-8d73-4993-b686-cfe87160046e}', # 3.2b2
     '3.2.121' :'{2094968d-7583-47f6-a7fd-22304532e09f}', # 3.2rc1
     '3.2.122' :'{4f3edfa6-cf70-469a-825f-e1206aa7f412}', # 3.2rc2
+    '3.2.123' :'{90c673d7-8cfd-4969-9816-f7d70bad87f3}', # 3.2rc3
     '3.2.150' :'{b2042d5e-986d-44ec-aee3-afe4108ccc93}', # 3.2.0
 }

Modified: python/branches/pep-3151/Tools/scripts/README
==============================================================================
--- python/branches/pep-3151/Tools/scripts/README	(original)
+++ python/branches/pep-3151/Tools/scripts/README	Sat Feb 26 08:16:32 2011
@@ -2,8 +2,6 @@
 useful while building, extending or managing Python.  Some (e.g., dutree or lll)
 are also generally useful UNIX tools.
 
-See also the Demo/scripts directory!
-
 2to3                    Main script for running the 2to3 conversion tool
 analyze_dxp.py          Analyzes the result of sys.getdxp()
 byext.py                Print lines/words/chars stats of files by extension

Modified: python/branches/pep-3151/Tools/scripts/find_recursionlimit.py
==============================================================================
--- python/branches/pep-3151/Tools/scripts/find_recursionlimit.py	(original)
+++ python/branches/pep-3151/Tools/scripts/find_recursionlimit.py	Sat Feb 26 08:16:32 2011
@@ -77,14 +77,15 @@
     except ImportError:
         print("cannot import _pickle, skipped!")
         return
-    l = None
+    k, l = None, None
     for n in itertools.count():
         try:
             l = _cache[n]
             continue  # Already tried and it works, let's save some time
         except KeyError:
             for i in range(100):
-                l = [l]
+                l = [k, l]
+                k = {i: l}
         _pickle.Pickler(io.BytesIO(), protocol=-1).dump(l)
         _cache[n] = l
 

Modified: python/branches/pep-3151/Tools/scripts/patchcheck.py
==============================================================================
--- python/branches/pep-3151/Tools/scripts/patchcheck.py	(original)
+++ python/branches/pep-3151/Tools/scripts/patchcheck.py	Sat Feb 26 08:16:32 2011
@@ -45,13 +45,16 @@
         sys.exit('need a checkout to get modified files')
 
     st = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
-    st.wait()
-    if vcs == 'hg':
-        return [x.decode().rstrip() for x in st.stdout]
-    else:
-        output = (x.decode().rstrip().rsplit(None, 1)[-1]
-                  for x in st.stdout if x[0] in b'AM')
+    try:
+        st.wait()
+        if vcs == 'hg':
+            return [x.decode().rstrip() for x in st.stdout]
+        else:
+            output = (x.decode().rstrip().rsplit(None, 1)[-1]
+                      for x in st.stdout if x[0] in b'AM')
         return set(path for path in output if os.path.isfile(path))
+    finally:
+        st.stdout.close()
 
 
 def report_modified_files(file_paths):

Deleted: python/branches/pep-3151/Tools/scripts/redemo.py
==============================================================================
--- python/branches/pep-3151/Tools/scripts/redemo.py	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,171 +0,0 @@
-"""Basic regular expression demostration facility (Perl style syntax)."""
-
-from tkinter import *
-import re
-
-class ReDemo:
-
-    def __init__(self, master):
-        self.master = master
-
-        self.promptdisplay = Label(self.master, anchor=W,
-                text="Enter a Perl-style regular expression:")
-        self.promptdisplay.pack(side=TOP, fill=X)
-
-        self.regexdisplay = Entry(self.master)
-        self.regexdisplay.pack(fill=X)
-        self.regexdisplay.focus_set()
-
-        self.addoptions()
-
-        self.statusdisplay = Label(self.master, text="", anchor=W)
-        self.statusdisplay.pack(side=TOP, fill=X)
-
-        self.labeldisplay = Label(self.master, anchor=W,
-                text="Enter a string to search:")
-        self.labeldisplay.pack(fill=X)
-        self.labeldisplay.pack(fill=X)
-
-        self.showframe = Frame(master)
-        self.showframe.pack(fill=X, anchor=W)
-
-        self.showvar = StringVar(master)
-        self.showvar.set("first")
-
-        self.showfirstradio = Radiobutton(self.showframe,
-                                         text="Highlight first match",
-                                          variable=self.showvar,
-                                          value="first",
-                                          command=self.recompile)
-        self.showfirstradio.pack(side=LEFT)
-
-        self.showallradio = Radiobutton(self.showframe,
-                                        text="Highlight all matches",
-                                        variable=self.showvar,
-                                        value="all",
-                                        command=self.recompile)
-        self.showallradio.pack(side=LEFT)
-
-        self.stringdisplay = Text(self.master, width=60, height=4)
-        self.stringdisplay.pack(fill=BOTH, expand=1)
-        self.stringdisplay.tag_configure("hit", background="yellow")
-
-        self.grouplabel = Label(self.master, text="Groups:", anchor=W)
-        self.grouplabel.pack(fill=X)
-
-        self.grouplist = Listbox(self.master)
-        self.grouplist.pack(expand=1, fill=BOTH)
-
-        self.regexdisplay.bind('<Key>', self.recompile)
-        self.stringdisplay.bind('<Key>', self.reevaluate)
-
-        self.compiled = None
-        self.recompile()
-
-        btags = self.regexdisplay.bindtags()
-        self.regexdisplay.bindtags(btags[1:] + btags[:1])
-
-        btags = self.stringdisplay.bindtags()
-        self.stringdisplay.bindtags(btags[1:] + btags[:1])
-
-    def addoptions(self):
-        self.frames = []
-        self.boxes = []
-        self.vars = []
-        for name in ('IGNORECASE',
-                     'LOCALE',
-                     'MULTILINE',
-                     'DOTALL',
-                     'VERBOSE'):
-            if len(self.boxes) % 3 == 0:
-                frame = Frame(self.master)
-                frame.pack(fill=X)
-                self.frames.append(frame)
-            val = getattr(re, name)
-            var = IntVar()
-            box = Checkbutton(frame,
-                    variable=var, text=name,
-                    offvalue=0, onvalue=val,
-                    command=self.recompile)
-            box.pack(side=LEFT)
-            self.boxes.append(box)
-            self.vars.append(var)
-
-    def getflags(self):
-        flags = 0
-        for var in self.vars:
-            flags = flags | var.get()
-        flags = flags
-        return flags
-
-    def recompile(self, event=None):
-        try:
-            self.compiled = re.compile(self.regexdisplay.get(),
-                                       self.getflags())
-            bg = self.promptdisplay['background']
-            self.statusdisplay.config(text="", background=bg)
-        except re.error as msg:
-            self.compiled = None
-            self.statusdisplay.config(
-                    text="re.error: %s" % str(msg),
-                    background="red")
-        self.reevaluate()
-
-    def reevaluate(self, event=None):
-        try:
-            self.stringdisplay.tag_remove("hit", "1.0", END)
-        except TclError:
-            pass
-        try:
-            self.stringdisplay.tag_remove("hit0", "1.0", END)
-        except TclError:
-            pass
-        self.grouplist.delete(0, END)
-        if not self.compiled:
-            return
-        self.stringdisplay.tag_configure("hit", background="yellow")
-        self.stringdisplay.tag_configure("hit0", background="orange")
-        text = self.stringdisplay.get("1.0", END)
-        last = 0
-        nmatches = 0
-        while last <= len(text):
-            m = self.compiled.search(text, last)
-            if m is None:
-                break
-            first, last = m.span()
-            if last == first:
-                last = first+1
-                tag = "hit0"
-            else:
-                tag = "hit"
-            pfirst = "1.0 + %d chars" % first
-            plast = "1.0 + %d chars" % last
-            self.stringdisplay.tag_add(tag, pfirst, plast)
-            if nmatches == 0:
-                self.stringdisplay.yview_pickplace(pfirst)
-                groups = list(m.groups())
-                groups.insert(0, m.group())
-                for i in range(len(groups)):
-                    g = "%2d: %r" % (i, groups[i])
-                    self.grouplist.insert(END, g)
-            nmatches = nmatches + 1
-            if self.showvar.get() == "first":
-                break
-
-        if nmatches == 0:
-            self.statusdisplay.config(text="(no match)",
-                                      background="yellow")
-        else:
-            self.statusdisplay.config(text="")
-
-
-# Main function, run when invoked as a stand-alone Python program.
-
-def main():
-    root = Tk()
-    demo = ReDemo(root)
-    root.protocol('WM_DELETE_WINDOW', root.quit)
-    root.mainloop()
-
-if __name__ == '__main__':
-    main()

Modified: python/branches/pep-3151/Tools/scripts/untabify.py
==============================================================================
--- python/branches/pep-3151/Tools/scripts/untabify.py	(original)
+++ python/branches/pep-3151/Tools/scripts/untabify.py	Sat Feb 26 08:16:32 2011
@@ -5,7 +5,7 @@
 import os
 import sys
 import getopt
-
+import tokenize
 
 def main():
     tabsize = 8
@@ -27,8 +27,9 @@
 
 def process(filename, tabsize, verbose=True):
     try:
-        with open(filename) as f:
+        with tokenize.open(filename) as f:
             text = f.read()
+            encoding = f.encoding
     except IOError as msg:
         print("%r: I/O error: %s" % (filename, msg))
         return
@@ -44,7 +45,7 @@
         os.rename(filename, backup)
     except os.error:
         pass
-    with open(filename, "w") as f:
+    with open(filename, "w", encoding=encoding) as f:
         f.write(newtext)
     if verbose:
         print(filename)

Modified: python/branches/pep-3151/Tools/unicode/gencodec.py
==============================================================================
--- python/branches/pep-3151/Tools/unicode/gencodec.py	(original)
+++ python/branches/pep-3151/Tools/unicode/gencodec.py	Sat Feb 26 08:16:32 2011
@@ -34,6 +34,9 @@
 # Standard undefined Unicode code point
 UNI_UNDEFINED = chr(0xFFFE)
 
+# Placeholder for a missing codepoint
+MISSING_CODE = -1
+
 mapRE = re.compile('((?:0x[0-9a-fA-F]+\+?)+)'
                    '\s+'
                    '((?:(?:0x[0-9a-fA-Z]+|<[A-Za-z]+>)\+?)*)'
@@ -52,7 +55,7 @@
 
     """
     if not codes:
-        return None
+        return MISSING_CODE
     l = codes.split('+')
     if len(l) == 1:
         return int(l[0],16)
@@ -60,8 +63,8 @@
         try:
             l[i] = int(l[i],16)
         except ValueError:
-            l[i] = None
-    l = [x for x in l if x is not None]
+            l[i] = MISSING_CODE
+    l = [x for x in l if x != MISSING_CODE]
     if len(l) == 1:
         return l[0]
     else:
@@ -113,7 +116,7 @@
     # mappings to None for the rest
     if len(identity) >= len(unmapped):
         for enc in unmapped:
-            enc2uni[enc] = (None, "")
+            enc2uni[enc] = (MISSING_CODE, "")
         enc2uni['IDENTITY'] = 256
 
     return enc2uni
@@ -211,7 +214,7 @@
             (mapkey, mapcomment) = mapkey
         if isinstance(mapvalue, tuple):
             (mapvalue, mapcomment) = mapvalue
-        if mapkey is None:
+        if mapkey == MISSING_CODE:
             continue
         table[mapkey] = (mapvalue, mapcomment)
         if mapkey > maxkey:
@@ -223,11 +226,11 @@
     # Create table code
     for key in range(maxkey + 1):
         if key not in table:
-            mapvalue = None
+            mapvalue = MISSING_CODE
             mapcomment = 'UNDEFINED'
         else:
             mapvalue, mapcomment = table[key]
-        if mapvalue is None:
+        if mapvalue == MISSING_CODE:
             mapchar = UNI_UNDEFINED
         else:
             if isinstance(mapvalue, tuple):

Modified: python/branches/pep-3151/Tools/unicode/genwincodecs.bat
==============================================================================
--- python/branches/pep-3151/Tools/unicode/genwincodecs.bat	(original)
+++ python/branches/pep-3151/Tools/unicode/genwincodecs.bat	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,7 @@
- at rem Recreate some python charmap codecs from the Windows function
- at rem MultiByteToWideChar.
-
- at cd /d %~dp0
- at mkdir build
- at rem Arabic DOS code page
-c:\python30\python genwincodec.py 720 > build/cp720.py
+ at rem Recreate some python charmap codecs from the Windows function
+ at rem MultiByteToWideChar.
+
+ at cd /d %~dp0
+ at mkdir build
+ at rem Arabic DOS code page
+c:\python30\python genwincodec.py 720 > build/cp720.py

Modified: python/branches/pep-3151/Tools/unicode/makeunicodedata.py
==============================================================================
--- python/branches/pep-3151/Tools/unicode/makeunicodedata.py	(original)
+++ python/branches/pep-3151/Tools/unicode/makeunicodedata.py	Sat Feb 26 08:16:32 2011
@@ -70,6 +70,15 @@
 NODELTA_MASK = 0x800
 NUMERIC_MASK = 0x1000
 
+# these ranges need to match unicodedata.c:is_unified_ideograph
+cjk_ranges = [
+    ('3400', '4DB5'),
+    ('4E00', '9FCB'),
+    ('20000', '2A6D6'),
+    ('2A700', '2B734'),
+    ('2B740', '2B81D')
+]
+
 def maketables(trace=0):
 
     print("--- Reading", UNICODE_DATA % "", "...")
@@ -81,7 +90,7 @@
 
     for version in old_versions:
         print("--- Reading", UNICODE_DATA % ("-"+version), "...")
-        old_unicode = UnicodeData(version)
+        old_unicode = UnicodeData(version, cjk_check=False)
         print(len(list(filter(None, old_unicode.table))), "characters")
         merge_old_version(version, unicode, old_unicode)
 
@@ -804,7 +813,8 @@
 
     def __init__(self, version,
                  linebreakprops=False,
-                 expand=1):
+                 expand=1,
+                 cjk_check=True):
         self.changed = []
         file = open_data(UNICODE_DATA, version)
         table = [None] * 0x110000
@@ -816,6 +826,8 @@
             char = int(s[0], 16)
             table[char] = s
 
+        cjk_ranges_found = []
+
         # expand first-last ranges
         if expand:
             field = None
@@ -826,12 +838,17 @@
                         s[1] = ""
                         field = s
                     elif s[1][-5:] == "Last>":
+                        if s[1].startswith("<CJK Ideograph"):
+                            cjk_ranges_found.append((field[0],
+                                                     s[0]))
                         s[1] = ""
                         field = None
                 elif field:
                     f2 = field[:]
                     f2[0] = "%X" % i
                     table[i] = f2
+            if cjk_check and cjk_ranges != cjk_ranges_found:
+                raise ValueError("CJK ranges deviate: have %r" % cjk_ranges_found)
 
         # public attributes
         self.filename = UNICODE_DATA % ''

Modified: python/branches/pep-3151/configure
==============================================================================
--- python/branches/pep-3151/configure	(original)
+++ python/branches/pep-3151/configure	Sat Feb 26 08:16:32 2011
@@ -1,7 +1,7 @@
 #! /bin/sh
-# From configure.in Revision: 86045 .
+# From configure.in Revision: 88624 .
 # Guess values for system-dependent variables and create Makefiles.
-# Generated by GNU Autoconf 2.65 for python 3.2.
+# Generated by GNU Autoconf 2.65 for python 3.3.
 #
 # Report bugs to <http://bugs.python.org/>.
 #
@@ -553,8 +553,8 @@
 # Identity of this package.
 PACKAGE_NAME='python'
 PACKAGE_TARNAME='python'
-PACKAGE_VERSION='3.2'
-PACKAGE_STRING='python 3.2'
+PACKAGE_VERSION='3.3'
+PACKAGE_STRING='python 3.3'
 PACKAGE_BUGREPORT='http://bugs.python.org/'
 PACKAGE_URL=''
 
@@ -647,6 +647,7 @@
 RUNSHARED
 INSTSONAME
 LDLIBRARYDIR
+PY3LIBRARY
 BLDLIBRARY
 DLLLIBRARY
 LDLIBRARY
@@ -1307,7 +1308,7 @@
   # Omit some internal or obsolete options to make the list less imposing.
   # This message is too long to be a string in the A/UX 3.1 sh.
   cat <<_ACEOF
-\`configure' configures python 3.2 to adapt to many kinds of systems.
+\`configure' configures python 3.3 to adapt to many kinds of systems.
 
 Usage: $0 [OPTION]... [VAR=VALUE]...
 
@@ -1368,7 +1369,7 @@
 
 if test -n "$ac_init_help"; then
   case $ac_init_help in
-     short | recursive ) echo "Configuration of python 3.2:";;
+     short | recursive ) echo "Configuration of python 3.3:";;
    esac
   cat <<\_ACEOF
 
@@ -1506,7 +1507,7 @@
 test -n "$ac_init_help" && exit $ac_status
 if $ac_init_version; then
   cat <<\_ACEOF
-python configure 3.2
+python configure 3.3
 generated by GNU Autoconf 2.65
 
 Copyright (C) 2009 Free Software Foundation, Inc.
@@ -1935,11 +1936,11 @@
        cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 $ac_includes_default
-	     enum { N = $2 / 2 - 1 };
 int
 main ()
 {
-static int test_array [1 - 2 * !(0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))];
+static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 };
+	     0 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1))];
 test_array [0] = 0
 
   ;
@@ -1950,11 +1951,11 @@
   cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 $ac_includes_default
-	        enum { N = $2 / 2 - 1 };
 int
 main ()
 {
-static int test_array [1 - 2 * !(($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1)
+static int test_array [1 - 2 * !(enum { N = $2 / 2 - 1 };
+		($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 1)
 		 < ($ac_type) ((((($ac_type) 1 << N) << N) - 1) * 2 + 2))];
 test_array [0] = 0
 
@@ -2334,7 +2335,7 @@
 This file contains any messages produced by compilers while
 running configure, to aid debugging if configure makes a mistake.
 
-It was created by python $as_me 3.2, which was
+It was created by python $as_me 3.3, which was
 generated by GNU Autoconf 2.65.  Invocation command line was
 
   $ $0 $@
@@ -2700,7 +2701,7 @@
 mv confdefs.h.new confdefs.h
 
 
-VERSION=3.2
+VERSION=3.3
 
 # Version number of Python's own shared library file.
 
@@ -4707,13 +4708,14 @@
 
 
 
+
 LDLIBRARY="$LIBRARY"
 BLDLIBRARY='$(LDLIBRARY)'
 INSTSONAME='$(LDLIBRARY)'
 DLLLIBRARY=''
 LDLIBRARYDIR=''
 RUNSHARED=''
-LDVERSION="$(VERSION)"
+LDVERSION="$VERSION"
 
 # LINKCC is the command that links the python executable -- default is $(CC).
 # If CXX is set, and if it is needed to link a main function that was
@@ -4903,6 +4905,10 @@
 	  BLDLIBRARY='-Wl,-R,$(LIBDIR) -L. -lpython$(LDVERSION)'
 	  RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH}
 	  INSTSONAME="$LDLIBRARY".$SOVERSION
+	  if test "$with_pydebug" != yes
+	  then
+	      PY3LIBRARY=libpython3.so
+	  fi
           ;;
     Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*)
 	  LDLIBRARY='libpython$(LDVERSION).so'
@@ -4914,6 +4920,10 @@
 		;;
 	  esac
 	  INSTSONAME="$LDLIBRARY".$SOVERSION
+	  if test "$with_pydebug" != yes
+          then
+	      PY3LIBRARY=libpython3.so
+	  fi
 	  ;;
     hp*|HP*)
 	  case `uname -m` in
@@ -5988,10 +5998,10 @@
 unistd.h utime.h \
 sys/audioio.h sys/bsdtty.h sys/epoll.h sys/event.h sys/file.h sys/loadavg.h \
 sys/lock.h sys/mkdev.h sys/modem.h \
-sys/param.h sys/poll.h sys/select.h sys/socket.h sys/statvfs.h sys/stat.h \
-sys/termio.h sys/time.h \
-sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \
-sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \
+sys/param.h sys/poll.h sys/select.h sys/sendfile.h sys/socket.h sys/statvfs.h \
+sys/stat.h sys/termio.h sys/time.h \
+sys/times.h sys/types.h sys/uio.h sys/un.h sys/utsname.h sys/wait.h pty.h \
+libutil.h sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \
 bluetooth/bluetooth.h linux/tipc.h spawn.h util.h
 do :
   as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh`
@@ -6389,6 +6399,13 @@
 if test "$use_lfs" = "yes"; then
 # Two defines needed to enable largefile support on various platforms
 # These may affect some typedefs
+case $ac_sys_system/$ac_sys_release in
+AIX*)
+
+$as_echo "#define _LARGE_FILES 1" >>confdefs.h
+
+    ;;
+esac
 
 $as_echo "#define _LARGEFILE_SOURCE 1" >>confdefs.h
 
@@ -7417,7 +7434,7 @@
 then
 	case $ac_sys_system/$ac_sys_release in
 	AIX*)
-		BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:Modules/python.exp -L\$(srcdir)"
+		BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:\$(srcdir)/Modules/python.exp"
 		LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp"
 		;;
 	IRIX/5*) LDSHARED="ld -shared";;
@@ -7524,8 +7541,8 @@
 				esac
 		fi;;
 	NetBSD*|DragonFly*)
-		LDSHARED="cc -shared"
-		LDCXXSHARED="c++ -shared";;
+		LDSHARED='$(CC) -shared'
+		LDCXXSHARED='$(CXX) -shared';;
 	OpenUNIX*|UnixWare*)
 		if test "$GCC" = "yes" ; then
 			LDSHARED='$(CC) -shared'
@@ -7676,6 +7693,51 @@
 
 
 # checks for libraries
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sendfile in -lsendfile" >&5
+$as_echo_n "checking for sendfile in -lsendfile... " >&6; }
+if test "${ac_cv_lib_sendfile_sendfile+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+  ac_check_lib_save_LIBS=$LIBS
+LIBS="-lsendfile  $LIBS"
+cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+/* Override any GCC internal prototype to avoid an error.
+   Use char because int might match the return type of a GCC
+   builtin and then its argument prototype would still apply.  */
+#ifdef __cplusplus
+extern "C"
+#endif
+char sendfile ();
+int
+main ()
+{
+return sendfile ();
+  ;
+  return 0;
+}
+_ACEOF
+if ac_fn_c_try_link "$LINENO"; then :
+  ac_cv_lib_sendfile_sendfile=yes
+else
+  ac_cv_lib_sendfile_sendfile=no
+fi
+rm -f core conftest.err conftest.$ac_objext \
+    conftest$ac_exeext conftest.$ac_ext
+LIBS=$ac_check_lib_save_LIBS
+fi
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_sendfile_sendfile" >&5
+$as_echo "$ac_cv_lib_sendfile_sendfile" >&6; }
+if test "x$ac_cv_lib_sendfile_sendfile" = x""yes; then :
+  cat >>confdefs.h <<_ACEOF
+#define HAVE_LIBSENDFILE 1
+_ACEOF
+
+  LIBS="-lsendfile $LIBS"
+
+fi
+
 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5
 $as_echo_n "checking for dlopen in -ldl... " >&6; }
 if test "${ac_cv_lib_dl_dlopen+set}" = set; then :
@@ -7881,7 +7943,7 @@
 		cat confdefs.h - <<_ACEOF >conftest.$ac_ext
 /* end confdefs.h.  */
 
-		  #include "/usr/lpp/xlC/include/load.h"
+		  #include <load.h>
 int
 main ()
 {
@@ -8965,7 +9027,7 @@
 			;;
 		solaris)
 			if test -f /etc/netconfig; then
-                          if /usr/xpg4/bin/grep -q tcp6 /etc/netconfig; then
+                          if $GREP -q tcp6 /etc/netconfig; then
 				ipv6type=$i
 				ipv6trylibc=yes
                           fi
@@ -9249,18 +9311,19 @@
 
 # checks for library functions
 for ac_func in alarm accept4 setitimer getitimer bind_textdomain_codeset chown \
- clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \
+ clock confstr ctermid execv faccessat fchmod fchmodat fchown fchownat \
+ fdopendir fork fpathconf fstatat ftime ftruncate futimesat \
  gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \
  getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \
- initgroups kill killpg lchmod lchown lstat mbrtowc mkfifo mknod mktime \
- mremap nice pathconf pause plock poll pthread_init \
- putenv readlink realpath \
- select sem_open sem_timedwait sem_getvalue sem_unlink setegid seteuid \
+ initgroups kill killpg lchmod lchown linkat lstat mbrtowc mkdirat mkfifo \
+ mkfifoat mknod mknodat mktime mremap nice openat pathconf pause plock poll \
+ pthread_init putenv readlink readlinkat realpath renameat \
+ select sem_open sem_timedwait sem_getvalue sem_unlink sendfile setegid seteuid \
  setgid \
- setlocale setregid setreuid setresuid setresgid setsid setpgid setpgrp setuid setvbuf \
- sigaction siginterrupt sigrelse snprintf strftime strlcpy \
+ setlocale setregid setreuid setresuid setresgid setsid setpgid setpgrp setpriority setuid setvbuf \
+ sigaction siginterrupt sigrelse snprintf strftime strlcpy symlinkat \
  sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \
- truncate uname unsetenv utimes waitpid wait3 wait4 \
+ truncate uname unlinkat unsetenv utimensat utimes waitpid wait3 wait4 \
  wcscoll wcsftime wcsxfrm _getpty
 do :
   as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
@@ -11772,52 +11835,6 @@
 LIBS_SAVE=$LIBS
 LIBS="$LIBS $LIBM"
 
-# On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of
-# -0. on some architectures.
-{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether tanh preserves the sign of zero" >&5
-$as_echo_n "checking whether tanh preserves the sign of zero... " >&6; }
-if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then :
-  $as_echo_n "(cached) " >&6
-else
-
-if test "$cross_compiling" = yes; then :
-  ac_cv_tanh_preserves_zero_sign=no
-else
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-
-#include <math.h>
-#include <stdlib.h>
-int main() {
-    /* return 0 if either negative zeros don't exist
-       on this platform or if negative zeros exist
-       and tanh(-0.) == -0. */
-  if (atan2(0., -1.) == atan2(-0., -1.) ||
-      atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0);
-  else exit(1);
-}
-
-_ACEOF
-if ac_fn_c_try_run "$LINENO"; then :
-  ac_cv_tanh_preserves_zero_sign=yes
-else
-  ac_cv_tanh_preserves_zero_sign=no
-fi
-rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
-  conftest.$ac_objext conftest.beam conftest.$ac_ext
-fi
-
-fi
-
-{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_tanh_preserves_zero_sign" >&5
-$as_echo "$ac_cv_tanh_preserves_zero_sign" >&6; }
-if test "$ac_cv_tanh_preserves_zero_sign" = yes
-then
-
-$as_echo "#define TANH_PRESERVES_ZERO_SIGN 1" >>confdefs.h
-
-fi
-
 for ac_func in acosh asinh atanh copysign erf erfc expm1 finite gamma
 do :
   as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh`
@@ -11879,6 +11896,101 @@
 _ACEOF
 
 
+# On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of
+# -0. on some architectures.
+{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether tanh preserves the sign of zero" >&5
+$as_echo_n "checking whether tanh preserves the sign of zero... " >&6; }
+if test "${ac_cv_tanh_preserves_zero_sign+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+if test "$cross_compiling" = yes; then :
+  ac_cv_tanh_preserves_zero_sign=no
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+#include <math.h>
+#include <stdlib.h>
+int main() {
+    /* return 0 if either negative zeros don't exist
+       on this platform or if negative zeros exist
+       and tanh(-0.) == -0. */
+  if (atan2(0., -1.) == atan2(-0., -1.) ||
+      atan2(tanh(-0.), -1.) == atan2(-0., -1.)) exit(0);
+  else exit(1);
+}
+
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  ac_cv_tanh_preserves_zero_sign=yes
+else
+  ac_cv_tanh_preserves_zero_sign=no
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+
+{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_tanh_preserves_zero_sign" >&5
+$as_echo "$ac_cv_tanh_preserves_zero_sign" >&6; }
+if test "$ac_cv_tanh_preserves_zero_sign" = yes
+then
+
+$as_echo "#define TANH_PRESERVES_ZERO_SIGN 1" >>confdefs.h
+
+fi
+
+if test "$ac_cv_func_log1p" = yes
+then
+    # On some versions of AIX, log1p(-0.) returns 0. instead of
+    # -0.  See issue #9920.
+    { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether log1p drops the sign of negative zero" >&5
+$as_echo_n "checking whether log1p drops the sign of negative zero... " >&6; }
+    if test "${ac_cv_log1p_drops_zero_sign+set}" = set; then :
+  $as_echo_n "(cached) " >&6
+else
+
+    if test "$cross_compiling" = yes; then :
+  ac_cv_log1p_drops_zero_sign=no
+else
+  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
+/* end confdefs.h.  */
+
+    #include <math.h>
+    #include <stdlib.h>
+    int main() {
+        /* Fail if the signs of log1p(-0.) and -0. can be
+	   distinguished. */
+        if (atan2(log1p(-0.), -1.) == atan2(-0., -1.))
+            return 0;
+        else
+            return 1;
+    }
+
+_ACEOF
+if ac_fn_c_try_run "$LINENO"; then :
+  ac_cv_log1p_drops_zero_sign=no
+else
+  ac_cv_log1p_drops_zero_sign=yes
+fi
+rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \
+  conftest.$ac_objext conftest.beam conftest.$ac_ext
+fi
+
+fi
+
+    { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_log1p_drops_zero_sign" >&5
+$as_echo "$ac_cv_log1p_drops_zero_sign" >&6; }
+fi
+if test "$ac_cv_log1p_drops_zero_sign" = yes
+then
+
+$as_echo "#define LOG1P_DROPS_ZERO_SIGN 1" >>confdefs.h
+
+fi
+
 LIBS=$LIBS_SAVE
 
 # For multiprocessing module, check that sem_open
@@ -13681,6 +13793,12 @@
   OSF*) as_fn_error "OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606" "$LINENO" 5 ;;
 esac
 
+ac_fn_c_check_func "$LINENO" "pipe2" "ac_cv_func_pipe2"
+if test "x$ac_cv_func_pipe2" = x""yes; then :
+
+$as_echo "#define HAVE_PIPE2 1" >>confdefs.h
+
+fi
 
 
 
@@ -14213,7 +14331,7 @@
 # report actual input values of CONFIG_FILES etc. instead of their
 # values after options handling.
 ac_log="
-This file was extended by python $as_me 3.2, which was
+This file was extended by python $as_me 3.3, which was
 generated by GNU Autoconf 2.65.  Invocation command line was
 
   CONFIG_FILES    = $CONFIG_FILES
@@ -14238,8 +14356,8 @@
 
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 # Files that config.status was made for.
-config_files="$ac_config_files"
-config_headers="$ac_config_headers"
+config_files="`echo $ac_config_files`"
+config_headers="`echo $ac_config_headers`"
 
 _ACEOF
 
@@ -14275,7 +14393,7 @@
 cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1
 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`"
 ac_cs_version="\\
-python config.status 3.2
+python config.status 3.3
 configured by $0, generated by GNU Autoconf 2.65,
   with options \\"\$ac_cs_config\\"
 

Modified: python/branches/pep-3151/configure.in
==============================================================================
--- python/branches/pep-3151/configure.in	(original)
+++ python/branches/pep-3151/configure.in	Sat Feb 26 08:16:32 2011
@@ -3,15 +3,8 @@
 dnl ***********************************************
 
 # Set VERSION so we only need to edit in one place (i.e., here)
-m4_define(PYTHON_VERSION, 3.2)
+m4_define(PYTHON_VERSION, 3.3)
 
-dnl Some m4 magic to ensure that the configure script is generated
-dnl by the correct autoconf version.
-m4_define([version_required],
-[m4_if(m4_version_compare(m4_defn([m4_PACKAGE_VERSION]), [$1]), 0,
-       [],
-       [m4_fatal([Autoconf version $1 is required for Python], 63)])
-])
 AC_PREREQ(2.65)
 
 AC_REVISION($Revision$)
@@ -608,6 +601,7 @@
 AC_SUBST(LDLIBRARY)
 AC_SUBST(DLLLIBRARY)
 AC_SUBST(BLDLIBRARY)
+AC_SUBST(PY3LIBRARY)
 AC_SUBST(LDLIBRARYDIR)
 AC_SUBST(INSTSONAME)
 AC_SUBST(RUNSHARED)
@@ -618,7 +612,7 @@
 DLLLIBRARY=''
 LDLIBRARYDIR=''
 RUNSHARED=''
-LDVERSION="$(VERSION)"
+LDVERSION="$VERSION"
 
 # LINKCC is the command that links the python executable -- default is $(CC).
 # If CXX is set, and if it is needed to link a main function that was
@@ -737,6 +731,10 @@
 	  BLDLIBRARY='-Wl,-R,$(LIBDIR) -L. -lpython$(LDVERSION)'
 	  RUNSHARED=LD_LIBRARY_PATH=`pwd`:${LD_LIBRARY_PATH}
 	  INSTSONAME="$LDLIBRARY".$SOVERSION
+	  if test "$with_pydebug" != yes
+	  then
+	      PY3LIBRARY=libpython3.so
+	  fi
           ;;
     Linux*|GNU*|NetBSD*|FreeBSD*|DragonFly*)
 	  LDLIBRARY='libpython$(LDVERSION).so'
@@ -748,6 +746,10 @@
 		;;
 	  esac
 	  INSTSONAME="$LDLIBRARY".$SOVERSION
+	  if test "$with_pydebug" != yes
+          then
+	      PY3LIBRARY=libpython3.so
+	  fi
 	  ;;
     hp*|HP*)
 	  case `uname -m` in
@@ -1281,10 +1283,10 @@
 unistd.h utime.h \
 sys/audioio.h sys/bsdtty.h sys/epoll.h sys/event.h sys/file.h sys/loadavg.h \
 sys/lock.h sys/mkdev.h sys/modem.h \
-sys/param.h sys/poll.h sys/select.h sys/socket.h sys/statvfs.h sys/stat.h \
-sys/termio.h sys/time.h \
-sys/times.h sys/types.h sys/un.h sys/utsname.h sys/wait.h pty.h libutil.h \
-sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \
+sys/param.h sys/poll.h sys/select.h sys/sendfile.h sys/socket.h sys/statvfs.h \
+sys/stat.h sys/termio.h sys/time.h \
+sys/times.h sys/types.h sys/uio.h sys/un.h sys/utsname.h sys/wait.h pty.h \
+libutil.h sys/resource.h netpacket/packet.h sysexits.h bluetooth.h \
 bluetooth/bluetooth.h linux/tipc.h spawn.h util.h)
 AC_HEADER_DIRENT
 AC_HEADER_MAJOR
@@ -1367,6 +1369,12 @@
 if test "$use_lfs" = "yes"; then
 # Two defines needed to enable largefile support on various platforms
 # These may affect some typedefs
+case $ac_sys_system/$ac_sys_release in
+AIX*)
+    AC_DEFINE(_LARGE_FILES, 1, 
+    [This must be defined on AIX systems to enable large file support.])
+    ;;
+esac
 AC_DEFINE(_LARGEFILE_SOURCE, 1, 
 [This must be defined on some systems to enable large file support.])
 AC_DEFINE(_FILE_OFFSET_BITS, 64,
@@ -1633,7 +1641,7 @@
 then
 	case $ac_sys_system/$ac_sys_release in
 	AIX*)
-		BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:Modules/python.exp -L\$(srcdir)"
+		BLDSHARED="\$(srcdir)/Modules/ld_so_aix \$(CC) -bI:\$(srcdir)/Modules/python.exp"
 		LDSHARED="\$(BINLIBDEST)/config/ld_so_aix \$(CC) -bI:\$(BINLIBDEST)/config/python.exp"
 		;;
 	IRIX/5*) LDSHARED="ld -shared";;
@@ -1740,8 +1748,8 @@
 				esac
 		fi;;
 	NetBSD*|DragonFly*)
-		LDSHARED="cc -shared"
-		LDCXXSHARED="c++ -shared";;
+		LDSHARED='$(CC) -shared'
+		LDCXXSHARED='$(CXX) -shared';;
 	OpenUNIX*|UnixWare*)
 		if test "$GCC" = "yes" ; then
 			LDSHARED='$(CC) -shared'
@@ -1883,6 +1891,7 @@
 
 
 # checks for libraries
+AC_CHECK_LIB(sendfile, sendfile)
 AC_CHECK_LIB(dl, dlopen)	# Dynamic linking for SunOS/Solaris and SYSV
 AC_CHECK_LIB(dld, shl_load)	# Dynamic linking for HP-UX
 
@@ -1903,7 +1912,7 @@
 case "$ac_sys_system" in
 	AIX*)	AC_MSG_CHECKING(for genuine AIX C++ extensions support)
 		AC_LINK_IFELSE([
-		  AC_LANG_PROGRAM([[#include "/usr/lpp/xlC/include/load.h"]],
+		  AC_LANG_PROGRAM([[#include <load.h>]],
 				  [[loadAndInit("", 0, "")]])
 		],[
 		  AC_DEFINE(AIX_GENUINE_CPLUSPLUS, 1,
@@ -2340,7 +2349,7 @@
 			;;
 		solaris)
 			if test -f /etc/netconfig; then
-                          if /usr/xpg4/bin/grep -q tcp6 /etc/netconfig; then
+                          if $GREP -q tcp6 /etc/netconfig; then
 				ipv6type=$i
 				ipv6trylibc=yes
                           fi
@@ -2525,18 +2534,19 @@
 
 # checks for library functions
 AC_CHECK_FUNCS(alarm accept4 setitimer getitimer bind_textdomain_codeset chown \
- clock confstr ctermid execv fchmod fchown fork fpathconf ftime ftruncate \
+ clock confstr ctermid execv faccessat fchmod fchmodat fchown fchownat \
+ fdopendir fork fpathconf fstatat ftime ftruncate futimesat \
  gai_strerror getgroups getlogin getloadavg getpeername getpgid getpid \
  getpriority getresuid getresgid getpwent getspnam getspent getsid getwd \
- initgroups kill killpg lchmod lchown lstat mbrtowc mkfifo mknod mktime \
- mremap nice pathconf pause plock poll pthread_init \
- putenv readlink realpath \
- select sem_open sem_timedwait sem_getvalue sem_unlink setegid seteuid \
+ initgroups kill killpg lchmod lchown linkat lstat mbrtowc mkdirat mkfifo \
+ mkfifoat mknod mknodat mktime mremap nice openat pathconf pause plock poll \
+ pthread_init putenv readlink readlinkat realpath renameat \
+ select sem_open sem_timedwait sem_getvalue sem_unlink sendfile setegid seteuid \
  setgid \
- setlocale setregid setreuid setresuid setresgid setsid setpgid setpgrp setuid setvbuf \
- sigaction siginterrupt sigrelse snprintf strftime strlcpy \
+ setlocale setregid setreuid setresuid setresgid setsid setpgid setpgrp setpriority setuid setvbuf \
+ sigaction siginterrupt sigrelse snprintf strftime strlcpy symlinkat \
  sysconf tcgetpgrp tcsetpgrp tempnam timegm times tmpfile tmpnam tmpnam_r \
- truncate uname unsetenv utimes waitpid wait3 wait4 \
+ truncate uname unlinkat unsetenv utimensat utimes waitpid wait3 wait4 \
  wcscoll wcsftime wcsxfrm _getpty)
 
 # For some functions, having a definition is not sufficient, since
@@ -3372,6 +3382,10 @@
 LIBS_SAVE=$LIBS
 LIBS="$LIBS $LIBM"
 
+AC_CHECK_FUNCS([acosh asinh atanh copysign erf erfc expm1 finite gamma])
+AC_CHECK_FUNCS([hypot lgamma log1p round tgamma])
+AC_CHECK_DECLS([isinf, isnan, isfinite], [], [], [[#include <math.h>]])
+
 # On FreeBSD 6.2, it appears that tanh(-0.) returns 0. instead of
 # -0. on some architectures.
 AC_MSG_CHECKING(whether tanh preserves the sign of zero)
@@ -3398,9 +3412,34 @@
   [Define if tanh(-0.) is -0., or if platform doesn't have signed zeros])
 fi
 
-AC_CHECK_FUNCS([acosh asinh atanh copysign erf erfc expm1 finite gamma])
-AC_CHECK_FUNCS([hypot lgamma log1p round tgamma])
-AC_CHECK_DECLS([isinf, isnan, isfinite], [], [], [[#include <math.h>]])
+if test "$ac_cv_func_log1p" = yes
+then
+    # On some versions of AIX, log1p(-0.) returns 0. instead of
+    # -0.  See issue #9920.
+    AC_MSG_CHECKING(whether log1p drops the sign of negative zero)
+    AC_CACHE_VAL(ac_cv_log1p_drops_zero_sign, [
+    AC_RUN_IFELSE([AC_LANG_SOURCE([[
+    #include <math.h>
+    #include <stdlib.h>
+    int main() {
+        /* Fail if the signs of log1p(-0.) and -0. can be
+	   distinguished. */
+        if (atan2(log1p(-0.), -1.) == atan2(-0., -1.))
+            return 0;
+        else
+            return 1;
+    }
+    ]])],
+    [ac_cv_log1p_drops_zero_sign=no],
+    [ac_cv_log1p_drops_zero_sign=yes],
+    [ac_cv_log1p_drops_zero_sign=no])])
+    AC_MSG_RESULT($ac_cv_log1p_drops_zero_sign)
+fi
+if test "$ac_cv_log1p_drops_zero_sign" = yes
+then
+  AC_DEFINE(LOG1P_DROPS_ZERO_SIGN, 1,
+  [Define if log1p(-0.) is 0. rather than -0.])
+fi
 
 LIBS=$LIBS_SAVE
 
@@ -4206,7 +4245,7 @@
   OSF*) AC_MSG_ERROR(OSF* systems are deprecated unless somebody volunteers. Check http://bugs.python.org/issue8606) ;;
 esac
 
-
+AC_CHECK_FUNC(pipe2, AC_DEFINE(HAVE_PIPE2, 1, [Define if the OS supports pipe2()]), )
 
 AC_SUBST(THREADHEADERS)
 

Modified: python/branches/pep-3151/pyconfig.h.in
==============================================================================
--- python/branches/pep-3151/pyconfig.h.in	(original)
+++ python/branches/pep-3151/pyconfig.h.in	Sat Feb 26 08:16:32 2011
@@ -205,21 +205,33 @@
 /* Define to 1 if you have the `expm1' function. */
 #undef HAVE_EXPM1
 
+/* Define to 1 if you have the `faccessat' function. */
+#undef HAVE_FACCESSAT
+
 /* Define if you have the 'fchdir' function. */
 #undef HAVE_FCHDIR
 
 /* Define to 1 if you have the `fchmod' function. */
 #undef HAVE_FCHMOD
 
+/* Define to 1 if you have the `fchmodat' function. */
+#undef HAVE_FCHMODAT
+
 /* Define to 1 if you have the `fchown' function. */
 #undef HAVE_FCHOWN
 
+/* Define to 1 if you have the `fchownat' function. */
+#undef HAVE_FCHOWNAT
+
 /* Define to 1 if you have the <fcntl.h> header file. */
 #undef HAVE_FCNTL_H
 
 /* Define if you have the 'fdatasync' function. */
 #undef HAVE_FDATASYNC
 
+/* Define to 1 if you have the `fdopendir' function. */
+#undef HAVE_FDOPENDIR
+
 /* Define to 1 if you have the `finite' function. */
 #undef HAVE_FINITE
 
@@ -241,6 +253,9 @@
 /* Define to 1 if you have the `fseeko' function. */
 #undef HAVE_FSEEKO
 
+/* Define to 1 if you have the `fstatat' function. */
+#undef HAVE_FSTATAT
+
 /* Define to 1 if you have the `fstatvfs' function. */
 #undef HAVE_FSTATVFS
 
@@ -259,6 +274,9 @@
 /* Define to 1 if you have the `ftruncate' function. */
 #undef HAVE_FTRUNCATE
 
+/* Define to 1 if you have the `futimesat' function. */
+#undef HAVE_FUTIMESAT
+
 /* Define to 1 if you have the `gai_strerror' function. */
 #undef HAVE_GAI_STRERROR
 
@@ -431,6 +449,9 @@
 /* Define if you have the 'link' function. */
 #undef HAVE_LINK
 
+/* Define to 1 if you have the `linkat' function. */
+#undef HAVE_LINKAT
+
 /* Define to 1 if you have the <linux/netlink.h> header file. */
 #undef HAVE_LINUX_NETLINK_H
 
@@ -461,12 +482,21 @@
 /* Define to 1 if you have the <memory.h> header file. */
 #undef HAVE_MEMORY_H
 
+/* Define to 1 if you have the `mkdirat' function. */
+#undef HAVE_MKDIRAT
+
 /* Define to 1 if you have the `mkfifo' function. */
 #undef HAVE_MKFIFO
 
+/* Define to 1 if you have the `mkfifoat' function. */
+#undef HAVE_MKFIFOAT
+
 /* Define to 1 if you have the `mknod' function. */
 #undef HAVE_MKNOD
 
+/* Define to 1 if you have the `mknodat' function. */
+#undef HAVE_MKNODAT
+
 /* Define to 1 if you have the `mktime' function. */
 #undef HAVE_MKTIME
 
@@ -485,6 +515,9 @@
 /* Define to 1 if you have the `nice' function. */
 #undef HAVE_NICE
 
+/* Define to 1 if you have the `openat' function. */
+#undef HAVE_OPENAT
+
 /* Define to 1 if you have the `openpty' function. */
 #undef HAVE_OPENPTY
 
@@ -497,6 +530,15 @@
 /* Define to 1 if you have the `pause' function. */
 #undef HAVE_PAUSE
 
+/* Define if the OS supports pipe2() */
+#undef HAVE_PIPE2
+
+/* Define if the OS supports pipe2() */
+#undef HAVE_PIPE2
+
+/* Define if the OS supports pipe2() */
+#undef HAVE_PIPE2
+
 /* Define to 1 if you have the `plock' function. */
 #undef HAVE_PLOCK
 
@@ -533,9 +575,15 @@
 /* Define to 1 if you have the `readlink' function. */
 #undef HAVE_READLINK
 
+/* Define to 1 if you have the `readlinkat' function. */
+#undef HAVE_READLINKAT
+
 /* Define to 1 if you have the `realpath' function. */
 #undef HAVE_REALPATH
 
+/* Define to 1 if you have the `renameat' function. */
+#undef HAVE_RENAMEAT
+
 /* Define if you have readline 2.1 */
 #undef HAVE_RL_CALLBACK
 
@@ -599,6 +647,9 @@
 /* Define to 1 if you have the `setpgrp' function. */
 #undef HAVE_SETPGRP
 
+/* Define to 1 if you have the `setpriority' function. */
+#undef HAVE_SETPRIORITY
+
 /* Define to 1 if you have the `setregid' function. */
 #undef HAVE_SETREGID
 
@@ -718,6 +769,9 @@
 /* Define if you have the 'symlink' function. */
 #undef HAVE_SYMLINK
 
+/* Define to 1 if you have the `symlinkat' function. */
+#undef HAVE_SYMLINKAT
+
 /* Define to 1 if you have the `sysconf' function. */
 #undef HAVE_SYSCONF
 
@@ -771,6 +825,9 @@
 /* Define to 1 if you have the <sys/select.h> header file. */
 #undef HAVE_SYS_SELECT_H
 
+/* Define to 1 if you have the <sys/sendfile.h> header file. */
+#undef HAVE_SYS_SENDFILE_H
+
 /* Define to 1 if you have the <sys/socket.h> header file. */
 #undef HAVE_SYS_SOCKET_H
 
@@ -860,6 +917,9 @@
 /* Define to 1 if you have the <unistd.h> header file. */
 #undef HAVE_UNISTD_H
 
+/* Define to 1 if you have the `unlinkat' function. */
+#undef HAVE_UNLINKAT
+
 /* Define to 1 if you have the `unsetenv' function. */
 #undef HAVE_UNSETENV
 
@@ -871,6 +931,9 @@
 /* Define to 1 if you have the <util.h> header file. */
 #undef HAVE_UTIL_H
 
+/* Define to 1 if you have the `utimensat' function. */
+#undef HAVE_UTIMENSAT
+
 /* Define to 1 if you have the `utimes' function. */
 #undef HAVE_UTIMES
 
@@ -911,6 +974,9 @@
 /* Define if you are using Mach cthreads directly under /include */
 #undef HURD_C_THREADS
 
+/* Define if log1p(-0.) is 0. rather than -0. */
+#undef LOG1P_DROPS_ZERO_SIGN
+
 /* Define if you are using Mach cthreads under mach / */
 #undef MACH_C_THREADS
 
@@ -1018,6 +1084,9 @@
 /* The size of `size_t', as computed by sizeof. */
 #undef SIZEOF_SIZE_T
 
+/* Define to 1 if you have the `sendfile' function. */
+#undef HAVE_SENDFILE
+
 /* The size of `time_t', as computed by sizeof. */
 #undef SIZEOF_TIME_T
 
@@ -1146,6 +1215,9 @@
 /* This must be defined on some systems to enable large file support. */
 #undef _LARGEFILE_SOURCE
 
+/* This must be defined on AIX systems to enable large file support. */
+#undef _LARGE_FILES
+
 /* Define to 1 if on MINIX. */
 #undef _MINIX
 

Deleted: python/branches/pep-3151/runtests.sh
==============================================================================
--- python/branches/pep-3151/runtests.sh	Sat Feb 26 08:16:32 2011
+++ (empty file)
@@ -1,93 +0,0 @@
-#!/bin/bash
-
-HELP="Usage: ./runtests.py [-h] [-x] [flags] [tests]
-
-Runs each unit test independently, with output directed to a file in
-OUT/<test>.out.  If no tests are given, all tests are run; otherwise,
-only the specified tests are run, unless -x is also given, in which
-case all tests *except* those given are run.
-
-Standard output shows the name of the tests run, with 'BAD' or
-'SKIPPED' added if the test didn't produce a positive result.  Also,
-three files are created, named 'BAD', 'GOOD' and 'SKIPPED', to which
-are written the names of the tests categorized by result.
-
-Flags (arguments starting with '-') are passed transparently to
-regrtest.py, except for -x, which is processed here."
-
-# Choose the Python binary.
-case `uname` in
-Darwin) PYTHON=./python.exe;;
-CYGWIN*) PYTHON=./python.exe;;
-*)      PYTHON=./python;;
-esac
-
-PYTHON="$PYTHON -bb"
-
-# Unset PYTHONPATH, just to be sure.
-unset PYTHONPATH
-
-# Create the output directory if necessary.
-mkdir -p OUT
-
-# Empty the summary files.
->GOOD
->BAD
->SKIPPED
-
-# Process flags (transparently pass these on to regrtest.py)
-FLAGS=""
-EXCEPT=""
-while :
-do
-    case $1 in
-    -h|--h|-help|--help) echo "$HELP"; exit;;
-    --) FLAGS="$FLAGS $1"; shift; break;;
-    -x) EXCEPT="$1"; shift;;
-    -*) FLAGS="$FLAGS $1"; shift;;
-    *)  break;;
-    esac
-done
-
-# Compute the list of tests to run.
-case "$#$EXCEPT" in
-0) 
-    TESTS=`(cd Lib/test; ls test_*.py | sed 's/\.py//')`
-    ;;
-*-x)
-    PAT="^(`echo $@ | sed 's/\.py//g' | sed 's/ /|/g'`)$"
-    TESTS=`(cd Lib/test; ls test_*.py | sed 's/\.py//' | egrep -v "$PAT")`
-    ;;
-*)
-    TESTS="$@"
-    ;;
-esac
-
-# Run the tests.
-for T in $TESTS
-do
-    echo -n $T
-    if   case $T in
-         *curses*)
-	     echo
-	     $PYTHON -E Lib/test/regrtest.py $FLAGS $T 2>OUT/$T.out
-	     ;;
-         *)  $PYTHON -E Lib/test/regrtest.py $FLAGS $T >OUT/$T.out 2>&1;;
-         esac
-    then
-        if grep -q "1 test skipped:" OUT/$T.out
-        then
-            echo " SKIPPED"
-            echo $T >>SKIPPED
-        else
-            echo
-            echo $T >>GOOD
-        fi
-    else
-        echo " BAD"
-        echo $T >>BAD
-    fi
-done
-
-# Summarize results
-wc -l BAD GOOD SKIPPED

Modified: python/branches/pep-3151/setup.py
==============================================================================
--- python/branches/pep-3151/setup.py	(original)
+++ python/branches/pep-3151/setup.py	Sat Feb 26 08:16:32 2011
@@ -14,6 +14,7 @@
 from distutils.command.build_ext import build_ext
 from distutils.command.install import install
 from distutils.command.install_lib import install_lib
+from distutils.command.build_scripts import build_scripts
 from distutils.spawn import find_executable
 
 # Were we compiled --with-pydebug or with #define Py_DEBUG?
@@ -27,11 +28,19 @@
 _BUILDDIR_COOKIE = "pybuilddir.txt"
 
 def add_dir_to_list(dirlist, dir):
-    """Add the directory 'dir' to the list 'dirlist' (at the front) if
+    """Add the directory 'dir' to the list 'dirlist' (after any relative
+    directories) if:
+
     1) 'dir' is not already in 'dirlist'
-    2) 'dir' actually exists, and is a directory."""
-    if dir is not None and os.path.isdir(dir) and dir not in dirlist:
-        dirlist.insert(0, dir)
+    2) 'dir' actually exists, and is a directory.
+    """
+    if dir is None or not os.path.isdir(dir) or dir in dirlist:
+        return
+    for i, path in enumerate(dirlist):
+        if not os.path.isabs(path):
+            dirlist.insert(i + 1, dir)
+            return
+    dirlist.insert(0, dir)
 
 def macosx_sdk_root():
     """
@@ -362,7 +371,9 @@
         return sys.platform
 
     def detect_modules(self):
-        # Ensure that /usr/local is always used
+        # Ensure that /usr/local is always used, but the local build
+        # directories (i.e. '.' and 'Include') must be first.  See issue
+        # 10520.
         add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib')
         add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
 
@@ -437,9 +448,10 @@
             # This should work on any unixy platform ;-)
             # If the user has bothered specifying additional -I and -L flags
             # in OPT and LDFLAGS we might as well use them here.
-            #   NOTE: using shlex.split would technically be more correct, but
-            # also gives a bootstrap problem. Let's hope nobody uses directories
-            # with whitespace in the name to store libraries.
+            #
+            # NOTE: using shlex.split would technically be more correct, but
+            # also gives a bootstrap problem. Let's hope nobody uses
+            # directories with whitespace in the name to store libraries.
             cflags, ldflags = sysconfig.get_config_vars(
                     'CFLAGS', 'LDFLAGS')
             for item in cflags.split():
@@ -624,7 +636,7 @@
             libs = ['crypt']
         else:
             libs = []
-        exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
+        exts.append( Extension('_crypt', ['_cryptmodule.c'], libraries=libs) )
 
         # CSV files
         exts.append( Extension('_csv', ['_csv.c']) )
@@ -1568,6 +1580,10 @@
 ##         # Uncomment these lines if you want to play with xxmodule.c
 ##         ext = Extension('xx', ['xxmodule.c'])
 ##         self.extensions.append(ext)
+        if 'd' not in sys.abiflags:
+            ext = Extension('xxlimited', ['xxlimited.c'],
+                            define_macros=[('Py_LIMITED_API', 1)])
+            self.extensions.append(ext)
 
         # XXX handle these, but how to detect?
         # *** Uncomment and edit for PIL (TkImaging) extension only:
@@ -1777,6 +1793,25 @@
     def is_chmod_supported(self):
         return hasattr(os, 'chmod')
 
+class PyBuildScripts(build_scripts):
+    def copy_scripts(self):
+        outfiles, updated_files = build_scripts.copy_scripts(self)
+        fullversion = '-{0[0]}.{0[1]}'.format(sys.version_info)
+        minoronly = '.{0[1]}'.format(sys.version_info)
+        newoutfiles = []
+        newupdated_files = []
+        for filename in outfiles:
+            if filename.endswith('2to3'):
+                newfilename = filename + fullversion
+            else:
+                newfilename = filename + minoronly
+            log.info('renaming {} to {}'.format(filename, newfilename))
+            os.rename(filename, newfilename)
+            newoutfiles.append(newfilename)
+            if filename in updated_files:
+                newupdated_files.append(newfilename)
+        return newoutfiles, newupdated_files
+
 SUMMARY = """
 Python is an interpreted, interactive, object-oriented programming
 language. It is often compared to Tcl, Perl, Scheme or Java.
@@ -1822,12 +1857,17 @@
           platforms = ["Many"],
 
           # Build info
-          cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall,
-                      'install_lib':PyBuildInstallLib},
+          cmdclass = {'build_ext': PyBuildExt,
+                      'build_scripts': PyBuildScripts,
+                      'install': PyBuildInstall,
+                      'install_lib': PyBuildInstallLib},
           # The struct module is defined here, because build_ext won't be
           # called unless there's at least one extension module defined.
           ext_modules=[Extension('_struct', ['_struct.c'])],
 
+          # If you change the scripts installed here, you also need to
+          # check the PyBuildScripts command above, and change the links
+          # created by the bininstall target in Makefile.pre.in
           scripts = ["Tools/scripts/pydoc3", "Tools/scripts/idle3",
                      "Tools/scripts/2to3"]
         )


More information about the Python-checkins mailing list